问:
Angular 2 Get width of a div
I've looked at numerous posts but none quite do what I want it to do.
I have a table which goes outside the width of the page and for various reasons I need to get it's width.

I used:

```<code>@ViewChild('tableToMeasure') elementView: ElementRef;
</code>```

And then put #tableToMeasure on the table. However this seems to error:

```<code>ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
</code>```

Even though this works on and only on the parent div of the page.

Any ideas? I need to get it's width on both page load and page resize and change another divs width to be the same value.

答:
I had the same problem. The solution I found was actually fairly easily; it returns undefined because in your HTML file there is nothing defined as 'tableToMeasure'.

Therefore you have to add #tableToMeasure to your HTML element.

Example code HTML file:

```<code><div #tableToMeasure style="width: 100px; height: 100px">
   <span>Some content!</span
</div>
</code>```

And in your TypeScript file:

```<code>@ViewChild('tableToMeasure')elementView: ElementRef;
</code>```

Make sure to import ViewChild and ElementRef from @angular/core.

Good luck!

Title: Angular 2 Get width of a div

Body:
I've looked at numerous posts but none quite do what I want it to do.
I have a table which goes outside the width of the page and for various reasons I need to get it's width.

I used:

@ViewChild('tableToMeasure') elementView: ElementRef;

And then put #tableToMeasure on the table. However this seems to error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined

Even though this works on and only on the parent div of the page.

Any ideas? I need to get it's width on both page load and page resize and change another divs width to be the same value.

Body:
I had the same problem. The solution I found was actually fairly easily; it returns undefined because in your HTML file there is nothing defined as 'tableToMeasure'.

Therefore you have to add #tableToMeasure to your HTML element.

Example code HTML file:

<div #tableToMeasure style="width: 100px; height: 100px">
   <span>Some content!</span
</div>

And in your TypeScript file:

@ViewChild('tableToMeasure')elementView: ElementRef;

Make sure to import ViewChild and ElementRef from @angular/core.

Good luck!


来源: stackexchange

问:
How to send mail with attachment in JavaScript via Gmail API
I'm trying to send a mail with attachment via Gmail API.

I'm successfully sending my mail as specified below:

```<code>function sendmail(to, subject, message) {
    var email =
        "To: " + to + "\r\n" +
        "Subject: " + subject + "\r\n" +
        'Content-Transfer-Encoding: 8bit\r\n' +
        'Content-Type: text/html; charset="UTF-8"\r\n' +
        "" +
        message + "\r\n\r\n";
    var sendRequest = gapi.client.gmail.users.messages.send({
        'userId': 'me',
        'resource': {
            'raw': window.btoa(unescape(encodeURIComponent(email))).replace(/\+/g, '-').replace(/\//g, '_')
        }
    });

    sendRequest.execute();
}
</code>```

Now I want to send some file as attachment and tried it in following way:

```<code><input id="inputFile" type="file" onChange="convertToBase64();"/>
<script>
    var file_ = '';

    function convertToBase64() {
        //Read File
        var file = document.getElementById("inputFile").files[0];
        var reader = new FileReader();
        reader.onload = function () {
            file_ = reader.result.split('base64,')[1];
        };
        reader.onerror = function (error) {
            console.log('Error: ', error);
        };
        reader.readAsDataURL(file);
    }

    function sendmail(to, subject, message, date) {
        console.log(date);

        if (typeof file_ !== "undefined" && file_ != '') {
            var email =
                "To: " + to + "\r\n" +
                "Subject: " + subject + "\r\n" +
                'Content-Transfer-Encoding: 8bit\r\n' +
                'Content-Type: text/html; charset="UTF-8"\r\n' +
                "" +
                message +
                "\r\n\r\n" +
                "--foo_bar_baz\r\n" +
                "Content-Type: application/pdf\r\n" +
                "MIME-Version: 1.0\r\n" +
                "Content-Disposition: attachment; filename=example.pdf\r\n\r\n" +
                file_ + "\r\n\r\n";
            var sendRequest = gapi.client.gmail.users.messages.send({
                'userId': 'me',
                'resource': {
                    'raw': window.btoa(unescape(encodeURIComponent(email))).replace(/\+/g, '-').replace(/\//g, '_')
                }
            });

            sendRequest.execute();
        } else {
            alert('boo');
        }
    }
</script>
</code>```

And I would receive the mail BUT I see no text and cannot open the file because of 'bad coding!'.

I did check the whole gmail documentation but without avail.

Could somebody please help me out?

答:
Have you tried: Content-Transfer-Encoding: base64

I read somewhere that encoding pdf's as base64 require you to set the content transfer encoding accordingly.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to send a mail with attachment via Gmail API.

I'm successfully sending my mail as specified below:

function sendmail(to, subject, message) {
    var email =
        "To: " + to + "\r\n" +
        "Subject: " + subject + "\r\n" +
        'Content-Transfer-Encoding: 8bit\r\n' +
        'Content-Type: text/html; charset="UTF-8"\r\n' +
        "" +
        message + "\r\n\r\n";
    var sendRequest = gapi.client.gmail.users.messages.send({
        'userId': 'me',
        'resource': {
            'raw': window.btoa(unescape(encodeURIComponent(email))).replace(/\+/g, '-').replace(/\//g, '_')
        }
    });

    sendRequest.execute();
}

Now I want to send some file as attachment and tried it in following way:

<input id="inputFile" type="file" onChange="convertToBase64();"/>

And I would receive the mail BUT I see no text and cannot open the file because of 'bad coding!'.

I did check the whole gmail documentation but without avail.

Could somebody please help me out?


问:
Xamarin Location Service OnLocationChanged dont trigger
We have one problem where it happen randomly on certain devices which is the OnLocationChanged event cannot be triggered.

```<code>LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, 30000, 100, this);
LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 30000, 100, this);
</code>```

We also try set a timer, if after a minute, the event didn't trigger, we will try get the last known location, but it still returning null.

```<code> CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.GpsProvider);
            LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, this);

            if (CurrentLocation == null)//network provider
            {
                CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
                LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 0, 0, this);
            }

            if (CurrentLocation == null)//passive provider
            {
                CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.PassiveProvider);
                LocationManager.RequestLocationUpdates(LocationManager.PassiveProvider, 0, 0, this);
            }
</code>```

May I know what wrong with my code ?

Edited (Complete Code) :

```<code>public class LocationService : Service, ILocationListener
{
    public IBinder Binder { get; private set; }
    public MainActivity MainAC { get { return m_ac; } set { m_ac = value; } }
    public Android.Locations.Location CurrentLocation { get; set; }
    public Android.Locations.LocationManager LocationManager { get; set; }
    public DateTime LastUpdateTime { get; set; }
    public bool IsMockLocation { get; set; }
    public string CurrentAddress { get; set; }
    public string CurrentCity { get; set; }

    private int iUpdateLocationInterval = 30000;// 30sec
    private int iUpdateLocationDistance = 100;// 100meter

    private int iUpdateLocationInterval_LastKnown = 0;// 0sec
    private int iUpdateLocationDistance_LastKnown = 0;// 0meter

    private System.Timers.Timer timerBackground = null;
    private MainActivity m_ac;
    private Lib.GoogleMaps google = new Lib.GoogleMaps();
    private bool bUpdateLocationIntervalUnknown = false;

    public LocationService()
    {
    }

    #region Override Function
    public override void OnCreate()
    {
        base.OnCreate();
    }

    [return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        StartCommandResult result = base.OnStartCommand(intent, flags, startId);

        return result;
    }

    public override void OnDestroy()
    {
        Binder = null;

        if (LocationManager != null)
        {
            LocationManager.RemoveUpdates(this);
        }

        base.OnDestroy();
    }

    public override IBinder OnBind(Intent intent)
    {
        // Return the communication channel to the service.

        this.Binder = new LocalLocationBinder(this);
        return this.Binder;
    }
    #endregion

    private void StartBackgroundTimer()
    {
        timerBackground = new System.Timers.Timer();
        timerBackground.Elapsed -= TimerBackground_Elapsed;
        timerBackground.Elapsed += TimerBackground_Elapsed;
        timerBackground.Interval = 10000;
        timerBackground.AutoReset = false;
        timerBackground.Enabled = true;
    }

    private void TimerBackground_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        timerBackground.Enabled = false;

        try
        {
            if (CurrentLocation == null)// OnLocationChanged didnt trigger, so get from last known location
            {
                GetLastKnownLocation();
            }
        }
        catch { }
    }

    public void GetLastKnownLocation()
    {
        m_ac.RunOnUiThread(() =>
        {
            bUpdateLocationIntervalUnknown = true;
            CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.GpsProvider);
            LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);

            if (CurrentLocation == null)//network provider
            {
                CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
                LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);
            }

            if (CurrentLocation == null)//passive provider
            {
                CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.PassiveProvider);
                LocationManager.RequestLocationUpdates(LocationManager.PassiveProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);
            }

            if (CurrentLocation != null)
            {
                UpdateCurrentLocationInterval();
                ResolveGPSCoordinates(CurrentLocation);
            }
            else
            {
                m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceGetFailure));
            }
        });
    }

    // Location GPS
    public  void InitializeLocationManager()
    {
        try
        {
            m_ac.RunOnUiThread(() =>
            {
                try
                {
                    if (LocationManager != null) return;

                    LocationManager = (LocationManager)GetSystemService(LocationService);
                    Criteria criteriaForLocationService = new Criteria
                    {
                        Accuracy = Accuracy.Fine
                    };
                    IList<string> acceptableLocationProviders = LocationManager.GetProviders(criteriaForLocationService, true);

                    if (!LocationManager.IsProviderEnabled(LocationManager.GpsProvider))
                    {
                        m_ac.ShowMessageToast(Function.GetLanguage(this, Resource.String.lblGPSLocationIsNotEnabled));
                        return;
                    }

                    if (acceptableLocationProviders.Any())
                    {
                        StartBackgroundTimer();
                        LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
                        LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
                    }
                    else
                    {
                        m_ac.ShowMessageToast(Function.GetLanguage(this, Resource.String.lblGPSLocationIsNotEnabled));
                    }
                }
                catch(Exception ex) { m_ac.ShowMessageToast("ERROR:" + ex.Message); }
            });

        }
        catch (Exception ex) { m_ac.ShowMessageToast("ERROR:" + ex.Message); }
    }

    private void UpdateCurrentLocationInterval()
    {
        try
        {
            if (LocationManager != null)
            {
                bUpdateLocationIntervalUnknown = false ;
                LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
                LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
            }
        }
        catch { }
    }

    public void OnLocationChanged(Location location)
    {
        LastUpdateTime = DateTime.Now;
        IsMockLocation = true;
        CurrentLocation = location;
        CurrentAddress = string.Empty;
        CurrentCity = string.Empty;

        if (bUpdateLocationIntervalUnknown)
        {
            UpdateCurrentLocationInterval();
        }

        if (location.IsFromMockProvider)
        {
            CurrentLocation = null;
            m_ac.UpdateLocationName(CurrentCity);
        }
        else
        {
            IsMockLocation = false;

            ResolveGPSCoordinates(location);
        }
    }

    private void ResolveGPSCoordinates(Location location)
    {
        ResolveGPSCoordinatesAwait(location);
    }

    private async void ResolveGPSCoordinatesAwait(Location location)
    {
        int iResult = await google.ResolveLatLng(location.Latitude, location.Longitude);

        if (iResult == 0)
        {
            CurrentAddress = google.AddressName;
            CurrentCity = google.CityName;

            if(CurrentCity == string.Empty)
                m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceGetFailure));
            else
                m_ac.UpdateLocationName(CurrentCity);
        }
        else if (iResult == -2)
        {
            m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceExceedAPIQuota));
        }
        else
        {
            if (string.IsNullOrEmpty(google.APIErrorMessage))
            {
                m_ac.UpdateLocationName("ERROR:" + location.Latitude + "," + location.Longitude );
            }
            else
            {
                m_ac.UpdateLocationName(google.APIErrorMessage);
            }
        }
    }

    public void OnProviderDisabled(string provider)
    {
        if (provider.Equals(LocationManager.GpsProvider, StringComparison.InvariantCultureIgnoreCase))
        {
            LastUpdateTime = DateTime.Now;
            IsMockLocation = false;
            CurrentLocation = null;
            CurrentAddress = string.Empty;
            CurrentCity = Function.GetLanguage(m_ac, Resource.String.lblLocationServiceDisable);

            m_ac.UpdateLocationName(CurrentCity);
        }
    }

    public void OnProviderEnabled(string provider)
    {
        UpdateCurrentLocationInterval();
    }

    public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
    {

    }

}

public class LocationServiceConnection : Java.Lang.Object, IServiceConnection
{
    MainActivity m_ac = null;

    public LocationServiceConnection(MainActivity activity)
    {
        m_ac = activity;
        IsConnected = false;
        Binder = null;
    }

    public bool IsConnected { get; private set; }
    public LocalLocationBinder Binder { get; private set; }

    public void OnServiceConnected(ComponentName name, IBinder service)
    {
        Binder = service as LocalLocationBinder;
        IsConnected = this.Binder != null;
        Binder.Service.MainAC = m_ac;
        Binder?.Service.InitializeLocationManager();
    }

    public void OnServiceDisconnected(ComponentName name)
    {
        IsConnected = false;
        Binder.Service.MainAC = null;
        Binder = null;
    }

    public void GetLastKnownLocation()
    {
        Binder?.Service.GetLastKnownLocation();
    }

}

#region LocalBinder
public class LocalLocationBinder : Binder
{
    public LocalLocationBinder(LocationService service)
    {
        this.Service = service;
    }

    public LocationService Service { get; private set; }
}
#endregion
</code>```

答:
Well I would suggest you check if the location services are provided and by that I mean are they turned on if not doing that would solve the issue also what you can do is if these services are not available or you can say are currently declined you can simply use this to check if it's available or not and in that way apply your own code to it which could determine if you continue forward to the maps page or not.

```<code> public class LocationEnabled : Fragment
{
    public GoogleApiClient googleApiClient;
  //  static int REQUEST_LOCATION = 199;
    public const int MIN_TIME_BW_UPDATES = 1000 * 3;
    public const int REQUEST_CHECK_SETTINGS = 9000;
    AppCompatActivity _activity;
    public LocationEnabled(AppCompatActivity activity)
    {
        _activity = activity;
    }
    private bool hasGPSDevice(Context context)
    {
        LocationManager mgr = (LocationManager)context.GetSystemService(Context.LocationService);
        if (mgr == null)
            return false;
        IList<string> providers = mgr.AllProviders;
        if (providers == null)
            return false;
        return providers.Contains(LocationManager.GpsProvider);
    }
    private async void enableLoc()
    {
        if (googleApiClient == null)
        {
            googleApiClient = new GoogleApiClient.Builder(_activity)
             .AddApi(LocationServices.API)
             .AddConnectionCallbacks(new CallBackHelper(googleApiClient))
             .AddOnConnectionFailedListener(new ConnectionFailedCallBack(_activity)).Build();

            googleApiClient.Connect();

            LocationRequest locationRequest = LocationRequest.Create();
            locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
            locationRequest.SetInterval(MIN_TIME_BW_UPDATES);
            locationRequest.SetFastestInterval(MIN_TIME_BW_UPDATES/2);

            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
              .AddLocationRequest(locationRequest);
            builder.SetAlwaysShow(true);

            LocationSettingsResult locationSettingsResult =
             await LocationServices.SettingsApi.CheckLocationSettingsAsync(googleApiClient, builder.Build());

            switch (locationSettingsResult.Status.StatusCode)
            {
                case LocationSettingsStatusCodes.Success:
                    Toast.MakeText(_activity, "SUCCESS", ToastLength.Short).Show();
                    break;

                case LocationSettingsStatusCodes.ResolutionRequired:
                    try
                    {
                        locationSettingsResult.Status.StartResolutionForResult(_activity, REQUEST_CHECK_SETTINGS);
                    }
                    catch (Exception e)
                    {
                        Toast.MakeText(_activity, "CANCEL: " + e.Message, ToastLength.Short).Show();
                    }
                    break;

                default:
                    googleApiClient.Disconnect();
                    break;
            }
        }
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        LocationManager manager = (LocationManager)_activity.GetSystemService(Context.LocationService);
        if (manager.IsProviderEnabled(LocationManager.GpsProvider) && hasGPSDevice(_activity))
        {
            Intent intent = new Intent(_activity, typeof(GoogleMapsActivity));
            StartActivity(intent);
        }
        if (!hasGPSDevice(_activity))
        {
              Toast.MakeText(_activity, "Gps not Supported", ToastLength.Long).Show();
        }

        if (!manager.IsProviderEnabled(LocationManager.GpsProvider) && hasGPSDevice(_activity))
        {
            enableLoc();
        }
        else
        {

        }
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return base.OnCreateView(inflater, container, savedInstanceState);
    }
}
public class ConnectionFailedCallBack : Java.Lang.Object, GoogleApiClient.IOnConnectionFailedListener
{
    Context _context;
    public ConnectionFailedCallBack(Context context)
    {
        _context = context;
    }
    public void OnConnectionFailed(ConnectionResult result)
    {
        Toast.MakeText(_context, "Location connection failed.", ToastLength.Short).Show();
    }
}
public class CallBackHelper : Java.Lang.Object, GoogleApiClient.IConnectionCallbacks
{
    GoogleApiClient googleApiClient;
    public CallBackHelper(GoogleApiClient googleApiClient)
    {
        this.googleApiClient = googleApiClient;
    }
    public void OnConnected(Bundle connectionHint)
    {

    }

    public void OnConnectionSuspended(int cause)
    {
        googleApiClient.Connect();
    }
}
</code>```

And get the result on your fragment host activity using this :

```<code>  protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationEnabled.REQUEST_CHECK_SETTINGS)
        {
            switch (resultCode)
            {
                case Result.Canceled:
                 //negative result
                    break;

                case Result.Ok:
               //positive result
                    break;

                case Result.FirstUser:
                default:
                    break;
            }
        }
    }
</code>```

Goodluck!

Body:
We have one problem where it happen randomly on certain devices which is the OnLocationChanged event cannot be triggered.

LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, 30000, 100, this);
LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 30000, 100, this);

We also try set a timer, if after a minute, the event didn't trigger, we will try get the last known location, but it still returning null.

 CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.GpsProvider);
            LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, this);

            if (CurrentLocation == null)//network provider
            {
                CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
                LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 0, 0, this);
            }

            if (CurrentLocation == null)//passive provider
            {
                CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.PassiveProvider);
                LocationManager.RequestLocationUpdates(LocationManager.PassiveProvider, 0, 0, this);
            }

May I know what wrong with my code ?

Edited (Complete Code) :

public class LocationService : Service, ILocationListener
{
    public IBinder Binder { get; private set; }
    public MainActivity MainAC { get { return m_ac; } set { m_ac = value; } }
    public Android.Locations.Location CurrentLocation { get; set; }
    public Android.Locations.LocationManager LocationManager { get; set; }
    public DateTime LastUpdateTime { get; set; }
    public bool IsMockLocation { get; set; }
    public string CurrentAddress { get; set; }
    public string CurrentCity { get; set; }

    private int iUpdateLocationInterval = 30000;// 30sec
    private int iUpdateLocationDistance = 100;// 100meter

    private int iUpdateLocationInterval_LastKnown = 0;// 0sec
    private int iUpdateLocationDistance_LastKnown = 0;// 0meter

    private System.Timers.Timer timerBackground = null;
    private MainActivity m_ac;
    private Lib.GoogleMaps google = new Lib.GoogleMaps();
    private bool bUpdateLocationIntervalUnknown = false;

    public LocationService()
    {
    }

    #region Override Function
    public override void OnCreate()
    {
        base.OnCreate();
    }

    [return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        StartCommandResult result = base.OnStartCommand(intent, flags, startId);

        return result;
    }

    public override void OnDestroy()
    {
        Binder = null;

        if (LocationManager != null)
        {
            LocationManager.RemoveUpdates(this);
        }

        base.OnDestroy();
    }

    public override IBinder OnBind(Intent intent)
    {
        // Return the communication channel to the service.

        this.Binder = new LocalLocationBinder(this);
        return this.Binder;
    }
    #endregion

    private void StartBackgroundTimer()
    {
        timerBackground = new System.Timers.Timer();
        timerBackground.Elapsed -= TimerBackground_Elapsed;
        timerBackground.Elapsed += TimerBackground_Elapsed;
        timerBackground.Interval = 10000;
        timerBackground.AutoReset = false;
        timerBackground.Enabled = true;
    }

    private void TimerBackground_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        timerBackground.Enabled = false;

        try
        {
            if (CurrentLocation == null)// OnLocationChanged didnt trigger, so get from last known location
            {
                GetLastKnownLocation();
            }
        }
        catch { }
    }

    public void GetLastKnownLocation()
    {
        m_ac.RunOnUiThread(() =>
        {
            bUpdateLocationIntervalUnknown = true;
            CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.GpsProvider);
            LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);

            if (CurrentLocation == null)//network provider
            {
                CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
                LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);
            }

            if (CurrentLocation == null)//passive provider
            {
                CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.PassiveProvider);
                LocationManager.RequestLocationUpdates(LocationManager.PassiveProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);
            }

            if (CurrentLocation != null)
            {
                UpdateCurrentLocationInterval();
                ResolveGPSCoordinates(CurrentLocation);
            }
            else
            {
                m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceGetFailure));
            }
        });
    }

    // Location GPS
    public  void InitializeLocationManager()
    {
        try
        {
            m_ac.RunOnUiThread(() =>
            {
                try
                {
                    if (LocationManager != null) return;

                    LocationManager = (LocationManager)GetSystemService(LocationService);
                    Criteria criteriaForLocationService = new Criteria
                    {
                        Accuracy = Accuracy.Fine
                    };
                    IList<string> acceptableLocationProviders = LocationManager.GetProviders(criteriaForLocationService, true);

                    if (!LocationManager.IsProviderEnabled(LocationManager.GpsProvider))
                    {
                        m_ac.ShowMessageToast(Function.GetLanguage(this, Resource.String.lblGPSLocationIsNotEnabled));
                        return;
                    }

                    if (acceptableLocationProviders.Any())
                    {
                        StartBackgroundTimer();
                        LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
                        LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
                    }
                    else
                    {
                        m_ac.ShowMessageToast(Function.GetLanguage(this, Resource.String.lblGPSLocationIsNotEnabled));
                    }
                }
                catch(Exception ex) { m_ac.ShowMessageToast("ERROR:" + ex.Message); }
            });

        }
        catch (Exception ex) { m_ac.ShowMessageToast("ERROR:" + ex.Message); }
    }

    private void UpdateCurrentLocationInterval()
    {
        try
        {
            if (LocationManager != null)
            {
                bUpdateLocationIntervalUnknown = false ;
                LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
                LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
            }
        }
        catch { }
    }

    public void OnLocationChanged(Location location)
    {
        LastUpdateTime = DateTime.Now;
        IsMockLocation = true;
        CurrentLocation = location;
        CurrentAddress = string.Empty;
        CurrentCity = string.Empty;

        if (bUpdateLocationIntervalUnknown)
        {
            UpdateCurrentLocationInterval();
        }

        if (location.IsFromMockProvider)
        {
            CurrentLocation = null;
            m_ac.UpdateLocationName(CurrentCity);
        }
        else
        {
            IsMockLocation = false;

            ResolveGPSCoordinates(location);
        }
    }

    private void ResolveGPSCoordinates(Location location)
    {
        ResolveGPSCoordinatesAwait(location);
    }

    private async void ResolveGPSCoordinatesAwait(Location location)
    {
        int iResult = await google.ResolveLatLng(location.Latitude, location.Longitude);

        if (iResult == 0)
        {
            CurrentAddress = google.AddressName;
            CurrentCity = google.CityName;

            if(CurrentCity == string.Empty)
                m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceGetFailure));
            else
                m_ac.UpdateLocationName(CurrentCity);
        }
        else if (iResult == -2)
        {
            m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceExceedAPIQuota));
        }
        else
        {
            if (string.IsNullOrEmpty(google.APIErrorMessage))
            {
                m_ac.UpdateLocationName("ERROR:" + location.Latitude + "," + location.Longitude );
            }
            else
            {
                m_ac.UpdateLocationName(google.APIErrorMessage);
            }
        }
    }

    public void OnProviderDisabled(string provider)
    {
        if (provider.Equals(LocationManager.GpsProvider, StringComparison.InvariantCultureIgnoreCase))
        {
            LastUpdateTime = DateTime.Now;
            IsMockLocation = false;
            CurrentLocation = null;
            CurrentAddress = string.Empty;
            CurrentCity = Function.GetLanguage(m_ac, Resource.String.lblLocationServiceDisable);

            m_ac.UpdateLocationName(CurrentCity);
        }
    }

    public void OnProviderEnabled(string provider)
    {
        UpdateCurrentLocationInterval();
    }

    public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
    {

    }

}

public class LocationServiceConnection : Java.Lang.Object, IServiceConnection
{
    MainActivity m_ac = null;

    public LocationServiceConnection(MainActivity activity)
    {
        m_ac = activity;
        IsConnected = false;
        Binder = null;
    }

    public bool IsConnected { get; private set; }
    public LocalLocationBinder Binder { get; private set; }

    public void OnServiceConnected(ComponentName name, IBinder service)
    {
        Binder = service as LocalLocationBinder;
        IsConnected = this.Binder != null;
        Binder.Service.MainAC = m_ac;
        Binder?.Service.InitializeLocationManager();
    }

    public void OnServiceDisconnected(ComponentName name)
    {
        IsConnected = false;
        Binder.Service.MainAC = null;
        Binder = null;
    }

    public void GetLastKnownLocation()
    {
        Binder?.Service.GetLastKnownLocation();
    }

}

#region LocalBinder
public class LocalLocationBinder : Binder
{
    public LocalLocationBinder(LocationService service)
    {
        this.Service = service;
    }

    public LocationService Service { get; private set; }
}
#endregion

Body:
Well I would suggest you check if the location services are provided and by that I mean are they turned on if not doing that would solve the issue also what you can do is if these services are not available or you can say are currently declined you can simply use this to check if it's available or not and in that way apply your own code to it which could determine if you continue forward to the maps page or not.

 public class LocationEnabled : Fragment
{
    public GoogleApiClient googleApiClient;
  //  static int REQUEST_LOCATION = 199;
    public const int MIN_TIME_BW_UPDATES = 1000 * 3;
    public const int REQUEST_CHECK_SETTINGS = 9000;
    AppCompatActivity _activity;
    public LocationEnabled(AppCompatActivity activity)
    {
        _activity = activity;
    }
    private bool hasGPSDevice(Context context)
    {
        LocationManager mgr = (LocationManager)context.GetSystemService(Context.LocationService);
        if (mgr == null)
            return false;
        IList<string> providers = mgr.AllProviders;
        if (providers == null)
            return false;
        return providers.Contains(LocationManager.GpsProvider);
    }
    private async void enableLoc()
    {
        if (googleApiClient == null)
        {
            googleApiClient = new GoogleApiClient.Builder(_activity)
             .AddApi(LocationServices.API)
             .AddConnectionCallbacks(new CallBackHelper(googleApiClient))
             .AddOnConnectionFailedListener(new ConnectionFailedCallBack(_activity)).Build();

            googleApiClient.Connect();

            LocationRequest locationRequest = LocationRequest.Create();
            locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
            locationRequest.SetInterval(MIN_TIME_BW_UPDATES);
            locationRequest.SetFastestInterval(MIN_TIME_BW_UPDATES/2);

            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
              .AddLocationRequest(locationRequest);
            builder.SetAlwaysShow(true);

            LocationSettingsResult locationSettingsResult =
             await LocationServices.SettingsApi.CheckLocationSettingsAsync(googleApiClient, builder.Build());

            switch (locationSettingsResult.Status.StatusCode)
            {
                case LocationSettingsStatusCodes.Success:
                    Toast.MakeText(_activity, "SUCCESS", ToastLength.Short).Show();
                    break;

                case LocationSettingsStatusCodes.ResolutionRequired:
                    try
                    {
                        locationSettingsResult.Status.StartResolutionForResult(_activity, REQUEST_CHECK_SETTINGS);
                    }
                    catch (Exception e)
                    {
                        Toast.MakeText(_activity, "CANCEL: " + e.Message, ToastLength.Short).Show();
                    }
                    break;

                default:
                    googleApiClient.Disconnect();
                    break;
            }
        }
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        LocationManager manager = (LocationManager)_activity.GetSystemService(Context.LocationService);
        if (manager.IsProviderEnabled(LocationManager.GpsProvider) && hasGPSDevice(_activity))
        {
            Intent intent = new Intent(_activity, typeof(GoogleMapsActivity));
            StartActivity(intent);
        }
        if (!hasGPSDevice(_activity))
        {
              Toast.MakeText(_activity, "Gps not Supported", ToastLength.Long).Show();
        }

        if (!manager.IsProviderEnabled(LocationManager.GpsProvider) && hasGPSDevice(_activity))
        {
            enableLoc();
        }
        else
        {

        }
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return base.OnCreateView(inflater, container, savedInstanceState);
    }
}
public class ConnectionFailedCallBack : Java.Lang.Object, GoogleApiClient.IOnConnectionFailedListener
{
    Context _context;
    public ConnectionFailedCallBack(Context context)
    {
        _context = context;
    }
    public void OnConnectionFailed(ConnectionResult result)
    {
        Toast.MakeText(_context, "Location connection failed.", ToastLength.Short).Show();
    }
}
public class CallBackHelper : Java.Lang.Object, GoogleApiClient.IConnectionCallbacks
{
    GoogleApiClient googleApiClient;
    public CallBackHelper(GoogleApiClient googleApiClient)
    {
        this.googleApiClient = googleApiClient;
    }
    public void OnConnected(Bundle connectionHint)
    {

    }

    public void OnConnectionSuspended(int cause)
    {
        googleApiClient.Connect();
    }
}

And get the result on your fragment host activity using this :

  protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationEnabled.REQUEST_CHECK_SETTINGS)
        {
            switch (resultCode)
            {
                case Result.Canceled:
                 //negative result
                    break;

                case Result.Ok:
               //positive result
                    break;

                case Result.FirstUser:
                default:
                    break;
            }
        }
    }

Goodluck!


问:
ES6 Display div to none when button is clicked
I'm new at ES6 and I'm trying to display to none a div when an inner button is clicked.

I tried this but it's not working:

const hide = () => {
  const z = document.getElementById('button')
  const y = document.getElementById('block')
  z.onclick = () => {
    y.style.display='none'
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="block">
  <button id="button" onClick="hide()">my button</button>
</div></code>```

Any help please?

答:
Instead of hiding the div, your hide method is assigning a new onclick handler to your button.

Simply

```<code>const hide = () => {
    document.getElementById('block').style.display='none'
  }
</code>```

Body:
I'm new at ES6 and I'm trying to display to none a div when an inner button is clicked.

I tried this but it's not working:

const hide = () => {
  const z = document.getElementById('button')
  const y = document.getElementById('block')
  z.onclick = () => {
    y.style.display='none'
  }
}

  <button id="button" onClick="hide()">my button</button>

Any help please?

Body:
Instead of hiding the div, your hide method is assigning a new onclick handler to your button.

Simply

const hide = () => {
    document.getElementById('block').style.display='none'
  }


问:
Include files didnt show inside echo query
Why my included file didn't show? even the theme is read the directory and it is working if I didn't put inside echo.. How can I fixed this?</p>

```<code> <?php
 require_once('config.php');
 blalal...
 echo "<?php include('theme/" . $row["themes"]. "/editor/index.php'); ?>"; } } else { echo ""; } $conn->close(); ?>
</code>```

答:
You should include file like this:</p>

```<code><?php
require_once('config.php');

if () {
    if () {

        include('theme/' . $row["themes"]. '/editor/index.php');

    }
} else {

    echo "";

}

$conn->close();

?>
</code>```

Body:
Why my included file didn't show? even the theme is read the directory and it is working if I didn't put inside echo.. How can I fixed this?

 <?php
 require_once('config.php');
 blalal...
 echo "<?php include('theme/" . $row["themes"]. "/editor/index.php'); ?>"; } } else { echo ""; } $conn->close(); ?>

Body:
You should include file like this:

<?php
require_once('config.php');

if () {
    if () {

        include('theme/' . $row["themes"]. '/editor/index.php');

    }
} else {

    echo "";

}

$conn->close();

?>


问:
java.lang.OutOfMemoryError when calling getDrawable()
I get the following out of memory error and I'm not sure why.

```<code>Failed to allocate a 1860508 byte allocation with 905740 free bytes and 884KB until OOM

java.lang.OutOfMemoryError: Failed to allocate a 1860508 byte allocation with 905740 free bytes and 884KB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:837)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:656)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1037)

at android.content.res.Resources.loadDrawableForCookie(Resources.java:4056)
at android.content.res.Resources.loadDrawable(Resources.java:3929)
at android.content.res.Resources.getDrawable(Resources.java:1991)
at android.content.res.Resources.getDrawable(Resources.java:1973)
at android.graphics.drawable.LevelListDrawable.inflate(LevelListDrawable.java:128)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1192)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1086)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:4045)
at android.content.res.Resources.loadDrawable(Resources.java:3929)
at android.content.res.Resources.getDrawable(Resources.java:1991)
at android.content.res.Resources.getDrawable(Resources.java:1973)
at android.content.Context.getDrawable(Context.java:409)
at com.MyCompany.MyApp.Login.updateWifiStatus(Login.java:942)
at com.MyCompany.MyApp.Login$6.run(Login.java:576)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6939)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
</code>```

I am using a 5 level resource to indicate wifi status and here is the code I'm using

```<code>    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    // Level of current connection
    int rssi = wifiManager.getConnectionInfo().getRssi();
    int level = WifiManager.calculateSignalLevel(rssi, 5);
    Drawable db = getDrawable(R.drawable.stat_sys_wifi_signal);
    db.setLevel(level);
    wifiMenu.setIcon(db);
</code>```

The images are all the same size (512x512).

In reference to other answers out there I have got largeheap in my manifest.

Any help would be greatly appreciated.

答:
Use TinyPNG

TinyPNG uses smart lossy compression techniques to reduce the file
  size of your PNG files. By selectively decreasing the number of colors
  in the image, fewer bytes are required to store the data. The effect
  is nearly invisible but it makes a very large difference in file size!

Compress all images using this link.

Reduce the size of all picture before use in your Android applications.

Make sure you read the document Loading Large Bitmaps Efficiently given by @mudit_sen.

Hope this may help you.

Body:
I get the following out of memory error and I'm not sure why.

Failed to allocate a 1860508 byte allocation with 905740 free bytes and 884KB until OOM

java.lang.OutOfMemoryError: Failed to allocate a 1860508 byte allocation with 905740 free bytes and 884KB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:837)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:656)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1037)

at android.content.res.Resources.loadDrawableForCookie(Resources.java:4056)
at android.content.res.Resources.loadDrawable(Resources.java:3929)
at android.content.res.Resources.getDrawable(Resources.java:1991)
at android.content.res.Resources.getDrawable(Resources.java:1973)
at android.graphics.drawable.LevelListDrawable.inflate(LevelListDrawable.java:128)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1192)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1086)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:4045)
at android.content.res.Resources.loadDrawable(Resources.java:3929)
at android.content.res.Resources.getDrawable(Resources.java:1991)
at android.content.res.Resources.getDrawable(Resources.java:1973)
at android.content.Context.getDrawable(Context.java:409)
at com.MyCompany.MyApp.Login.updateWifiStatus(Login.java:942)
at com.MyCompany.MyApp.Login$6.run(Login.java:576)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6939)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

I am using a 5 level resource to indicate wifi status and here is the code I'm using

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    // Level of current connection
    int rssi = wifiManager.getConnectionInfo().getRssi();
    int level = WifiManager.calculateSignalLevel(rssi, 5);
    Drawable db = getDrawable(R.drawable.stat_sys_wifi_signal);
    db.setLevel(level);
    wifiMenu.setIcon(db);

The images are all the same size (512x512).

In reference to other answers out there I have got largeheap in my manifest.

Any help would be greatly appreciated.


问:
How to make secure route in Laravel 5.2?
I have a application with Laravel 5.2. I have some route. Now i want to make few routes secure so that anyone can not guessing and insert any value.Now i want to add some character before {id} and after {id} So that anyone can't reach it by guessing.

```<code>Route::get('/prize/{id}','PrizeCalculateController@showPrizePage');
</code>```

Now user can go to localhost/laravel/public/prize/1 or replace 1 by anything and can go to that url. I want make it secure so that anyone can't go by guessing.

I have tried with:

```<code>$parameter = $qrcode->id;
$encryption= Crypt::encrypt($parameter);
</code>```

What will be the best approach to make a route secure?

答:
I use this lib to hash IDs: http://hashids.org/php/

Here's my wrapper for Laravel:

```<code>public static function staticHash($number, $obfuscate = false)
{
   $hashids = new \Hashids\Hashids(\Config::get('app.key'));

   return $hashids->encode($number);
}

public static function staticHashDecode($hash, $obfuscate = false)
{
   $hashids = new \Hashids\Hashids(\Config::get('app.key'));
   $number = $hashids->decode($hash);

   if (isset($number[0])) {
      $number = $number[0];
   } else {
      $number = false;
   }

   return $number;
}
</code>```

Body:
I have a application with Laravel 5.2. I have some route. Now i want to make few routes secure so that anyone can not guessing and insert any value.Now i want to add some character before {id} and after {id} So that anyone can't reach it by guessing.

Route::get('/prize/{id}','PrizeCalculateController@showPrizePage');

Now user can go to localhost/laravel/public/prize/1 or replace 1 by anything and can go to that url. I want make it secure so that anyone can't go by guessing.

I have tried with:

$parameter = $qrcode->id;
$encryption= Crypt::encrypt($parameter);

What will be the best approach to make a route secure?

Body:
I use this lib to hash IDs: http://hashids.org/php/

Here's my wrapper for Laravel:

public static function staticHash($number, $obfuscate = false)
{
   $hashids = new \Hashids\Hashids(\Config::get('app.key'));

   return $hashids->encode($number);
}

public static function staticHashDecode($hash, $obfuscate = false)
{
   $hashids = new \Hashids\Hashids(\Config::get('app.key'));
   $number = $hashids->decode($hash);

   if (isset($number[0])) {
      $number = $number[0];
   } else {
      $number = false;
   }

   return $number;
}


问:
How to setup a lock for a read-manipulate-write operation?
Considering the following table

The sequence value is a custom auto increment key combining letters and numbers that a particular client need for his system.

We made a function called GetNextSequence() which should return the next value of the sequence. The step to reading and updating the sequence goes as follow

Read the sequence value using the KeyId: SELECT Sequence FROM [Key] WHERE KeyId = @Id

Parse the sequence value and determine the next value

Write the sequence value to the table: UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id

Here is the C# code (simplified for clarity):

```<code>var transaction = connection.BeginTransaction(IsolationLevel.RepeatableRead);
var currentSequenceValue = SqlUtils.ExecuteScalar(connection, transaction, "SELECT Sequence FROM [Key] WHERE KeyId = @Id", new SqlParameter("@Id", keyId));
var updatedSequenceValue = ParseSequence(currentSequenceValue);
SqlUtils.ExecuteScalar(connection, transaction, "UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id", new SqlParameter("@Id", keyId), new SqlParameter("@Sequence", updatedSequenceValue));
transaction.Commit();
return updatedSequenceValue;
</code>```

Our problem reside in that two different servers can access the same sequence and we end up getting a deadlock

Transaction (Process ID X) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

In C#, I tried to set up different lock combination like a transaction isolation IsolationLevel.RepeatableRead or IsolationLevel.Serializable or in SQL using table hint ROWLOCK and HOLDLOCK, but without success.

I want that each server be able to read, manipulate and update a sequence in a atomic way. What is the proper way to setup a lock for this situation?

答:
I suggest using an exclusive row-level lock for the duration of a transaction (ROWLOCK, XLOCK, HOLDLOCK). Your use of hints etc so far isn't enough.

```<code>BEGIN TRAN
    SELECT Sequence FROM [Key] WITH (ROWLOCK, XLOCK, HOLDLOCK) WHERE KeyId = @Id

    Parse the sequence value and determine the next value

    UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id
COMMIT
</code>```

Although, I'd look at at least reducing scope to a single transaction

```<code>    UPDATE [Key] WITH (ROWLOCK, XLOCK, HOLDLOCK)
    SET Sequence = dbo.scalarudf(...)
    WHERE KeyId = @Id
</code>```

Edit: you don't need HOLDLOCK if you use SERIALIZABLE. And "RepeatableRead" may not be enough because of how ranges are locked

ContentLicense: CC BY-SA 2.5

Body:
Considering the following table

The sequence value is a custom auto increment key combining letters and numbers that a particular client need for his system.

We made a function called GetNextSequence() which should return the next value of the sequence. The step to reading and updating the sequence goes as follow

Read the sequence value using the KeyId: SELECT Sequence FROM [Key] WHERE KeyId = @Id

Parse the sequence value and determine the next value

Write the sequence value to the table: UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id

Here is the C# code (simplified for clarity):

var transaction = connection.BeginTransaction(IsolationLevel.RepeatableRead);
var currentSequenceValue = SqlUtils.ExecuteScalar(connection, transaction, "SELECT Sequence FROM [Key] WHERE KeyId = @Id", new SqlParameter("@Id", keyId));
var updatedSequenceValue = ParseSequence(currentSequenceValue);
SqlUtils.ExecuteScalar(connection, transaction, "UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id", new SqlParameter("@Id", keyId), new SqlParameter("@Sequence", updatedSequenceValue));
transaction.Commit();
return updatedSequenceValue;

Our problem reside in that two different servers can access the same sequence and we end up getting a deadlock

Transaction (Process ID X) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

In C#, I tried to set up different lock combination like a transaction isolation IsolationLevel.RepeatableRead or IsolationLevel.Serializable or in SQL using table hint ROWLOCK and HOLDLOCK, but without success.

I want that each server be able to read, manipulate and update a sequence in a atomic way. What is the proper way to setup a lock for this situation?

Body:
I suggest using an exclusive row-level lock for the duration of a transaction (ROWLOCK, XLOCK, HOLDLOCK). Your use of hints etc so far isn't enough.

BEGIN TRAN
    SELECT Sequence FROM [Key] WITH (ROWLOCK, XLOCK, HOLDLOCK) WHERE KeyId = @Id

    Parse the sequence value and determine the next value

    UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id
COMMIT

Although, I'd look at at least reducing scope to a single transaction

    UPDATE [Key] WITH (ROWLOCK, XLOCK, HOLDLOCK)
    SET Sequence = dbo.scalarudf(...)
    WHERE KeyId = @Id

Edit: you don't need HOLDLOCK if you use SERIALIZABLE. And "RepeatableRead" may not be enough because of how ranges are locked


问:
MySQL geo-spatial query
After some research, it appears that ST_Contains determines whether the second argument is present inside the first argument as a polygon.

What function is available for querying all points inside a polygon from a points table?

答:
Here is an example of spatial query in MySql where I retrieve all points (features to be drawn on a map) inside a rectangle:

```<code>SELECT * FROM `features`
WHERE CONTAINS(GeomFromText('POLYGON((6.71813 45.25942,
7.42126 45.25942,
7.42126 45.02695,
6.71813 45.02695,
6.71813 45.25942))'), coord);
</code>```

field features.coord is of type point (see https://dev.mysql.com/doc/refman/5.7/en/spatial-datatypes.html)

Title: MySQL geo-spatial query

Body:
Here is an example of spatial query in MySql where I retrieve all points (features to be drawn on a map) inside a rectangle:

SELECT * FROM `features`
WHERE CONTAINS(GeomFromText('POLYGON((6.71813 45.25942,
7.42126 45.25942,
7.42126 45.02695,
6.71813 45.02695,
6.71813 45.25942))'), coord);

field features.coord is of type point (see https://dev.mysql.com/doc/refman/5.7/en/spatial-datatypes.html)


问:
Best neural network for certain type of pattern analysis?
I'm working on a system that will send telemetry data on machine operation back to a central server for analysis.  One of the machine parameters we're measuring is motor current drawn vs time.  After an operation is finished we plan to send back an array of currents vs time to the server.  A successful operation would have a pattern like a trapezoid, problematic operations would have a pattern completely different, more like a large spike in values.  Can anyone recommend a type of neural network that would be good at classifying these 1D vectors of current values into a pass/fail type output?

Thanks,
Fred

答: Maybe taking the FFT and passing it through a radial basis function neural network will do the trick. It seems like the features you are looking for are periodic features which will be captured by the FFT, and RBF can do the learning.</p>


问:
C++ declaring multiple classes in one header
I got an assignment where I am supposed to create a Linked list by using CRTP. I got some starting code/suggestion on how to define the classes in their respective header files. I have omitted some code below:

Link.h

```<code>#include <iosfwd>

template<class T>
class List;

template<class T>
class Link {
    Link* next;

    friend class List<T>;

public:
    Link();

    virtual ~Link() = default;
  //etc...
</code>```

List.h

```<code>#include "Link.h"

template<class T>
class List : public Link<T> {
public:
    List();

    T* First();

    T* Last();
    //Etc...
</code>```

This code compiles without any errors. Now my question is about the two first lines in Link.h, template<class T> class List;. I experimented a little bit and realized that Link.h won't compile without that class definition beacuse of the friend class List<T>  statement. But why can't I just write #include "List.h" and remove the inheritance inside List.h and just use that definition from the start? I have tried this of course and get the error

```<code>"error: 'List' is not a class template
     friend class List<T>;"
</code>```

it would look like this:

Link.h

```<code>#include <iosfwd>
#include "List.h"

template<class T>
class Link {
    Link* next;

    friend class List<T>;

public:
    Link();

    virtual ~Link() = default;
</code>```

List.h

```<code>#include "Link.h"

template<class T>
class List {
public:
    List();

    T* First();
</code>```

答: Try to use a unique template in one file only or in files that build upon each other sequentially, not equally. In your case, you should probably move all of your files to one. Your .h files seem to mirror each other, so your compiler would have go back and forth between your references, but they do so in order. Choose the order of precedence. </p>

Body:
I got an assignment where I am supposed to create a Linked list by using CRTP. I got some starting code/suggestion on how to define the classes in their respective header files. I have omitted some code below:

Link.h

#include <iosfwd>

template<class T>
class List;

template<class T>
class Link {
    Link* next;

    friend class List<T>;

public:
    Link();

    virtual ~Link() = default;
  //etc...

List.h

#include "Link.h"

template<class T>
class List : public Link<T> {
public:
    List();

    T* First();

    T* Last();
    //Etc...

This code compiles without any errors. Now my question is about the two first lines in Link.h, template<class T> class List;. I experimented a little bit and realized that Link.h won't compile without that class definition beacuse of the friend class List<T>  statement. But why can't I just write #include "List.h" and remove the inheritance inside List.h and just use that definition from the start? I have tried this of course and get the error

"error: 'List' is not a class template
     friend class List<T>;"

it would look like this:

Link.h

#include <iosfwd>
#include "List.h"

template<class T>
class Link {
    Link* next;

    friend class List<T>;

public:
    Link();

    virtual ~Link() = default;

List.h

#include "Link.h"

template<class T>
class List {
public:
    List();

    T* First();


问:
Bootstrap4- sticky first row and column for grid/flex layout
can anyone give me an idea of how to approach the attached grid/table layout using bootstrap4 flex/grid (must be responsive)?
It's like a table with sticky first row and sticky first column as navigation items.

I tried using w- & h- but it's not responsive without media query. Would like to know the best solution on bootstrap4.

Thanks a lot! :)

(Pardon my English...)

答:
Freeze First Row & First Column

However, to get this behavior for both first row and first column, you need to separate the first row, first column, and first cell from the table, and then continuously set the position of these elements based on the scrolled position of the table body, upon a scroll event.

 $(document).ready(function() {
      $('tbody').scroll(function(e) {
        $('thead').css("left", -$("tbody").scrollLeft());
        $('thead th:nth-child(1)').css("left", $("tbody").scrollLeft()-5);
        $('tbody td:nth-child(1)').css("left", $("tbody").scrollLeft()-5);
      });
    });

   ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
      margin: 0;
    }
    th, td {
        text-align: center;
        background-color: white
    }
    table {
      position: relative;
      width: 400px;
      overflow: hidden;
    }
    thead {
      position: relative;
      display: block;
      width: 400px;
      overflow: visible;
    }
    thead th {
      min-width: 80px;
      height: 40px;
    }
    thead th:nth-child(1) {
      position: relative;
      display: block;
      height: 40px;
      padding-top: 20px;
    }
    tbody {
      position: relative;
      display: block;
      width: 400px;
      height: 90px;
      overflow: scroll;
    }
    tbody td {
      min-width: 80px;
    }
    tbody tr td:nth-child(1) {
      position: relative;
      display: block;
    }</code>```

          ID
          Tanggal
          Judul Pekerjaan
          Deskripsi
          Level
          Category
          Severity

          1
          1 May 2017
          Satu
          Satu
          5
          Lorem
          Ipsum

          2
          2 May 2017
          Dua
          Dua

          3
          3 May 2017
          Tiga
          Tiga

          3
          3 May 2017
          Tiga
          Tiga

          2
          2 May 2017
          Dua
          Dua

          3
          3 May 2017
          Tiga
          Tiga

          3
          3 May 2017
          Tiga
          Tiga

```

Body:
Freeze First Row & First Column

However, to get this behavior for both first row and first column, you need to separate the first row, first column, and first cell from the table, and then continuously set the position of these elements based on the scrolled position of the table body, upon a scroll event.

 $(document).ready(function() {
      $('tbody').scroll(function(e) {
        $('thead').css("left", -$("tbody").scrollLeft());
        $('thead th:nth-child(1)').css("left", $("tbody").scrollLeft()-5);
        $('tbody td:nth-child(1)').css("left", $("tbody").scrollLeft()-5);
      });
    });

body {
      margin: 0;
    }
    th, td {
        text-align: center;
        background-color: white
    }
    table {
      position: relative;
      width: 400px;
      overflow: hidden;
    }
    thead {
      position: relative;
      display: block;
      width: 400px;
      overflow: visible;
    }
    thead th {
      min-width: 80px;
      height: 40px;
    }
    thead th:nth-child(1) {
      position: relative;
      display: block;
      height: 40px;
      padding-top: 20px;
    }
    tbody {
      position: relative;
      display: block;
      width: 400px;
      height: 90px;
      overflow: scroll;
    }
    tbody td {
      min-width: 80px;
    }
    tbody tr td:nth-child(1) {
      position: relative;
      display: block;
    }

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>ID</th>
          <th>Tanggal</th>
          <th>Judul Pekerjaan</th>
          <th>Deskripsi</th>
          <th>Level</th>
          <th>Category</th>
          <th>Severity</th>
        </tr>
      </thead>

      <tbody>
        <tr>
          <td>1</td>
          <td>1 May 2017</td>
          <td>Satu</td>
          <td>Satu</td>
          <td>5</td>
          <td>Lorem</td>
          <td>Ipsum</td>
        </tr>
        <tr>
          <td>2</td>
          <td>2 May 2017</td>
          <td>Dua</td>
          <td>Dua</td>
        </tr>
        <tr>
          <td>3</td>
          <td>3 May 2017</td>
          <td>Tiga</td>
          <td>Tiga</td>
        </tr>
        <tr>
          <td>3</td>
          <td>3 May 2017</td>
          <td>Tiga</td>
          <td>Tiga</td>
        </tr>
        <tr>
          <td>2</td>
          <td>2 May 2017</td>
          <td>Dua</td>
          <td>Dua</td>
        </tr>
        <tr>
          <td>3</td>
          <td>3 May 2017</td>
          <td>Tiga</td>
          <td>Tiga</td>
        </tr>
        <tr>
          <td>3</td>
          <td>3 May 2017</td>
          <td>Tiga</td>
          <td>Tiga</td>
        </tr>
      </tbody>
    </table>


问:
I can convert char to string but not string to char
I am creating a program in C++ to break down a character array that the user enters into individual characters and then to add them to a 2d array. The bits of the keyword are stored in char's j-l. when I try to give the value of the chars to a part of the array it doe not work but when I try to give the value of a part of the array to the chars it works. Someone will probably mention the conflict between string functions and arrays and char variables. Exept for this one little problem the setup works for me and if I try to change it it comes up wih some errors. Is there a simple way to fix this problem without changing the arrays and function to a different type? If not please tell me what to do, I am only a beginner.

```<code>while (key[a] != '\0' ){

while(b <= 4){
        m++;
cipherarray[b][c] = key[a];

 if (m == 1 ) {
</code>```

if I swith this to "cipherarray[b][c] = f;" it works but then cipherarray[b][c] = "q"

```<code>f = cipherarray[b][c];
}

 if ( m == 2 )
 {
g = cipherarray[b][c];
}

 if ( m == 3 )
 {
h = cipherarray[b][c];
}

 if ( m == 4  )
 {
i = cipherarray[b][c];
}

 if ( m == 5 )
{
j = cipherarray[b][c];
}

 if ( m == 6 )
 {
k = cipherarray[b][c];
}

 if ( m == 7 )
 {
l = cipherarray[b][c];
}

a++;
b++;
if (key[a] == 0)
break;
}

if (key[a] != 0){
c++;
b = 0;
}
}
</code>```

By the way this is the error i get:

incompatible types in assignment of std::string to char[2]

答: I just changed al of the chars to strings and the function decalation. I have been slaving over this for so long I could not see how obvious it was to fix.</p>

Body:
I am creating a program in C++ to break down a character array that the user enters into individual characters and then to add them to a 2d array. The bits of the keyword are stored in char's j-l. when I try to give the value of the chars to a part of the array it doe not work but when I try to give the value of a part of the array to the chars it works. Someone will probably mention the conflict between string functions and arrays and char variables. Exept for this one little problem the setup works for me and if I try to change it it comes up wih some errors. Is there a simple way to fix this problem without changing the arrays and function to a different type? If not please tell me what to do, I am only a beginner.

while (key[a] != '\0' ){

while(b <= 4){
        m++;
cipherarray[b][c] = key[a];

 if (m == 1 ) {

if I swith this to "cipherarray[b][c] = f;" it works but then cipherarray[b][c] = "q"

f = cipherarray[b][c];
}

 if ( m == 2 )
 {
g = cipherarray[b][c];
}

 if ( m == 3 )
 {
h = cipherarray[b][c];
}

 if ( m == 4  )
 {
i = cipherarray[b][c];
}

 if ( m == 5 )
{
j = cipherarray[b][c];
}

 if ( m == 6 )
 {
k = cipherarray[b][c];
}

 if ( m == 7 )
 {
l = cipherarray[b][c];
}

a++;
b++;
if (key[a] == 0)
break;
}

if (key[a] != 0){
c++;
b = 0;
}
}

By the way this is the error i get:

incompatible types in assignment of std::string to char[2]


问:
how to clear console data without refreshing the page in chrome
I am reading an ebook, which is about ReactJs,I want to run commands in the same page console but if redeclare the same variable it showing me variable has already been declared

for ex:-

```<code>var pizza = true
pizza = false
console.log(pizza)
</code>```

when i declarce const it show's me

```<code>const pizza = true
pizza = false
</code>```

error:-

Uncaught SyntaxError: Identifier 'pizza' has already been declared

I searched and used these commands but it is not working

```<code>CLTRL + L
</code>```

console.clear();

```<code>window.clear = clear

clear()
</code>```

Can anyone can tell me how to refresh console without refreshing the page

答:
You can clear console with a "stop / danger button" on left top of the console. here the picture

and about CTRL + L is working for me.

Body:
I am reading an ebook, which is about ReactJs,I want to run commands in the same page console but if redeclare the same variable it showing me variable has already been declared

for ex:-

var pizza = true
pizza = false
console.log(pizza)

when i declarce const it show's me

const pizza = true
pizza = false

error:-

Uncaught SyntaxError: Identifier 'pizza' has already been declared

I searched and used these commands but it is not working

CLTRL + L

console.clear();

window.clear = clear

clear()

Can anyone can tell me how to refresh console without refreshing the page


问:
UWP Navigation between frames without losing Hamburger menu
So, I'm using MVVM Light. I have an UWP app where I have made a hamburger menu with buttons that loads a page into a Frame on the MainPage. The hamburger menu resides in the MainPage.

So far I've only used SourcePageType and binding it to a Type property in the MainPageViewModel. I can easily update the binding source of the SourcePageType by assigning the MainPageViewModel instance to a static property. That way I can do this for example:

```<code>MainPageViewModel.Current.CurrentFrame = typeof(NewItemPage);
</code>```

However, that means I'm navigating between the frames just by updating the MainFrameViewModel, which is probably not optimal (losing out on GoBack for example).

The reason I did this is because whenever I use NavigateTo, I lose the Hamburger menu and I open a whole new page, which is not what I want. I want to keep the Hamburger menu available at all time.

It's also important that I can navigate from within the other pages as well, not just the MainPage. For instance, one of the pages is has a grid view of images, loaded from a database. Whenever I click on one of these images, I'm taken to for example a detail page or an edit page.

Can anyone tell me how I can do this using a NavigationService of some sort? I don't want to rely on just using the code-behind, since I want to learn mvvm.

答:
The following structure will help you

In your main Frame place XAML for Hamburger and another Frame(will contain all content which can be navigated and also act as main placeholder)

In your NavigationService have the reference to content Frame and load views inside it and navigate within them.

I have also done a similar thing in one of my applications and is working great.

Note- I assume that this much should help you, if you require further help please feel free to ask.

Body:
So, I'm using MVVM Light. I have an UWP app where I have made a hamburger menu with buttons that loads a page into a Frame on the MainPage. The hamburger menu resides in the MainPage.

So far I've only used SourcePageType and binding it to a Type property in the MainPageViewModel. I can easily update the binding source of the SourcePageType by assigning the MainPageViewModel instance to a static property. That way I can do this for example:

MainPageViewModel.Current.CurrentFrame = typeof(NewItemPage);

However, that means I'm navigating between the frames just by updating the MainFrameViewModel, which is probably not optimal (losing out on GoBack for example).

The reason I did this is because whenever I use NavigateTo, I lose the Hamburger menu and I open a whole new page, which is not what I want. I want to keep the Hamburger menu available at all time.

It's also important that I can navigate from within the other pages as well, not just the MainPage. For instance, one of the pages is has a grid view of images, loaded from a database. Whenever I click on one of these images, I'm taken to for example a detail page or an edit page.

Can anyone tell me how I can do this using a NavigationService of some sort? I don't want to rely on just using the code-behind, since I want to learn mvvm.


问:
Template reference variable as @Input() for other component
Angular v5.0.1

I have this template on a component

```<code><div #content>some content</div>
<some-component [content]="content"></some-component>
</code>```

I want to pass the reference of #content variable to SomeComponent via @Input()content but I'm not sure what type the variable is.

From what I searched on the web it appears to be ElementRef so I did

```<code>  @Input()
  component: ElementRef;
  ngOnInit() {
    console.log(this.component); // this prints the html element on console
    console.log(this.component.nativeElement); // this prints undefined
  }
</code>```

but this.component.nativeElement is undefined

Doing more tests it appears that this.component is actually the native element

Doing something like this works and actually the background color is changed (this is just for testing purposes I'm not interesting in actually changing the color this way)

```<code>this.component.style.backgroundColor = 'red';
</code>```

While I got this working the way I wanted I have a few question to better understand how things work.

Is  #content the native element and not the ElementRef ?

Is this the valid Angular way of passing a reference variable to another component?

If you think this approach is wrong or is a better way of doing this please provide some valid example.

答:
ngOnInit() might be too early.
ngAfterViewInit() might work:

```<code>ngAfterViewInit() {
  console.log(this.component); // this prints the html element on console
  console.log(this.component.nativeElement); // this prints undefined
}
</code>```

Is  #content the native element and not the ElementRef ?

If #content is on a plain element, it is the nativeElement.

If the element hosts a component or directive, you'll get the component or directive instance.

Body:
Angular v5.0.1

I have this template on a component

some content

<some-component [content]="content"></some-component>

I want to pass the reference of #content variable to SomeComponent via @Input()content but I'm not sure what type the variable is.

From what I searched on the web it appears to be ElementRef so I did

  @Input()
  component: ElementRef;
  ngOnInit() {
    console.log(this.component); // this prints the html element on console
    console.log(this.component.nativeElement); // this prints undefined
  }

but this.component.nativeElement is undefined

Doing more tests it appears that this.component is actually the native element

Doing something like this works and actually the background color is changed (this is just for testing purposes I'm not interesting in actually changing the color this way)

this.component.style.backgroundColor = 'red';

While I got this working the way I wanted I have a few question to better understand how things work.

Is  #content the native element and not the ElementRef ?

Is this the valid Angular way of passing a reference variable to another component?

If you think this approach is wrong or is a better way of doing this please provide some valid example.

Body:
ngOnInit() might be too early.
ngAfterViewInit() might work:

ngAfterViewInit() {
  console.log(this.component); // this prints the html element on console
  console.log(this.component.nativeElement); // this prints undefined
}

Is  #content the native element and not the ElementRef ?

If #content is on a plain element, it is the nativeElement.

If the element hosts a component or directive, you'll get the component or directive instance.


问:
When is the best place to use Task.Result instead of awaiting Task
Whilst I've been using async code in .NET for a while, I've only recently started to research it and understand what's going on.  I've just been going through my code and trying to alter it so if a task can be done in parallel to some work, then it is. So for example:

```<code>var user = await _userRepo.GetByUsername(User.Identity.Name);

//Some minor work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;
</code>```

Now becomes:

```<code>var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(userTask.Result, DateTime.Now);

return user;
</code>```

My understand is that the user object is now being fetched from the database WHILST some unrelated work is going on. However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independant logic at the same time?

答:
Have you considered this version?

```<code>var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(await userTask, DateTime.Now);

return user;
</code>```

This will execute the "work" while the user is retrieved, but it also has all the advantages of await that are described in Await on a completed task same as task.Result?

As suggested you can also use a more explicit version to be able to inspect the result of the call in the debugger.

```<code>var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await userTask;
user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;
</code>```

Body:
Whilst I've been using async code in .NET for a while, I've only recently started to research it and understand what's going on.  I've just been going through my code and trying to alter it so if a task can be done in parallel to some work, then it is. So for example:

var user = await _userRepo.GetByUsername(User.Identity.Name);

//Some minor work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;

Now becomes:

var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(userTask.Result, DateTime.Now);

return user;

My understand is that the user object is now being fetched from the database WHILST some unrelated work is going on. However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independant logic at the same time?

Body:
Have you considered this version?

var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(await userTask, DateTime.Now);

return user;

This will execute the "work" while the user is retrieved, but it also has all the advantages of await that are described in Await on a completed task same as task.Result?

As suggested you can also use a more explicit version to be able to inspect the result of the call in the debugger.

var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await userTask;
user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;


问:
How to automatically reconnect a DataSource connection in Spring?
Problem: when my spring application is running, and meanwhile the database server is stopped/restarted, then then db connection is lost and never restored.

I tested as follows:

execute query: OK

service mysql stop

execute query: exception:

Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.

service mysql start

execute query: still exception!

Question: how can I tell spring DataSource to automatically reconnect after connection has been lost?

This is my configuration:

```<code>spring.datasource.url=jdbc:mysql://localhost/tablename?useSSL=false
spring.datasource.username=root
spring.datasource.password=rootpw
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.validation-query=SELECT 1
spring.datasource.tomcat.validation-query-timeout=5000
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.test-on-connect=true
</code>```

答:
I'm using a connection pool like  HikariCP to do a reconnect automatically.

see the example at Stackoverflow: How do I configure HikariCP in my Spring Boot app in my application.properties files?

Body:
Problem: when my spring application is running, and meanwhile the database server is stopped/restarted, then then db connection is lost and never restored.

I tested as follows:

execute query: OK

service mysql stop

execute query: exception:

Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.

service mysql start

execute query: still exception!

Question: how can I tell spring DataSource to automatically reconnect after connection has been lost?

This is my configuration:

spring.datasource.url=jdbc:mysql://localhost/tablename?useSSL=false
spring.datasource.username=root
spring.datasource.password=rootpw
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.validation-query=SELECT 1
spring.datasource.tomcat.validation-query-timeout=5000
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.test-on-connect=true


问:
Why does my getColor function always return false?
I have a function that gets user input and its supposed to validate the user input from a list of options. The last part of the function, where I cycle through results and return true, if there's a true boolean value in results doesn't seem to be working properly. It keeps returning false. </p>

```<code>    function getColor(){
        //gets user color and makes all characters lower case;
        let color=prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();

        //stores acceptable colors
        let acceptableColors=["white","yellow", "brown", "black","tan","red","orange"];

        function validate(){
            let results=[];
            for(let i=0; i<acceptableColors.length; i++){//loops through and stores a true value in results if user color is in list of acceptableColors
                    if(color===acceptableColors[i]){
                        results.push(true);
                    }
                    else{
                        results.push(false);
                    }

            }

            results.forEach(function(item){//loops through results to search for true value and returns true, if it finds one
                if(item===true){
                    return true
                }
            });
             return false;//returns false if user entered invalid color

        }
        return validate();

    }
</code>```

答:
It keeps returning false.

Return false inside forEach will not return from getColor and your return false is unconditional

Make it

```<code>    return results.some(function(item){
       return item;
    });
</code>```

Body:
I have a function that gets user input and its supposed to validate the user input from a list of options. The last part of the function, where I cycle through results and return true, if there's a true boolean value in results doesn't seem to be working properly. It keeps returning false.

    function getColor(){
        //gets user color and makes all characters lower case;
        let color=prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();

        //stores acceptable colors
        let acceptableColors=["white","yellow", "brown", "black","tan","red","orange"];

        function validate(){
            let results=[];
            for(let i=0; i<acceptableColors.length; i++){//loops through and stores a true value in results if user color is in list of acceptableColors
                    if(color===acceptableColors[i]){
                        results.push(true);
                    }
                    else{
                        results.push(false);
                    }

            }

            results.forEach(function(item){//loops through results to search for true value and returns true, if it finds one
                if(item===true){
                    return true
                }
            });
             return false;//returns false if user entered invalid color

        }
        return validate();

    }

Body:
It keeps returning false.

Return false inside forEach will not return from getColor and your return false is unconditional

Make it

    return results.some(function(item){
       return item;
    });


问:
Get last but one value using SQL function FIRST_VALUE
Is it possible to get last but one value of sorted variable using SQL function FIRST_VALUE? Here is a way to get the last value.

```<code>select
[MyVal_Last] = FIRST_VALUE([MyValue]) OVER (PARTITION BY [Category] ORDER BY [MyValue] DESC)
from tbl
</code>```

Is it possible to modify it to get second last value?

Update. I am familiar with different ways of getting the last but one value mentioned i.e. here Those answers are old and have grown long beards. I wonder if new version of SQL Server can do it in a more elegant way, using new functions.

答:
OK, I have found it. The function LAG does the job in year 2017. I do not know if it is most performant but it is good enough as simplicity counts.

```<code>[MyVal_Last] = LAG([MyValue],1) OVER (PARTITION BY [Category] ORDER BY [MyValue] ASC)
</code>```

Body:
Is it possible to get last but one value of sorted variable using SQL function FIRST_VALUE? Here is a way to get the last value.

select
[MyVal_Last] = FIRST_VALUE([MyValue]) OVER (PARTITION BY [Category] ORDER BY [MyValue] DESC)
from tbl

Is it possible to modify it to get second last value?

Update. I am familiar with different ways of getting the last but one value mentioned i.e. here Those answers are old and have grown long beards. I wonder if new version of SQL Server can do it in a more elegant way, using new functions.

Body:
OK, I have found it. The function LAG does the job in year 2017. I do not know if it is most performant but it is good enough as simplicity counts.

[MyVal_Last] = LAG([MyValue],1) OVER (PARTITION BY [Category] ORDER BY [MyValue] ASC)


问:
Should I use the Reply-To header when sending emails as a service to others?
Suppose we have an application that acts as a middleman, allowing Company A to send reports to their customers.

Company A --> Company B (me)--> Company A's customers

After getting the report we send email notifications to the recipients, but they necessarily originate from our company notifications email address e.g.

joe.bloggs@a.com --> notifications@b.com --> peter@c.com

Now, customers tend to reply to those email notifications, wanting them to go back to whoever sent the report at Company A. Instead, they end up back at our address, notifications@b.com.

A simple solution may be to change the Reply-To header on the notifications we send to the relevant Company A address e.g.

joe.bloggs@a.com --> notifications@b.com [Reply-To: joe.bloggs@a.com] --> peter@c.com

But my main concerns are:

the complete discrepancy in email address and domain between the From and Reply-To fields might make spam or phishing filters more eager to flag the emails

not all email clients may respect the Reply-To field when people actually click "Reply", and just use From instead. A lesser concern, unless widespread.

Are these concerns founded at all? Or, are there other concerns I should have?

答:
You may want to consider placing the customer's name in the From header and your address in the Sender header:

```<code>From: Company A <joe.bloggs@a.com>
Sender: notifications@b.com
</code>```

Most mailers will render this as "From notifications@b.com on behalf of Company A", which is accurate.  And then a Reply-To of Company A's address won't seem out of sorts.

From RFC 5322:

The "From:" field specifies the author(s) of the message,
that is, the mailbox(es) of the person(s) or system(s) responsible
for the writing of the message.  The "Sender:" field specifies the
mailbox of the agent responsible for the actual transmission of the
message.  For example, if a secretary were to send a message for
another person, the mailbox of the secretary would appear in the
"Sender:" field and the mailbox of the actual author would appear in
the "From:" field.

Body:
You may want to consider placing the customer's name in the From header and your address in the Sender header:

From: Company A <joe.bloggs@a.com>
Sender: notifications@b.com

Most mailers will render this as "From notifications@b.com on behalf of Company A", which is accurate.  And then a Reply-To of Company A's address won't seem out of sorts.

From RFC 5322:

The "From:" field specifies the author(s) of the message,
that is, the mailbox(es) of the person(s) or system(s) responsible
for the writing of the message.  The "Sender:" field specifies the
mailbox of the agent responsible for the actual transmission of the
message.  For example, if a secretary were to send a message for
another person, the mailbox of the secretary would appear in the
"Sender:" field and the mailbox of the actual author would appear in
the "From:" field.


问:
Understanding the Flyweight pattern

Intent:

The intent of this pattern is to use sharing to support a large number
  of objects that have part of their internal state in common where the
  other part of state can vary.

Objects can share state via static fields.

What is the difference between sharing internal state of a large number of objects using the flyweight pattern and using static fields?

Is the pool of objects that the flyweight provides via its Factory what the flyweight is really all about?

答:
Here is some example, it print all of the soldiers and their medals.

Because not all of the soldiers are decorated we are using the flyweight design pattern.

```<code>public class Soldiers
{
  private string[] _soldiers;
  private Dictionary<int, Medal> _medals = new Dictionary<int, Medal>();

  public Soldiers(string[] soldier)
  {
    this._soldiers = soldier;
  }

  public Medal this[int index]
  {
    get
    {
      Medal medal = new Medal();
      this._medals.Add(index, medal);
      return this._medals[index];
    }
  }

  public override string ToString()
  {
    var soldierList = new List<string>();
    for (var i = 0; i < this._soldiers.Length; i++)
    {
      string soldier = this._soldiers[i];
      if (this._medals.ContainsKey(i))
        soldier = soldier + ", Medal: " + this._medals.ElementAt(i).ToString();
      soldierList.Add(soldier);
    }
    return string.Join("; ", soldierList);
  }

  public class Medal
  {
    public bool Bronze;
    public bool Silver;
    public bool Gold;

    public override string ToString()
    {
      return (this.Bronze ? "Bronze," : "") + (this.Silver ? "Silver," : "") + (this.Gold ? "Gold" : "")
    }
  }
}
</code>```

Usage:

```<code>Soldiers soldiers = new Soldiers(new string[] { "SoldierA" , "SoldierB" , "SoldierC" });

soldiers[0].Gold = true;
soldiers[0].Silver = true;
soldiers[2].Bronze = true;
Console.Write(soldiers.ToString()) // "SoldierA, Medal: Silver,Gold; SoldierB; SoldierC, Medal: Bronze";
</code>```

Title: Understanding the Flyweight pattern

Body:
Here is some example, it print all of the soldiers and their medals.

Because not all of the soldiers are decorated we are using the flyweight design pattern.

public class Soldiers
{
  private string[] _soldiers;
  private Dictionary<int, Medal> _medals = new Dictionary<int, Medal>();

  public Soldiers(string[] soldier)
  {
    this._soldiers = soldier;
  }

  public Medal this[int index]
  {
    get
    {
      Medal medal = new Medal();
      this._medals.Add(index, medal);
      return this._medals[index];
    }
  }

  public override string ToString()
  {
    var soldierList = new List<string>();
    for (var i = 0; i < this._soldiers.Length; i++)
    {
      string soldier = this._soldiers[i];
      if (this._medals.ContainsKey(i))
        soldier = soldier + ", Medal: " + this._medals.ElementAt(i).ToString();
      soldierList.Add(soldier);
    }
    return string.Join("; ", soldierList);
  }

  public class Medal
  {
    public bool Bronze;
    public bool Silver;
    public bool Gold;

    public override string ToString()
    {
      return (this.Bronze ? "Bronze," : "") + (this.Silver ? "Silver," : "") + (this.Gold ? "Gold" : "")
    }
  }
}

Usage:

Soldiers soldiers = new Soldiers(new string[] { "SoldierA" , "SoldierB" , "SoldierC" });

soldiers[0].Gold = true;
soldiers[0].Silver = true;
soldiers[2].Bronze = true;
Console.Write(soldiers.ToString()) // "SoldierA, Medal: Silver,Gold; SoldierB; SoldierC, Medal: Bronze";

ContentLicense: CC BY-SA 4.0