问:
Convert stored Month Name as string into correct month number order in sql in delphi
I searched through this forum and others, but can't get the solutions to work in my Delphi 2010 app.

I want to order my results by the correct month order instead of the alphabetical name.

Here is my code:

```<code>select
  *
from
  provHedis
where
  provLastName = ''' + cbPLName.Text +'''
  and
  hyear = ''' + cbYear.Text + '''
order by
  hyear, hmonth
</code>```

hyear and hmonth are string fields in the table provHedis and I want to show my results in a dbgrid in order from January to February.  I hope this makes sense.

What I am getting now is alphabetical order by month.

Any help appreciated.  I am a beginner/novice (actually a physician) who is self taught, so please no harsh or condescending remarks.

答:
Make it a SubQuery :

```<code>select
  *
from
  provHedis
where
  provLastName = ''' + cbPLName.Text +'''
  and
  hyear = ''' + cbYear.Text + '''
    order by case hmonth
                when 'January' then 1
                when 'February' then 2
                when 'March' then 3
                when 'April' then 4
                when 'May' then 5
                when 'June' then 6
                when 'July' then 7
                when 'August' then 8
                when 'September' then 9
                when 'October' then 10
                when 'November' then 11
                when 'December' then 12
                else 13
            end,
            hyear
</code>```

OR :

```<code>ORDER BY [hyear],MONTH('1' + [hmonth] +'00')
</code>```

OR SEE THIS ANSWER :

convert month name in varchar to date so as to order by month

You could have a DATETIME field that would be much easier to short by (not having to do calculations there) and if you would like to display the name of the month you could use:

```<code>DATENAME ( month, DateField )
</code>```

Body:
I searched through this forum and others, but can't get the solutions to work in my Delphi 2010 app.

I want to order my results by the correct month order instead of the alphabetical name.

Here is my code:

select
  *
from
  provHedis
where
  provLastName = ''' + cbPLName.Text +'''
  and
  hyear = ''' + cbYear.Text + '''
order by
  hyear, hmonth

hyear and hmonth are string fields in the table provHedis and I want to show my results in a dbgrid in order from January to February.  I hope this makes sense.

What I am getting now is alphabetical order by month.

Any help appreciated.  I am a beginner/novice (actually a physician) who is self taught, so please no harsh or condescending remarks.

Body:
Make it a SubQuery :

select
  *
from
  provHedis
where
  provLastName = ''' + cbPLName.Text +'''
  and
  hyear = ''' + cbYear.Text + '''
    order by case hmonth
                when 'January' then 1
                when 'February' then 2
                when 'March' then 3
                when 'April' then 4
                when 'May' then 5
                when 'June' then 6
                when 'July' then 7
                when 'August' then 8
                when 'September' then 9
                when 'October' then 10
                when 'November' then 11
                when 'December' then 12
                else 13
            end,
            hyear

OR :

ORDER BY [hyear],MONTH('1' + [hmonth] +'00')

OR SEE THIS ANSWER :

convert month name in varchar to date so as to order by month

You could have a DATETIME field that would be much easier to short by (not having to do calculations there) and if you would like to display the name of the month you could use:

DATENAME ( month, DateField )


来源: stackexchange

问:
Is 20 MB Document size limit in couchdb inclusive of attachment size?
I read about 20MB limit on document size on couchbase and 20MB limit on attachment size. I want to know if attachments added to a document add up to total size of that document. I think it is not inclusive but couldn't find any reference to it.</p>

答:
The answer to your question recently changed, actually. From the CouchDB 2.1.0 release notes you can see:

The new httpd/max_http_request_size configuration parameter was added. This has the same behavior as the old couchdb/max_document_size configuration parameter, which had been unfortunately misnamed, and has now been updated to behave as the name would suggest. Both are documented in the shipped default.ini file.

So the answer to your question depends on which version of CouchDB you're using.  With CouchDB 2.0.x and earlier, the limit was actually related to the HTTP request size, which means that the effectual document size limit could be somewhat lower, depending on how the document was transmitted.

As of 2.1.0, however, the new description applies:

Limit maximum document body size. Size is calculated based on the serialized Erlang representation of the JSON document body, because that reflects more accurately the amount of storage consumed on disk.

Since the serialized Erlang representation of the JSON document does not contain attachments, it is a safe assumption that this limit does not include attachments.

I have just updated the CouchDB documentation to explain this explicitly, as well.

ContentLicense: CC BY-SA 3.0


问:
How to get saved date value from Sql Server in dateTimePicker Control in Windows Application
I have a simple registration table of employee having column Name, Number, Email, DOB, JoinDate.
I want to populate this value in the form in respective controls, i.e Name value goes in textbox and DOB value goes in dateTimePicker control and dateTimePicker automatically select the date which is coming from DB.
I do the logics for textboxes but not have a solution for dateTimePicker Control.
I am attaching some code for reference. </p>

```<code>using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCN"].ConnectionString))
{

            SqlCommand cmd = new SqlCommand("Select * from EmpRegister", con);
            con.Open();

            SqlDataAdapter da = new SqlDataAdapter();

            DataTable dt = new DataTable();
            da.SelectCommand = cmd;
            da.Fill(dt);
            if (dt != null && dt.Rows.Count > 0)
            {

                txtName.Text = dt.Rows[0]["EmpName"].ToString();
                txtPassword.Text = dt.Rows[0]["Password"].ToString();
                txtPassword.Enabled = false;
                txtUserName.Text = dt.Rows[0]["UserName"].ToString();

                txtDesignation.Text = dt.Rows[0]["EmpDesignation"].ToString();
                txtMobileNumber.Text = dt.Rows[0]["Empnumber"].ToString();
                txtEmailId.Text = dt.Rows[0]["EmpEmail"].ToString();
                bindRole();
                comboboxRole.SelectedValue = dt.Rows[0]["EmpRole"].ToString();

                dateTimePickerJoinDate.Value = Convert.ToDateTime("JoinDate");

                dateTimePickerDOB.Value = dt.Rows[0][Convert.ToDateTime(DOB)].ToString();
                dateTimePickerJoinDate.Value = dt.Rows[0][Convert.ToDateTime(JoinDate)].ToString();

                //string Gender = null;
                //if (radioButtonMale.Checked)
                //{
                  //  Gender = "Male";
                //}
                //else
                //{
                //    Gender = "Female";
                //}
                //radioButtonMale.Checked = dt.Rows[0]["Gender"].ToString();

            }

            else
            {
                MessageBox.Show("No Data in dt");
            }

        }
</code>```

<p>Please tell me how can i get the values of date in the datetimepicker control.
I am working on windows application.
Thanks in advance </p>

答:
It is also possible to pass the date time from your sql database then convert that string to Date Time:</p>

```<code>string sqlDate = dt.Rows[0]["JoinDate"].ToString();
dateTimePIckerJoinDate.Value = Convert.ToDateTime(sqlDate);
</code>```

Body:
I have a simple registration table of employee having column Name, Number, Email, DOB, JoinDate.
I want to populate this value in the form in respective controls, i.e Name value goes in textbox and DOB value goes in dateTimePicker control and dateTimePicker automatically select the date which is coming from DB.
I do the logics for textboxes but not have a solution for dateTimePicker Control.
I am attaching some code for reference.

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCN"].ConnectionString))
{

            SqlCommand cmd = new SqlCommand("Select * from EmpRegister", con);
            con.Open();

            SqlDataAdapter da = new SqlDataAdapter();

            DataTable dt = new DataTable();
            da.SelectCommand = cmd;
            da.Fill(dt);
            if (dt != null && dt.Rows.Count > 0)
            {

                txtName.Text = dt.Rows[0]["EmpName"].ToString();
                txtPassword.Text = dt.Rows[0]["Password"].ToString();
                txtPassword.Enabled = false;
                txtUserName.Text = dt.Rows[0]["UserName"].ToString();

                txtDesignation.Text = dt.Rows[0]["EmpDesignation"].ToString();
                txtMobileNumber.Text = dt.Rows[0]["Empnumber"].ToString();
                txtEmailId.Text = dt.Rows[0]["EmpEmail"].ToString();
                bindRole();
                comboboxRole.SelectedValue = dt.Rows[0]["EmpRole"].ToString();

                dateTimePickerJoinDate.Value = Convert.ToDateTime("JoinDate");

                dateTimePickerDOB.Value = dt.Rows[0][Convert.ToDateTime(DOB)].ToString();
                dateTimePickerJoinDate.Value = dt.Rows[0][Convert.ToDateTime(JoinDate)].ToString();

                //string Gender = null;
                //if (radioButtonMale.Checked)
                //{
                  //  Gender = "Male";
                //}
                //else
                //{
                //    Gender = "Female";
                //}
                //radioButtonMale.Checked = dt.Rows[0]["Gender"].ToString();

            }

            else
            {
                MessageBox.Show("No Data in dt");
            }

        }

Please tell me how can i get the values of date in the datetimepicker control.
I am working on windows application.
Thanks in advance

Body:
It is also possible to pass the date time from your sql database then convert that string to Date Time:

string sqlDate = dt.Rows[0]["JoinDate"].ToString();
dateTimePIckerJoinDate.Value = Convert.ToDateTime(sqlDate);


问:
Google Chrome autoplays my embedded sound
Is there any way to disable this? I want to use jQuery to play the sound. I chose to use < embed >, because it doesn't require Flash and it works on all browsers/ platforms:

```<code><embed src="sounds/button-9.mp3" autostart="false" width=0 height=0 id="newMsgSound" enablejavascript="true">
</code>```

Thanks!

答: Why don't use jPlayer? It uses JQuery at backend, and it supports both HTML5 and Flash. So, if your users are using IE, which doesn't have HTML5 support, jPlayer will automatically use Flash. If the device doesn't support Flash (say, iPhone, iPad), jPlayer will automatically use HTML5... everything is seamless to you as a developer.</p>

ContentLicense: CC BY-SA 2.5

Body:
Is there any way to disable this? I want to use jQuery to play the sound. I chose to use < embed >, because it doesn't require Flash and it works on all browsers/ platforms:

<embed src="sounds/button-9.mp3" autostart="false" width=0 height=0 id="newMsgSound" enablejavascript="true">

Thanks!


问:
How can I call a function before it is defined?
I have an AJAX call placed inside a function, which is called through PHP when there is an error (such as an input field is empty) to display a notification to the user, however I am receiving this error:

Uncaught ReferenceError: sendnotification is not defined

I know why this is... but I don't know how to fix it. It is because I am calling a function which has not yet been defined. Here is an extremely cut-down version of two of my files:

index.php:

```<code><?php

include('con.php'); // the file which connects to the database

echo'<script>sendnotification();</script>'; // calls the function which is in footer.php

include('header.php'); // the file which contains the document headers and imports the jQuery and other libraries

include('footer.php');

?>
</code>```

I cannot place the echo line after I import header.php because it is inside a function which validates a form and other if statements will cause a 'headers already sent' error.

footer.php:

```<code><script>
function sendnotification() {
   // do something
}
</script>
</code>```

答:
What if you call it after the header (which according to you comments, is where you include jQuery) is included?</p>

```<code><?php

include('con.php'); // the file which connects to the database

include('header.php'); // the file which contains the document headers and imports the jQuery and other libraries

echo'<script>$(document).ready(function(){sendnotification();});</script>'; // calls the function which is in footer.php

include('footer.php');

?>
</code>```

OwnerDisplayName: anon

LastEditorDisplayName: anon

Body:
I have an AJAX call placed inside a function, which is called through PHP when there is an error (such as an input field is empty) to display a notification to the user, however I am receiving this error:

Uncaught ReferenceError: sendnotification is not defined

I know why this is... but I don't know how to fix it. It is because I am calling a function which has not yet been defined. Here is an extremely cut-down version of two of my files:

index.php:

<?php

include('con.php'); // the file which connects to the database

echo''; // calls the function which is in footer.php

include('header.php'); // the file which contains the document headers and imports the jQuery and other libraries

include('footer.php');

?>

I cannot place the echo line after I import header.php because it is inside a function which validates a form and other if statements will cause a 'headers already sent' error.

footer.php:

Body:
What if you call it after the header (which according to you comments, is where you include jQuery) is included?

<?php

include('con.php'); // the file which connects to the database

include('header.php'); // the file which contains the document headers and imports the jQuery and other libraries

echo'<script>$(document).ready(function(){sendnotification();});</script>'; // calls the function which is in footer.php

include('footer.php');

?>


问:
Android get location in button click app unfortunately stopped
I am new in android and I want to get my current location in button click. I am following this documentation as a tutorial for this. All the functions are working fine except showLocation(). If I simply write a toast message in this function then it works fine but when I add the code to get location then I got error in app ShanTest app unfortunately stopped.

I have tried commenting out the below code and replaced it with a TOAST message, then it works fine. The code where the error is there is below :-

```<code>mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Logic to handle location object
                                onLocationChanged(location);
                            }
                            else {
                                Toast.makeText(getApplicationContext(), "Oops", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
</code>```

SDK Manager

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    dataBinding.enabled = true
    defaultConfig {
        applicationId "com.example.borntoflirt.design1"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-location:11.0.4'
    testCompile 'junit:junit:4.12'
}
</code>```

events.java

```<code>     package com.example.borntoflirt.design1;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.media.MediaPlayer.OnCompletionListener;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.widget.Toast;

import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class events extends AppCompatActivity {

    private CameraManager mCameraManager;
    private String mCameraId;
    private Button mTorchOnOffButton;
    private Boolean isTorchOn;
    private Boolean isFlashAvailable;

    private FusedLocationProviderClient mFusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_events);

        mTorchOnOffButton = (Button) findViewById(R.id.mTorchOnOffButton);
        isFlashAvailable = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        isTorchOn = false;

        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            mCameraId = mCameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

        mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isFlashAvailable) {
                        if (isTorchOn) {
                            turnOffFlashLight();
                            isTorchOn = false;
                        } else {
                            turnOnFlashLight();
                            isTorchOn = true;
                        }
                    }
                    else {
                        Toast.makeText(getApplicationContext(), "Flash is not supported", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }

    public void turnOnFlashLight() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mCameraManager.setTorchMode(mCameraId, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void turnOffFlashLight() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mCameraManager.setTorchMode(mCameraId, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showToast(View v) {
        Context context = getApplicationContext();  // OR getBaseContext()
        CharSequence text = "Hello Toast";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }

    public void showAlert(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Write your message here.");
        builder.setCancelable(false);

        builder.setPositiveButton(
                "ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Do Task
                        Toast.makeText(getApplicationContext(),
                                "You clicked on OK", Toast.LENGTH_SHORT)
                                .show();
                    }
                });

        builder.setNegativeButton(
                "Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();
    }

    public void showDate(View v) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy HH:mm:ss");
        String currentDateTime = simpleDateFormat.format(calendar.getTime());
        Toast.makeText(getApplicationContext(), currentDateTime, Toast.LENGTH_LONG).show();
    }

    public void showLocation() {
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        if( permissionCheck != PackageManager.PERMISSION_GRANTED ) {
            //Toast.makeText(getApplicationContext(), "Granted", Toast.LENGTH_SHORT).show();
            mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Logic to handle location object
                                onLocationChanged(location);
                            }
                            else {
                                Toast.makeText(getApplicationContext(), "Oops", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
        else {
            Toast.makeText(getApplicationContext(), "Permission Not Granted", Toast.LENGTH_SHORT).show();
        }
    }

    public void onLocationChanged(Location location) {
        // New location has now been determined
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

}
</code>```

答:
Assuming all permission are setup in the manifest and the dependency is good.

mFusedLocationClient doesn't seem to be initialized anywhere in your code. according to https://developer.android.com/training/location/retrieve-current.html#last-known

do this in onCreate

```<code>mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
</code>```

Body:
I am new in android and I want to get my current location in button click. I am following this documentation as a tutorial for this. All the functions are working fine except showLocation(). If I simply write a toast message in this function then it works fine but when I add the code to get location then I got error in app ShanTest app unfortunately stopped.

I have tried commenting out the below code and replaced it with a TOAST message, then it works fine. The code where the error is there is below :-

mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Logic to handle location object
                                onLocationChanged(location);
                            }
                            else {
                                Toast.makeText(getApplicationContext(), "Oops", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

SDK Manager

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    dataBinding.enabled = true
    defaultConfig {
        applicationId "com.example.borntoflirt.design1"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-location:11.0.4'
    testCompile 'junit:junit:4.12'
}

events.java

     package com.example.borntoflirt.design1;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.media.MediaPlayer.OnCompletionListener;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.widget.Toast;

import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class events extends AppCompatActivity {

    private CameraManager mCameraManager;
    private String mCameraId;
    private Button mTorchOnOffButton;
    private Boolean isTorchOn;
    private Boolean isFlashAvailable;

    private FusedLocationProviderClient mFusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_events);

        mTorchOnOffButton = (Button) findViewById(R.id.mTorchOnOffButton);
        isFlashAvailable = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        isTorchOn = false;

        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            mCameraId = mCameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

        mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isFlashAvailable) {
                        if (isTorchOn) {
                            turnOffFlashLight();
                            isTorchOn = false;
                        } else {
                            turnOnFlashLight();
                            isTorchOn = true;
                        }
                    }
                    else {
                        Toast.makeText(getApplicationContext(), "Flash is not supported", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }

    public void turnOnFlashLight() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mCameraManager.setTorchMode(mCameraId, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void turnOffFlashLight() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mCameraManager.setTorchMode(mCameraId, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showToast(View v) {
        Context context = getApplicationContext();  // OR getBaseContext()
        CharSequence text = "Hello Toast";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }

    public void showAlert(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Write your message here.");
        builder.setCancelable(false);

        builder.setPositiveButton(
                "ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Do Task
                        Toast.makeText(getApplicationContext(),
                                "You clicked on OK", Toast.LENGTH_SHORT)
                                .show();
                    }
                });

        builder.setNegativeButton(
                "Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();
    }

    public void showDate(View v) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy HH:mm:ss");
        String currentDateTime = simpleDateFormat.format(calendar.getTime());
        Toast.makeText(getApplicationContext(), currentDateTime, Toast.LENGTH_LONG).show();
    }

    public void showLocation() {
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        if( permissionCheck != PackageManager.PERMISSION_GRANTED ) {
            //Toast.makeText(getApplicationContext(), "Granted", Toast.LENGTH_SHORT).show();
            mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Logic to handle location object
                                onLocationChanged(location);
                            }
                            else {
                                Toast.makeText(getApplicationContext(), "Oops", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
        else {
            Toast.makeText(getApplicationContext(), "Permission Not Granted", Toast.LENGTH_SHORT).show();
        }
    }

    public void onLocationChanged(Location location) {
        // New location has now been determined
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

}

Body:
Assuming all permission are setup in the manifest and the dependency is good.

mFusedLocationClient doesn't seem to be initialized anywhere in your code. according to https://developer.android.com/training/location/retrieve-current.html#last-known

do this in onCreate

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);


问:
How to find out the task dependency in apache spark
I understand that from Apache Spark you can find out dependency of among RDD inside stages by using spark history UI, like this:

From that DAG of RDD I know that: RDD number 36 can not start before finishing RDD number 33,34 and 35.

My question is: How can I find dependency among all tasks inside specific stage?

From the spark event logs and Spark history server UI I can get the start and end time of task, But I cant find how to get dependency between tasks.

答:
You have already almost answered your question . You can check the RDD dependencies using API also Spar todebug String gives the facilities to check the RDD Dependencies. Please check spark-rdd-dependencies .

At high level, when any action is called on the RDD, Spark creates the DAG and submits it to the DAG scheduler.

The DAG scheduler divides operators into stages of tasks. A stage is comprised of tasks based on partitions of the input data. The DAG scheduler pipelines operators together. For e.g. Many map operators can be scheduled in a single stage. The final result of a DAG scheduler is a set of stages.

The Stages are passed on to the Task Scheduler.The task scheduler launches tasks via cluster manager (Spark Standalone/Yarn/Mesos). The task scheduler doesn't know about dependencies of the stages.

At high level, there are two transformations that can be applied onto the RDDs, namely narrow transformation and wide transformation. Wide transformations basically result in stage boundaries.

Narrow transformation - doesn't require the data to be shuffled across the partitions. for example, Map, filter etc..

wide transformation- requires the data to be shuffled for example, reduceByKey etc..

Advanced Apache Spark- Sameer Farooqui (Databricks) check this its best


问:
PHPExcel save error - Cell coordinate string can not be a range of cells

I am currently trying to save an excel file loaded with PHPExcel. The template file has multiple sheets that reference other sheets in formulas. The template is being loaded from my local Apache server. After loading the file I try to save it and it throws an exception "Cell coordinate string can not be a range of cells". Using the HTML writer it displays perfectly.

Here is my code:

```<code>require_once "assets/vendors/PHPExcel/PHPExcel.php";
require_once 'assets/vendors/PHPExcel/PHPExcel/IOFactory.php';
$tmpfname = 'template_files/templateFile.xlsx';

$objReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$objPHPExcel = $objReader->load($tmpfname);

try {
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header('Content-Disposition: attachment;filename="myfile.xlsx"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');

} catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
}
</code>```

I expected my template sheet to be downloaded as usual in PHPExcel but cannot solve this issue. Has anyone else run into something similar?

The document that is downloaded is completely blank with the exception printed "Caught exception: Cell coordinate string can not be a range of cells".

答:
For anyone that runs into this exception in the future:

Remove the formatting from your document and try saving it with PHPExcel.
I am not sure of the exact source, but after removal I replicated the formatting with Google Sheets and the writer exported perfectly fine.

Body:
I am currently trying to save an excel file loaded with PHPExcel. The template file has multiple sheets that reference other sheets in formulas. The template is being loaded from my local Apache server. After loading the file I try to save it and it throws an exception "Cell coordinate string can not be a range of cells". Using the HTML writer it displays perfectly.

Here is my code:

require_once "assets/vendors/PHPExcel/PHPExcel.php";
require_once 'assets/vendors/PHPExcel/PHPExcel/IOFactory.php';
$tmpfname = 'template_files/templateFile.xlsx';

$objReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$objPHPExcel = $objReader->load($tmpfname);

try {
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header('Content-Disposition: attachment;filename="myfile.xlsx"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');

} catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
}

I expected my template sheet to be downloaded as usual in PHPExcel but cannot solve this issue. Has anyone else run into something similar?

The document that is downloaded is completely blank with the exception printed "Caught exception: Cell coordinate string can not be a range of cells".


问:
I get an error that looks like this : parse error: syntax error, unexpected ';' on line 18
i am getting this error :
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\loginsystem\includes\signup.inc.php on line 18

```<code>        <?php

    if (isset($_POST['Submit'])) {

        include_once 'dbh.inc.php';

        $first = mysqli_real_escape_string($conn, $_POST['first']);
        $last = mysqli_real_escape_string($conn, $_POST['last']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $uid = mysqli_real_escape_string($conn, $_POST['uid']);
        $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

        //error handlers
        // check for empty fields

        if (empty($first)) (empty($last)) (empty($email)) (empty($uid)) (empty($pwd)) {

            header ("location: ../signup.php?signup=empty");
            exit();

        } else {
            //check if input characters are valid
            if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last) {

                header("location: ../signup.php?signup=invalid");
                exit();

            } else {
            // check if eimal is valid
                if (!filter_var($email, FILTER_VALIDATE_EMAIL))

                    header("location: ../signup.php?Signup=email");
                    exit();
            } else {
                $sql = "SELECT * FROM users WHERE user_uid='$uid'";
                $result = mysqli_query($conn, $sql);
                $resultCheck = mysqli_num_rows($result);

                if ($resultCheck > 0) {

                    header("location: ../signup.php?signup=usernametaken");
                    exit();
                } else {
                    //Hashing th password
                    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);

                    //Insert the user into the database
                    $sq l= "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$emial', '$uid','$hashedPwd');";

                    mysqli_query($conn, $sql);
                    header("location: ../signup.php?signup=success");
                    exit();
                }
            }
        }

    }   else {
        header("location: ../signup.php");
        exit();
</code>```

when i take the semicolon away i get this error:
Parse error: syntax error, unexpected 'exit' (T_EXIT) in C:\xampp\htdocs\loginsystem\includes\signup.inc.php on line 19

If somone can please help me i would appreciate it.

thanks

答:
1) You are missing a ) at the end of if statement.

2) You should be using an operator may be && or || operator. Insert it according to your requirements.

Updated Code:

```<code>if (empty($first)) && (empty($last)) && (empty($email)) && (empty($uid)) && (empty($pwd))) {

      ...//rest of the code
</code>```

Body:
i am getting this error :
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\loginsystem\includes\signup.inc.php on line 18

        <?php

    if (isset($_POST['Submit'])) {

        include_once 'dbh.inc.php';

        $first = mysqli_real_escape_string($conn, $_POST['first']);
        $last = mysqli_real_escape_string($conn, $_POST['last']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $uid = mysqli_real_escape_string($conn, $_POST['uid']);
        $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

        //error handlers
        // check for empty fields

        if (empty($first)) (empty($last)) (empty($email)) (empty($uid)) (empty($pwd)) {

            header ("location: ../signup.php?signup=empty");
            exit();

        } else {
            //check if input characters are valid
            if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last) {

                header("location: ../signup.php?signup=invalid");
                exit();

            } else {
            // check if eimal is valid
                if (!filter_var($email, FILTER_VALIDATE_EMAIL))

                    header("location: ../signup.php?Signup=email");
                    exit();
            } else {
                $sql = "SELECT * FROM users WHERE user_uid='$uid'";
                $result = mysqli_query($conn, $sql);
                $resultCheck = mysqli_num_rows($result);

                if ($resultCheck > 0) {

                    header("location: ../signup.php?signup=usernametaken");
                    exit();
                } else {
                    //Hashing th password
                    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);

                    //Insert the user into the database
                    $sq l= "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$emial', '$uid','$hashedPwd');";

                    mysqli_query($conn, $sql);
                    header("location: ../signup.php?signup=success");
                    exit();
                }
            }
        }

    }   else {
        header("location: ../signup.php");
        exit();

when i take the semicolon away i get this error:
Parse error: syntax error, unexpected 'exit' (T_EXIT) in C:\xampp\htdocs\loginsystem\includes\signup.inc.php on line 19

If somone can please help me i would appreciate it.

thanks

Body:
1) You are missing a ) at the end of if statement.

2) You should be using an operator may be && or || operator. Insert it according to your requirements.

Updated Code:

if (empty($first)) && (empty($last)) && (empty($email)) && (empty($uid)) && (empty($pwd))) {

      ...//rest of the code


问:
Can we use wildcards with "Android Emulator Plugin" on jenkins server?
I am trying to install and run my apk on emulator with help of Android Emulator Plugin on Jenkins CI, but I am unable to use wildcards, since I rename my apk file with the flavour name, build number and build date. Is there a way to make things work out?</p>

答:
Looking at the source code, it seems that the Install APK step doesn't support wildcards.

In that case you could first copy the APK to a known path (e.g. in an Execute Shell step).

e.g.

```<code>shopt -s globstar
cp **/app/**/*.apk app.apk
cp **/test/**/*.apk test.apk
</code>```

Body:
Looking at the source code, it seems that the Install APK step doesn't support wildcards.

In that case you could first copy the APK to a known path (e.g. in an Execute Shell step).

e.g.

shopt -s globstar
cp **/app/**/*.apk app.apk
cp **/test/**/*.apk test.apk


问:
MySQL String to Time Format
Could you please help.

In the database time represent in string format like 5.5 (hours) how to convert to 5:30 min

I tried

```<code>select CAST('5.50' AS DATETIME)

select STR_TO_DATE('5.50', '%h:%i %p') ;
</code>```

but this is not working.

Thank you

答:
To get the time in format hh:mm:ss you could use this query.

```<code>SELECT SUBTIME(TIME(DATE_ADD(FROM_UNIXTIME(UNIX_TIMESTAMP(0),'%Y-%m-%d %H:%i:%s'), INTERVAL 5.5*60 MINUTE)), TIME(UNIX_TIMESTAMP(0)));
</code>```

check it out on SQL fiddle

EDIT

In case you want seconds accuracy then change the query like this.

```<code>SELECT SUBTIME(TIME(DATE_ADD(FROM_UNIXTIME(UNIX_TIMESTAMP(0),'%Y-%m-%d %H:%i:%s'), INTERVAL 5.501*3600 SECOND)), TIME(UNIX_TIMESTAMP(0)));
</code>```

Title: MySQL String to Time Format

Body:
Could you please help.

In the database time represent in string format like 5.5 (hours) how to convert to 5:30 min

I tried

select CAST('5.50' AS DATETIME)

select STR_TO_DATE('5.50', '%h:%i %p') ;

but this is not working.

Thank you

Body:
To get the time in format hh:mm:ss you could use this query.

SELECT SUBTIME(TIME(DATE_ADD(FROM_UNIXTIME(UNIX_TIMESTAMP(0),'%Y-%m-%d %H:%i:%s'), INTERVAL 5.5*60 MINUTE)), TIME(UNIX_TIMESTAMP(0)));

check it out on SQL fiddle

EDIT

In case you want seconds accuracy then change the query like this.

SELECT SUBTIME(TIME(DATE_ADD(FROM_UNIXTIME(UNIX_TIMESTAMP(0),'%Y-%m-%d %H:%i:%s'), INTERVAL 5.501*3600 SECOND)), TIME(UNIX_TIMESTAMP(0)));


问:
Importing application models from Google cloud shell
I am very, very new to Google App Engine, but I need to administer a WebApp2 (so, Python) -based website that uses it.  Specifically I need to filter a queryset and delete certain model instances.

Building the site locally is fine. Locally I can get at the models by hitting

```<code>http://localhost:8000/console
</code>```

in my browser. This pulls up the "interactive console", and in there I can put some code like

```<code>from application.models.user import User
</code>```

and it will work. From there I can create / delete User objects in the Datastore, so this local interactive console seems to have ORM-like functionality. (I'm coming from a Django background, so that's what it reminds me of).

However I don't seem to have this option on the live website. I was hoping to find it at

```<code>https://console.cloud.google.com/home/dashboard?project=<my project>
</code>```

And I thought I had found it when I found the control to "activate google cloud shell".  This brings up a command line on the web server, but the website's codebase doesn't seem to exist here, so launching the Python cli and trying to import the applications models like I can do locally doesn't work. And even if I could, I doubt it would be a Django-like ORM the way it is on my local build.

Am I thinking about this in the wrong way? How do you create / filter / delete / etc. Datastore objects via the backend in a GAE / WebApp2 website?  Is the  "Google cloud shell" even part of the answer?

答:
To get access to your app code in the cloud shell one option would be to create in the shell a local copy of your app repository. For an example (addressing a different question, true) you can peek at Google Cloud: How to deploy mirrored Repository. But I'm not 100% certain if that will automatically give you access to your app's datastore. Worth a try IMHO.

Another option is to hook the desired operations as handler actions inside your app itself and execute them from there. Eventually hidden/protected/restricted via authentication, for example for admin users only. This is what I use for one-time datastore migrations that I need from time to time when I make changes to my entity models.

Finally, but not really a programatic access - you could use the Datastore page in the developer console to manually find, read and modify your entities, see  Managing Datastore from the Console.

Body:
I am very, very new to Google App Engine, but I need to administer a WebApp2 (so, Python) -based website that uses it.  Specifically I need to filter a queryset and delete certain model instances.

Building the site locally is fine. Locally I can get at the models by hitting

http://localhost:8000/console

in my browser. This pulls up the "interactive console", and in there I can put some code like

from application.models.user import User

and it will work. From there I can create / delete User objects in the Datastore, so this local interactive console seems to have ORM-like functionality. (I'm coming from a Django background, so that's what it reminds me of).

However I don't seem to have this option on the live website. I was hoping to find it at

https://console.cloud.google.com/home/dashboard?project=<my project>

And I thought I had found it when I found the control to "activate google cloud shell".  This brings up a command line on the web server, but the website's codebase doesn't seem to exist here, so launching the Python cli and trying to import the applications models like I can do locally doesn't work. And even if I could, I doubt it would be a Django-like ORM the way it is on my local build.

Am I thinking about this in the wrong way? How do you create / filter / delete / etc. Datastore objects via the backend in a GAE / WebApp2 website?  Is the  "Google cloud shell" even part of the answer?


问:
64/32-bit division on a processor with 32/16-bit division
My processor, a small 16-bit microcontroller with no FPU and integer math only has 16/16 division and 32/16 division which both take 18 cycles. At the moment I'm using a very slow software routine (~7,500 cycles) to do 64/32 division. Is there any way to use these division engines to calculate a 64/32 division? Similar to how I'm already using the 16x16 multiplier and adder to calculate 32x32 multiplies? I'm using C but can work with any general explanation on how it can be done... I'm hoping to target <200 cycles (if it's at all possible.)</p>

答:
My copy of Knuth (The Art of Computer Programming) is at work, so I can't check it until Monday, but that would be my first source. It has a whole section on arithmetic.

edit: your post about "16/16 division and 32/16 division which both take 18 cycles." -- dsPICs have a conditional subtract operation in assembly. Consider using this as your computational primitive.

Also note that if X = XH * 232 + XL and D = DH * 216 + DL, then if you are looking for

(Q,R) = X/D where X = Q * D + R

where Q = QH * 216 + QL,  R = RH * 216 + RL, then

XH * 232 + XL = DH * QH * 232 + (DL * QH + DH * QL) * 216 + (DL * QL) +  RH * 216 + RL

This suggests (by looking at terms that are the high 32 bits) to use the following procedure, akin to long division:

(QH, R0) = XH / (DH+1) -> XH = QH * (DH+1) + R0  [32/16 divide]

R1 = X - (QH * 216) * D  [requires a 16*32 multiply, a shift-left by 16, and a 64-bit subtract]

calculate R1' = R1 - D * 216

while R1' >= 0, adjust QH upwards by 1, set R1 = R1', and goto step 3

(QL, R2) = (R1 >> 16) / (DH+1) -> R1 = QL * (DH+1) + R2 [32/16 divide]

R3 = R1 - (QL * D) [requires a 16*32 multiply and a 48-bit subtract]

calculate R3' = R3 - D

while R3' >= 0, adjust QL upwards by 1, set R3 = R3', and goto step 7

Your 32-bit quotient is the pair (QH,QL), and 32-bit remainder is R3.

(This assumes that the quotient is not larger than 32-bit, which you need to know ahead of time, and can easily check ahead of time.)


问:
javascript (boolean ^ boolean)
I'm working on rewriting some Javascript-code to work in Excel VBA.
I've manage to translate almost all of the Javascript-code thanks to searching on this website! However, there is some code I can't understand what it's doing precisely.
This is the bit of Javascript-code:

```<code>var k = x % y;
return (k != 0 && (k > 0 ^ y > 0) && isFinite(y)) ? k + y : k;
</code>```

The first line is clear to me. k is the remainder of x/y.
In the second line, modulo gets the value of either k+y or k. This is decided by (k!=0 && (k > 0 ^ y > 0) && isFinite(y))

Could somebody explain to me step by step how I should be reading this code? Especially the &&(k>0^y>0)&& is puzzling me.

This is how far I seem to be getting till now:

Example 1: x=9 and y=4

```<code>k = 9%4 = 9/4=2 with remainder 1    So: k=1
(1!=0&&(1>0^4>0)&&isFinite(4))   (True AND (True^True) AND True)  =  True?
</code>```

Example 1: x=9 and y=1

```<code>k = 9%1 = 9/1=9 with remainder 0    So: k=0
(0!=0&&(0>0^1>0)&&isFinite(1))  (False AND (False^True) AND True)  =  False?
</code>```

If I would think purely mathematically, then I would guess that the part (False^True) should be read like (0^1) = 0 = False.

答:
The ^ operator is the XOR, or EXCLUSIVE OR, bitwise operator. It only returns true if and only if one value is true. If both are true, or both are false, the result is false

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR:

a      b       a XOR b
0      0       0
0      1       1
1      0       1
1      1       0

As to why your second example returns FALSE, it's because you're using AND logic:

FALSE && (FALSE ^ TRUE) && TRUE results in FALSE && TRUE && TRUE which equates to FALSE.

Title: javascript (boolean ^ boolean)

Body:
I'm working on rewriting some Javascript-code to work in Excel VBA.
I've manage to translate almost all of the Javascript-code thanks to searching on this website! However, there is some code I can't understand what it's doing precisely.
This is the bit of Javascript-code:

var k = x % y;
return (k != 0 && (k > 0 ^ y > 0) && isFinite(y)) ? k + y : k;

The first line is clear to me. k is the remainder of x/y.
In the second line, modulo gets the value of either k+y or k. This is decided by (k!=0 && (k > 0 ^ y > 0) && isFinite(y))

Could somebody explain to me step by step how I should be reading this code? Especially the &&(k>0^y>0)&& is puzzling me.

This is how far I seem to be getting till now:

Example 1: x=9 and y=4

k = 9%4 = 9/4=2 with remainder 1    So: k=1
(1!=0&&(1>0^4>0)&&isFinite(4))   (True AND (True^True) AND True)  =  True?

Example 1: x=9 and y=1

k = 9%1 = 9/1=9 with remainder 0    So: k=0
(0!=0&&(0>0^1>0)&&isFinite(1))  (False AND (False^True) AND True)  =  False?

If I would think purely mathematically, then I would guess that the part (False^True) should be read like (0^1) = 0 = False.


问:
How to get list of json strings from sinlgle line multi json string in scala
I am trying to get list of json string from given string having multiple json strings separated by ",".

For example
    val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"

```<code>expected result , List[String] :
["{\"a\":\"b\"}", "{\"c\":\"d\", \"e\":\"f\"}"]
</code>```

答:
Got solution for it.

```<code>val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"
val jsonListString = "[" + jsonString + "]"
val jsonArray = new JSONArray(jsonListString)
</code>```

This will create array of json.

Body:
I am trying to get list of json string from given string having multiple json strings separated by ",".

For example
    val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"

expected result , List[String] :
["{\"a\":\"b\"}", "{\"c\":\"d\", \"e\":\"f\"}"]

Body:
Got solution for it.

val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"
val jsonListString = "[" + jsonString + "]"
val jsonArray = new JSONArray(jsonListString)

This will create array of json.


问:
Comparing cells in two CSV files using powershell
Pretty new to this. I need to compare a column with usernames from one CSV file, against a column with usernames in another CSV file and output if duplicates exists or remove them.

How they currently look:

$File1:

```
Firstname,Lastname,Username
Peter,Larsen,Larsen.123
Pia,Jensen,Jensen.123
Poul,Hansen,Hansen.123
```

$File2:

```
Username
Larsen.123
Andersen.123
Jensen.123
```

What I'm looking for:

```
Firstname,Lastname,Username,Duplicate
Peter,Larsen,Larsen.123,True
Pia,Jensen,Jensen.123,True
Poul,Hansen,Hansen.123,False
```

It doesn't necessarily have to be a true/false output, removing all duplicate entries from File1 or similar, would be perfectly fine as well. It's essentially just to compare users in our AD against users in our user database, to see if anyone still have access who shouldn't have.

Edit:

Tried with this so far, found in a similar question in here:

```<code>foreach ($user in $File1) {
    $MatchAccount = (Compare-Object $File2 $user -Property 'Username' -PassThru).Value
    $user = Add-Member -InputObject $user -Type NoteProperty -Name 'Value' -Value $MatchAccount
</code>```

And just importing and exporting the CSV files before and after, in that order.

答:
here is my approach:

```<code># import csv file1
$file1 = Import-Csv -Path C:\tmp\file1.csv

# import csv file2 and select column "Username"
$file2 = Import-Csv -Path C:\tmp\file2.csv | % {$_.Username}

# create output/result hash table
$file3 = @()

# go through entries in file1
foreach($entry in $file1) {
    # check if entry is in not in file2
    if($file2 -notcontains $entry.Username) {
        # add entry to output hash table
        $file3 += $entry
    }
}

# export result to csv
$file3 | Export-Csv -Path C:\tmp\file3.csv -NoTypeInformation
</code>```

file3.csv will then have the following contents

```<code>Firstname,Lastname,Username
Poul,Hansen,Hansen.123
</code>```

Best regards
Guenther

Body:
Pretty new to this. I need to compare a column with usernames from one CSV file, against a column with usernames in another CSV file and output if duplicates exists or remove them.

How they currently look:

$File1:

Firstname,Lastname,Username
Peter,Larsen,Larsen.123
Pia,Jensen,Jensen.123
Poul,Hansen,Hansen.123

$File2:

Username
Larsen.123
Andersen.123
Jensen.123

What I'm looking for:

Firstname,Lastname,Username,Duplicate
Peter,Larsen,Larsen.123,True
Pia,Jensen,Jensen.123,True
Poul,Hansen,Hansen.123,False

It doesn't necessarily have to be a true/false output, removing all duplicate entries from File1 or similar, would be perfectly fine as well. It's essentially just to compare users in our AD against users in our user database, to see if anyone still have access who shouldn't have.

Edit:

Tried with this so far, found in a similar question in here:

foreach ($user in $File1) {
    $MatchAccount = (Compare-Object $File2 $user -Property 'Username' -PassThru).Value
    $user = Add-Member -InputObject $user -Type NoteProperty -Name 'Value' -Value $MatchAccount

And just importing and exporting the CSV files before and after, in that order.

Body:
here is my approach:

# import csv file1
$file1 = Import-Csv -Path C:\tmp\file1.csv

# import csv file2 and select column "Username"
$file2 = Import-Csv -Path C:\tmp\file2.csv | % {$_.Username}

# create output/result hash table
$file3 = @()

# go through entries in file1
foreach($entry in $file1) {
    # check if entry is in not in file2
    if($file2 -notcontains $entry.Username) {
        # add entry to output hash table
        $file3 += $entry
    }
}

# export result to csv
$file3 | Export-Csv -Path C:\tmp\file3.csv -NoTypeInformation

file3.csv will then have the following contents

Firstname,Lastname,Username
Poul,Hansen,Hansen.123

Best regards
Guenther


问:
How to mock a non static method of a class whose instance is passed as argument?
How to mock a non static method of an argument class passed to a method?
I'm testing below method:

```<code>public Seed getAppleSeed(AppleTree appleTree){
    Seed appleSeed = appleTree.getApple().getSeed();
    //Some logic flow
}
</code>```

Rest of the classes are below:

```<code>public class AppleTree{
    public Apple getApple(){
        return new Apple():
    }
}

public class Apple{
    public Seed getSeed(){
        return new Seed():
    }
}
</code>```

End goal is to test the flow of the getAppleSeed() method for which I need to mock the calls to getApple and getSeed.

Thanks

答:
With mocking, like this:

```<code>AppleTree appleTree = Mockito.mock(AppleTree.class);
Apple apple = Mockito.mock(Apple.class);

Seed seed  = new Seed();

Mockito.when(appleTree.getApple()).thenReturn(apple);
Mockito.when(apple.getSeed()).thenReturn(seed);

Seed actual = getAppleSeed(appleTree);

assertThat(actual, is(seed));
</code>```

Though if the actual code is as simple as what you have outlined in your question then I'd suggest that there is no need to mock Apple or AppleTree.

Body:
How to mock a non static method of an argument class passed to a method?
I'm testing below method:

public Seed getAppleSeed(AppleTree appleTree){
    Seed appleSeed = appleTree.getApple().getSeed();
    //Some logic flow
}

Rest of the classes are below:

public class AppleTree{
    public Apple getApple(){
        return new Apple():
    }
}

public class Apple{
    public Seed getSeed(){
        return new Seed():
    }
}

End goal is to test the flow of the getAppleSeed() method for which I need to mock the calls to getApple and getSeed.

Thanks

Body:
With mocking, like this:

AppleTree appleTree = Mockito.mock(AppleTree.class);
Apple apple = Mockito.mock(Apple.class);

Seed seed  = new Seed();

Mockito.when(appleTree.getApple()).thenReturn(apple);
Mockito.when(apple.getSeed()).thenReturn(seed);

Seed actual = getAppleSeed(appleTree);

assertThat(actual, is(seed));

Though if the actual code is as simple as what you have outlined in your question then I'd suggest that there is no need to mock Apple or AppleTree.


问:
What Exception to throw if (arg1 > arg2) should be fulfilled?
I do not really have a problem to solve, I would just like to know if there is a common way to deal with the following:

I have a constructor that takes two arguments (both int). The constructor itself only initializes attributes of my object. However, if (arg1 > arg2) is not fulfilled, there will be problems later on. Therefore I want to throw an Exception here because this is the place where a potential problem originates.

Is there a common Exception to throw in this case? Or would you rather throw a custom Exception? If so, how would you call that?

答:
This is a good reason to use IllegalArgumentException. You can use it in your class that way:

```<code>class YourClass {
    int first, second;
    YourClass(int first, int second) {
        if(first <= second) {
            throw new IllegalArgumentException("First argument has to be higher than second, arguments passed: " + first + ", " + second);
        }
        this.first = first;
        this.second = second;
    }
}
</code>```

Body:
This is a good reason to use IllegalArgumentException. You can use it in your class that way:

class YourClass {
    int first, second;
    YourClass(int first, int second) {
        if(first <= second) {
            throw new IllegalArgumentException("First argument has to be higher than second, arguments passed: " + first + ", " + second);
        }
        this.first = first;
        this.second = second;
    }
}


问:
Calculate the duration between now and the next midnight using Chrono
What is the idiomatic way to get the duration between now and the next midnight?

I have a function like this:

```<code>extern crate chrono;

use chrono::prelude::*;
use time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now(); // Fri Dec 08 2017 23:00:00 GMT-0300 (-03)
    // ... how to continue??
}
</code>```

It should make a Duration with 1 hour, since the next midnight is Sat Dec 09 2017 00:00:00 GMT-0300 (-03)

答:
After scouring the docs, I finally found the missing link: Date::and_hms.

So, actually, it's as easy as:

```<code>fn main() {
    let now = Local::now();

    let tomorrow_midnight = (now + Duration::days(1)).date().and_hms(0, 0, 0);

    let duration = tomorrow_midnight.signed_duration_since(now).to_std().unwrap();

    println!("Duration between {:?} and {:?}: {:?}", now, tomorrow_midnight, duration);
}
</code>```

The idea is simple:

increase the DateTime to tomorrow,

extract the Date part, which keeps the timezone,

reconstructs a new DateTime by specifying a "00:00:00" Time with and_hms.

There's a panic! in and_hms, so one has to be careful to specify a correct time.

Body:
What is the idiomatic way to get the duration between now and the next midnight?

I have a function like this:

extern crate chrono;

use chrono::prelude::*;
use time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now(); // Fri Dec 08 2017 23:00:00 GMT-0300 (-03)
    // ... how to continue??
}

It should make a Duration with 1 hour, since the next midnight is Sat Dec 09 2017 00:00:00 GMT-0300 (-03)

Body:
After scouring the docs, I finally found the missing link: Date::and_hms.

So, actually, it's as easy as:

fn main() {
    let now = Local::now();

    let tomorrow_midnight = (now + Duration::days(1)).date().and_hms(0, 0, 0);

    let duration = tomorrow_midnight.signed_duration_since(now).to_std().unwrap();

    println!("Duration between {:?} and {:?}: {:?}", now, tomorrow_midnight, duration);
}

The idea is simple:

increase the DateTime to tomorrow,

extract the Date part, which keeps the timezone,

reconstructs a new DateTime by specifying a "00:00:00" Time with and_hms.

There's a panic! in and_hms, so one has to be careful to specify a correct time.


问:
PHP totalling column and simplifying Sessions
I'm trying to total a column in a table of prices and it's not working out for me. I've looked at a ton of solutions such as array_sum() but it's not displaying anything for me. This is a cart page where I'm posting items to a session and then displaying in a for loop. I'm not sure if my sessions are overly complicated or what. Here is my session and post code:

```<code>session_start();

if( $_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['item'][] = array($_POST['item'], $_POST['price']);
}

?>
</code>```

And here is my for loop section of code:

```<code>for($i=0; $i < count($_SESSION['item']); $i++){
    $prices = $_SESSION['item'][$i][1];
         $sum = 0;
         $sum += $_SESSION['item'][$i][1];
         print $sum;
?>

<tr>
    <td class="left"> <?php print_r($_SESSION['item'][$i][0]) ?></td>
    <td class="center"><?php echo "$ " . $_SESSION['item'][$i][1] ?></td>
</tr>

<?php
}
?>

<tr>
    <td class="center">Total:</td>
    <td></td>
</tr>

<?php
}
?>

</table><br>
</code>```

Any help would be greatly appreciated!

答:
At first your code must be like this:

```<code>$sum = 0;
for($i=0; $i < count($_SESSION['item']); $i++){
         $prices = $_SESSION['item'][$i][1];
         $sum += $prices;

?>

<tr>
    <td class="left"> <?php print_r($_SESSION['item'][$i][0]) ?></td>
    <td class="center"><?php echo "$ " . $_SESSION['item'][$i][1] ?></td>
</tr>

<?php
}
?>

<tr>
    <td class="center">Total: <?=$sum?></td>
    <td></td>
</tr>

<?php
}
?>

</table><br>
</code>```

And the second if you want to sum column of prices from database then you can use mysql SUM function
Reference for mysql SUM

Body:
I'm trying to total a column in a table of prices and it's not working out for me. I've looked at a ton of solutions such as array_sum() but it's not displaying anything for me. This is a cart page where I'm posting items to a session and then displaying in a for loop. I'm not sure if my sessions are overly complicated or what. Here is my session and post code:

session_start();

if( $_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['item'][] = array($_POST['item'], $_POST['price']);
}

?>

And here is my for loop section of code:

for($i=0; $i < count($_SESSION['item']); $i++){
    $prices = $_SESSION['item'][$i][1];
         $sum = 0;
         $sum += $_SESSION['item'][$i][1];
         print $sum;
?>

     <?php print_r($_SESSION['item'][$i][0]) ?>
    <?php echo "$ " . $_SESSION['item'][$i][1] ?>

<?php
}
?>

    Total:

<?php
}
?>

Any help would be greatly appreciated!

Body:
At first your code must be like this:

$sum = 0;
for($i=0; $i < count($_SESSION['item']); $i++){
         $prices = $_SESSION['item'][$i][1];
         $sum += $prices;

?>

<tr>
    <td class="left"> <?php print_r($_SESSION['item'][$i][0]) ?></td>
    <td class="center"><?php echo "$ " . $_SESSION['item'][$i][1] ?></td>
</tr>

<?php
}
?>

<tr>
    <td class="center">Total: <?=$sum?></td>
    <td></td>
</tr>

<?php
}
?>

</table><br>

And the second if you want to sum column of prices from database then you can use mysql SUM function
Reference for mysql SUM


问:
Ruby on Rails5: Filtering users by City / Country
what is the best way to structure Location information for users? I need to be able filter hundreds of users by City/Country.

Currently I have created a free-text string for location as I could not find any gem for whole cities grouped under countries. Btw this is a custom scaffold, not devise.

Should I just enter as free-text as in city, country and then filter based on that string with alike?

Thank you

答:
I don't recommend usage of free-tex input because you will get different possible entries for the same city and country which will make filteration an impossible task. It is always better to use a drop down list.

Here is a full list of countries and cities using java script.

change the location attribute with two attributes country and state and use the previous list to fill them.


问:
Sqlalchemy Unexpected Cascading Delete in Flask Application
I'm getting a strage cascading delete (that I haven't configured) when I delete an item from my database. The category entry corresponding to the deleted item is deleted. How do I stop this from happening?

Here's my database setup:

```<code>from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class User(Base):
    """Object holding information about individual registered users"""

    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    email = Column(String(250), nullable=False)
    picture = Column(String(250))

class Category(Base):
    """Object holding information about item categories"""

    __tablename__ = 'category'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

class Item(Base):
    """Object holding information about individual catalog items"""

    __tablename__ = 'item'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    description = Column(String(5000), nullable=False)
    category_id = Column(Integer, ForeignKey('category.id'))
    category = relationship("Category")
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship("User")

engine = create_engine('postgresql+psycopg2://********:********'
                       + '/itemcatalog.db', echo=False)
Base.metadata.create_all(engine)
</code>```

Here's the code the triggers the delete:

```<code>@app.route('/item/<int:item_id>/delete/', methods=['GET', 'POST'])

def delete_item(item_id):
    item = session.query(Item).filter_by(id=item_id).one()

    if request.method == 'POST':
        session.delete(item)
        session.commit()
        flash('Item Successfully Deleted')
        return redirect(url_for('show_catalog'))
    else:
        return render_template('deleteitem.html', item=item,
                               username=login_session['username'],
                               picture=login_session['picture'])
</code>```

The expected behavior is for only the item specified by its "id" to be deleted, and for there to be no changes to the other tables.

The actual result I get is for the item to be deleted, and the entry in the category table corresponding to this item is also deleted.

UPDATE:

The steps I'm taking are:

Creating a new item in the database

Deleting that item

The logs that show this, (and the delete) follow.

Adding the new item:

```<code>2017-12-06 19:32:16 UTC [5383-22] vagrant@itemcatalog.db LOG:  statement: SELECT category.id AS category_id, category.name AS category_name
    FROM category
2017-12-06 19:32:16 UTC [5383-23] vagrant@itemcatalog.db LOG:  statement: INSERT INTO item (name, description, category_id, user_id) VALUES ('Coffee', 'tasty beverage', 3, 2) RETURNING item.id
2017-12-06 19:32:16 UTC [5383-24] vagrant@itemcatalog.db LOG:  statement: COMMIT
2017-12-06 19:32:16 UTC [5383-25] vagrant@itemcatalog.db LOG:  statement: BEGIN
2017-12-06 19:32:16 UTC [5383-26] vagrant@itemcatalog.db LOG:  statement: SELECT category.id AS category_id, category.name AS category_name
    FROM category ORDER BY category.name ASC
2017-12-06 19:32:16 UTC [5383-27] vagrant@itemcatalog.db LOG:  statement: SELECT item.id AS item_id, item.name AS item_name, item.description AS item_description, item.category_id AS item_category_id, item.user_id AS item_user_id
    FROM item ORDER BY item.name ASC
</code>```

Deleting the new item:

```<code>2017-12-06 19:33:14 UTC [5383-30] vagrant@itemcatalog.db LOG:  statement: SELECT item.id AS item_id, item.name AS item_name, item.description AS item_description, item.category_id AS item_category_id, item.user_id AS item_user_id
    FROM item
    WHERE item.id = 7
2017-12-06 19:33:14 UTC [5383-31] vagrant@itemcatalog.db LOG:  statement: SELECT category.id AS category_id, category.name AS category_name
    FROM category
    WHERE category.id = 3
2017-12-06 19:33:14 UTC [5383-32] vagrant@itemcatalog.db LOG:  statement: SELECT item.id AS item_id, item.name AS item_name, item.description AS item_description, item.category_id AS item_category_id, item.user_id AS item_user_id
    FROM item
    WHERE 3 = item.category_id
2017-12-06 19:33:14 UTC [5383-33] vagrant@itemcatalog.db LOG:  statement: UPDATE item SET category_id=NULL WHERE item.id = 5
2017-12-06 19:33:14 UTC [5383-34] vagrant@itemcatalog.db LOG:  statement: UPDATE item SET category_id=NULL WHERE item.id = 6
2017-12-06 19:33:14 UTC [5383-35] vagrant@itemcatalog.db LOG:  statement: DELETE FROM item WHERE item.id = 7
2017-12-06 19:33:14 UTC [5383-36] vagrant@itemcatalog.db LOG:  statement: DELETE FROM category WHERE category.id = 3
2017-12-06 19:33:14 UTC [5383-37] vagrant@itemcatalog.db LOG:  statement: COMMIT
2017-12-06 19:33:14 UTC [5383-38] vagrant@itemcatalog.db LOG:  statement: BEGIN
2017-12-06 19:33:14 UTC [5383-39] vagrant@itemcatalog.db LOG:  statement: SELECT category.id AS category_id, category.name AS category_name
    FROM category ORDER BY category.name ASC
2017-12-06 19:33:14 UTC [5383-40] vagrant@itemcatalog.db LOG:  statement: SELECT item.id AS item_id, item.name AS item_name, item.description AS item_description, item.category_id AS item_category_id, item.user_id AS item_user_id
    FROM item ORDER BY item.name ASC
</code>```

From the logs I can see its not behaving the way I want it to, but I'm at a loss as to what to change to stop this behavior.

答: Thanks for your response larsks, and sorry for the confuion. My mistake was a silly one… I created a new database setup file for testing purposes, and forget to update the path to it in my main app.py file.</p>

Body:
I'm getting a strage cascading delete (that I haven't configured) when I delete an item from my database. The category entry corresponding to the deleted item is deleted. How do I stop this from happening?

Here's my database setup:

from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class User(Base):
    """Object holding information about individual registered users"""

    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    email = Column(String(250), nullable=False)
    picture = Column(String(250))

class Category(Base):
    """Object holding information about item categories"""

    __tablename__ = 'category'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

class Item(Base):
    """Object holding information about individual catalog items"""

    __tablename__ = 'item'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    description = Column(String(5000), nullable=False)
    category_id = Column(Integer, ForeignKey('category.id'))
    category = relationship("Category")
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship("User")

engine = create_engine('postgresql+psycopg2://********:********'
                       + '/itemcatalog.db', echo=False)
Base.metadata.create_all(engine)

Here's the code the triggers the delete:

@app.route('/item/<int:item_id>/delete/', methods=['GET', 'POST'])

def delete_item(item_id):
    item = session.query(Item).filter_by(id=item_id).one()

    if request.method == 'POST':
        session.delete(item)
        session.commit()
        flash('Item Successfully Deleted')
        return redirect(url_for('show_catalog'))
    else:
        return render_template('deleteitem.html', item=item,
                               username=login_session['username'],
                               picture=login_session['picture'])

The expected behavior is for only the item specified by its "id" to be deleted, and for there to be no changes to the other tables.

The actual result I get is for the item to be deleted, and the entry in the category table corresponding to this item is also deleted.

UPDATE:

The steps I'm taking are:

Creating a new item in the database

Deleting that item

The logs that show this, (and the delete) follow.

Adding the new item:

2017-12-06 19:32:16 UTC [5383-22] vagrant@itemcatalog.db LOG:  statement: SELECT category.id AS category_id, category.name AS category_name
    FROM category
2017-12-06 19:32:16 UTC [5383-23] vagrant@itemcatalog.db LOG:  statement: INSERT INTO item (name, description, category_id, user_id) VALUES ('Coffee', 'tasty beverage', 3, 2) RETURNING item.id
2017-12-06 19:32:16 UTC [5383-24] vagrant@itemcatalog.db LOG:  statement: COMMIT
2017-12-06 19:32:16 UTC [5383-25] vagrant@itemcatalog.db LOG:  statement: BEGIN
2017-12-06 19:32:16 UTC [5383-26] vagrant@itemcatalog.db LOG:  statement: SELECT category.id AS category_id, category.name AS category_name
    FROM category ORDER BY category.name ASC
2017-12-06 19:32:16 UTC [5383-27] vagrant@itemcatalog.db LOG:  statement: SELECT item.id AS item_id, item.name AS item_name, item.description AS item_description, item.category_id AS item_category_id, item.user_id AS item_user_id
    FROM item ORDER BY item.name ASC

Deleting the new item:

2017-12-06 19:33:14 UTC [5383-30] vagrant@itemcatalog.db LOG:  statement: SELECT item.id AS item_id, item.name AS item_name, item.description AS item_description, item.category_id AS item_category_id, item.user_id AS item_user_id
    FROM item
    WHERE item.id = 7
2017-12-06 19:33:14 UTC [5383-31] vagrant@itemcatalog.db LOG:  statement: SELECT category.id AS category_id, category.name AS category_name
    FROM category
    WHERE category.id = 3
2017-12-06 19:33:14 UTC [5383-32] vagrant@itemcatalog.db LOG:  statement: SELECT item.id AS item_id, item.name AS item_name, item.description AS item_description, item.category_id AS item_category_id, item.user_id AS item_user_id
    FROM item
    WHERE 3 = item.category_id
2017-12-06 19:33:14 UTC [5383-33] vagrant@itemcatalog.db LOG:  statement: UPDATE item SET category_id=NULL WHERE item.id = 5
2017-12-06 19:33:14 UTC [5383-34] vagrant@itemcatalog.db LOG:  statement: UPDATE item SET category_id=NULL WHERE item.id = 6
2017-12-06 19:33:14 UTC [5383-35] vagrant@itemcatalog.db LOG:  statement: DELETE FROM item WHERE item.id = 7
2017-12-06 19:33:14 UTC [5383-36] vagrant@itemcatalog.db LOG:  statement: DELETE FROM category WHERE category.id = 3
2017-12-06 19:33:14 UTC [5383-37] vagrant@itemcatalog.db LOG:  statement: COMMIT
2017-12-06 19:33:14 UTC [5383-38] vagrant@itemcatalog.db LOG:  statement: BEGIN
2017-12-06 19:33:14 UTC [5383-39] vagrant@itemcatalog.db LOG:  statement: SELECT category.id AS category_id, category.name AS category_name
    FROM category ORDER BY category.name ASC
2017-12-06 19:33:14 UTC [5383-40] vagrant@itemcatalog.db LOG:  statement: SELECT item.id AS item_id, item.name AS item_name, item.description AS item_description, item.category_id AS item_category_id, item.user_id AS item_user_id
    FROM item ORDER BY item.name ASC

From the logs I can see its not behaving the way I want it to, but I'm at a loss as to what to change to stop this behavior.


问:
How to insert blank rows when number of record is less than rows fixed in detail section
How to fix Number of rows in detail section and insert blank rows if number of record less than rows fixed in detail section eg. Suppose there are fix 8 rows and if 2 rows are shown then 6 rows should be left blank?</p>

答:
First of all fix height detail section by right click on detail section
Detail Section->Section Expert click on paging Tab->Check in New Page Before checkbox and beside it (x+2)button write formula->
(Suppose you want 8 rows to display in your report per page and additional rows(9th row,10th row and so on... to another page)
IF Remainder (RecordNumber, 9) = 0 THEN
    TRUE
ELSE
    FALSE
so now your height is fixed.. and for blank rows
suppose 2 records/rows are coming from data table/data source then from 8 fixed rows , 6 rows should be blank rows for that..
design your detail section with fields and keep report footer(section 4) blank with with some spaces(i want 8 rows fixed so keep size of 8 rows blank assuming in report footer) and put footer details in your section 5(page footer)..

if your header or footer  is not visible on another page then put all header parts details in page header and footer details in page footer

:)


问:
Removing objects from Tiled Map after collision

Hello guys!

I'm creating a 2D-game similar to Mario Bros, by using Libgdx. I have watched Mario Bros tutorials on YouTube. I put diamonds inside Tiled map to make the player collects these diamonds. I have succeed with the collision. But, I have Two problems:
-First, I can't make all diamonds disappear after the collision (just one diamond disappears).
- Second, if(f2.getUserData() instanceof Treasure) doesn't work.

    This is my code:

```<code>public TiledMapTileLayer.Cell getCell(){
    TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(8);
    return  layer.getCell((int) (body.getPosition().x * MainGame.PPM / 64),
            (int) (body.getPosition().y * MainGame.PPM / 64));

}

if(f1.getUserData() == "HARRY" && f2.getUserData() == "COINS"){
        System.out.println("coins");
        //if(f2.getUserData() instanceof Treasure){
            System.out.println("Works");
         treasure.getCell().setTile(null);
        //}

    }
</code>```

I expect diamonds will disappear when the player collides with.

But the result was, if I put (treasure.getCell().setTile(null);) inside if statement doesn't work. And, if I put it without the if statement just one diamond disappears, and not the one that the player collides with. The first diamond that I put inside the Tiled map disappears

答:
A couple concerning things...

In Java == compares references when it comes to objects like Strings (so only true if both are referencing the same object). So f2.getUserData() == "COINS" seems like it should be: "COINS".equals((String) f2.getUserData()), which will compare the actual character sequence of the String in question (also... "COINS" first to avoid any possible NullPointerException).

Based on your code, if(f2.getUserData() instanceof Treasure) is comparing a Treasure object to what seems like a String (unless Treasure extends String or something - I'm not familiar with the library you are using).

Are you setting the value for f2.getUserData()? If so, use a Treasure object instead of a String instance of "COINS". Maybe it has a constructor like this Treasure coins = new Treasure("COINS") or something.

This code: treasure.getCell().setTile(null); is referencing an object (that I assume is a Treasure object) that isn't defined in your sample code (ie. Its probably defined somewhere above in your source compared to the sample code provided). Which is probably why only the one diamond is disappearing. I think you mean something more like this (assuming Treasure extends String or something like that...):

if("HARRY".equals(f1.getUserData()) && "COINS".equals(f2.getUserData())){
    System.out.println("coins");
    if(f2.getUserData() instanceof Treasure){
        System.out.println("Works");
        ((Treasure)f2.getUserData()).getCell().setTile(null);
    }
 }

Hope that helps and makes sense!

Body:
Hello guys!

I'm creating a 2D-game similar to Mario Bros, by using Libgdx. I have watched Mario Bros tutorials on YouTube. I put diamonds inside Tiled map to make the player collects these diamonds. I have succeed with the collision. But, I have Two problems:
-First, I can't make all diamonds disappear after the collision (just one diamond disappears).
- Second, if(f2.getUserData() instanceof Treasure) doesn't work.

    This is my code:

public TiledMapTileLayer.Cell getCell(){
    TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(8);
    return  layer.getCell((int) (body.getPosition().x * MainGame.PPM / 64),
            (int) (body.getPosition().y * MainGame.PPM / 64));

}

if(f1.getUserData() == "HARRY" && f2.getUserData() == "COINS"){
        System.out.println("coins");
        //if(f2.getUserData() instanceof Treasure){
            System.out.println("Works");
         treasure.getCell().setTile(null);
        //}

    }

I expect diamonds will disappear when the player collides with.

But the result was, if I put (treasure.getCell().setTile(null);) inside if statement doesn't work. And, if I put it without the if statement just one diamond disappears, and not the one that the player collides with. The first diamond that I put inside the Tiled map disappears


问:
Extract JSON data from struct in struct
See the output of a deserializeJSON(query).

For each row, how i can extract only id and DTIME? Following is my code:

```<code> <cfscript>
  record=deserializeJSON(query_testing.data_test);

  writeDump(record);

</cfscript>
</code>```

Below is a sample data in "query_testing.data_test":

```<code> '{"id3":
        {"DECISION":1,
        "DTIME":"2013-10-18 16:17:28"},
   "id5":
        {"DECISION":1,
        "DTIME":"2013-10-09 15:43:35",}
  }'
</code>```

答:
```<code><cfscript>

    record = deserializeJSON(query_testing.data_test);

    rows = [];
    for (id in record) {

        rows.add({
            id:    reReplace(id, "^id", ""),
            dtime: record[id].DTIME
        });
    }
    writeDump(rows);

</cfscript>
</code>```

Here's the tag variant and a usage example as requested:

```<code><cfset record = deserializeJSON(query_testing.data_test)>

<cfset rows = []>
<cfloop collection="#record#" item="id">

    <cfset rows.add({
        id:    reReplace(id, "^id", ""),
        dtime: record[id].DTIME
    })>
</cfloop>
<cfdump var="#rows#">

<!--- print as table --->
<cfoutput>
    <table>
        <tr>
            <th>id</th>
            <th>dtime</th>
        </tr>
        <cfloop array="#rows#" index="row">
            <tr>
                <td>#encodeForHtml(row.id)#</td>
                <td>#dateTimeFormat(row.dtime, "yyyy-mm-dd, HH:nn:ss")#</td>
            </tr>
        </cfloop>
    </table>
</cfoutput>
</code>```

Title: Extract JSON data from struct in struct

Body:
See the output of a deserializeJSON(query).

For each row, how i can extract only id and DTIME? Following is my code:

 <cfscript>
  record=deserializeJSON(query_testing.data_test);

  writeDump(record);

</cfscript>

Below is a sample data in "query_testing.data_test":

 '{"id3":
        {"DECISION":1,
        "DTIME":"2013-10-18 16:17:28"},
   "id5":
        {"DECISION":1,
        "DTIME":"2013-10-09 15:43:35",}
  }'

Body:
<cfscript>

    record = deserializeJSON(query_testing.data_test);

    rows = [];
    for (id in record) {

        rows.add({
            id:    reReplace(id, "^id", ""),
            dtime: record[id].DTIME
        });
    }
    writeDump(rows);

</cfscript>

Here's the tag variant and a usage example as requested:

<cfset record = deserializeJSON(query_testing.data_test)>

<cfset rows = []>
<cfloop collection="#record#" item="id">

    <cfset rows.add({
        id:    reReplace(id, "^id", ""),
        dtime: record[id].DTIME
    })>
</cfloop>
<cfdump var="#rows#">

<!--- print as table --->
<cfoutput>
    <table>
        <tr>
            <th>id</th>
            <th>dtime</th>
        </tr>
        <cfloop array="#rows#" index="row">
            <tr>
                <td>#encodeForHtml(row.id)#</td>
                <td>#dateTimeFormat(row.dtime, "yyyy-mm-dd, HH:nn:ss")#</td>
            </tr>
        </cfloop>
    </table>
</cfoutput>


问:
PHP Form Redirect Based Off of Drop Down Selection
This relates to a previous question I had asked about filling out a php form and using those answers to populate a page. When finished filling out the form, I want to determine what page it goes to after you submit the form by a dropdown you choose while filling out the form.

For example, you type in:

Your Name

Email

Phone Number

Then from a drop down you'd pick "Page 3".

Then hit submit.

I would need it then to redirect you to "Page 3" because that's the one you chose in the drop down. I know this should be simple, I just can't seem to figure out how to do it. Thank you in advance to all that help!

答:
In the script your form submits to:

```<code>if ($_POST['dropdown-name'] == 'Page 3') {
    header("Location: page3.php");
} else if ($_POST['dropdown-name'] == 'Page 4') {
    header("Location: page4.php");
} // ... etc
</code>```

~

```<code>$pages = array('Page 1' => 'page1.php', 'Page 2' => 'page2.php', 'Page 3' => 'page3.php');

if (array_key_exists($_POST['dropdown-name'], $pages)) {
    header("Location: " . $pages[$_POST['dropdown-name']]);
} else {
    echo "Error processing form"; // submitted form value wasn't in your array, perhaps a hack attempt
}
</code>```

Body:
In the script your form submits to:

if ($_POST['dropdown-name'] == 'Page 3') {
    header("Location: page3.php");
} else if ($_POST['dropdown-name'] == 'Page 4') {
    header("Location: page4.php");
} // ... etc

~

$pages = array('Page 1' => 'page1.php', 'Page 2' => 'page2.php', 'Page 3' => 'page3.php');

if (array_key_exists($_POST['dropdown-name'], $pages)) {
    header("Location: " . $pages[$_POST['dropdown-name']]);
} else {
    echo "Error processing form"; // submitted form value wasn't in your array, perhaps a hack attempt
}