问:
Make linux SPLIT command compatible with Mac OS terminal
I have a bash script that works fine in linux, but when I run it on my Mac terminal it fails, as the options for the splitcommand are slightly different in Mac terminal. My script is:

```<code>## Merge and half final two segments
last_file=`ls temp_filt.snplist_* | tail -n 1`
penultimate_file=`ls temp_filt.snplist_* | tail -n 2 | head -1`
cat $penultimate_file $last_file > temp && mv temp $penultimate_file
split -n l/2 $penultimate_file && mv xaa $penultimate_file; mv xab $last_file
</code>```

The script fails at the final line, since the -n l/2 doesn't exist in tcsh (default shel environment in Mac OS 10.x.x). I was wondering what is the equivalent script in tcsh.

Is there a generic way to run linux script in Mac OS terminal, without the need to change the script?

答:
It's not the MacOS terminal that's doing the split. It's a programm called split. MacOS is built on the FreeBSD userland tools, which behave differently from the GNU utils.

There are two options:

Install the FreeBSD tools on your Linux boxes to make them compatible with FreeBSD.

Install the GNU utils on your MacOS machine. If you have brew you can do this with brew install coreutils

Body:
I have a bash script that works fine in linux, but when I run it on my Mac terminal it fails, as the options for the splitcommand are slightly different in Mac terminal. My script is:

## Merge and half final two segments
last_file=`ls temp_filt.snplist_* | tail -n 1`
penultimate_file=`ls temp_filt.snplist_* | tail -n 2 | head -1`
cat $penultimate_file $last_file > temp && mv temp $penultimate_file
split -n l/2 $penultimate_file && mv xaa $penultimate_file; mv xab $last_file

The script fails at the final line, since the -n l/2 doesn't exist in tcsh (default shel environment in Mac OS 10.x.x). I was wondering what is the equivalent script in tcsh.

Is there a generic way to run linux script in Mac OS terminal, without the need to change the script?


来源: stackexchange

问:
How to set the output of the Asynchronous Task to the text view of the Main Activity
```<code>public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}
</code>```

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.

答:
Pass the textview object from MainActivity in Constructor of CheckLoginCredentialsTask and create object of textview in MainActivity,Like this

```<code>TextView tvEmpId,tvType,tvDept_code;

 CheckLoginCredentialsTask (Context context,String id,String pwd,TextView tvEmpId,TextView tvType,TextView tvDept_code)
  {
  this.context=context;
  this.employeeId=id;
  this.password=pwd;
  this.tvEmpId=tvEmpId;
  this.tvType=tvType;
  this.tvDept_code=tvDept_code;
  }
</code>```

and don't create object MainActivity like this

```<code>MainActivity obj = new MainActivity();
</code>```

set text in TextView

```<code> tvEmpId.setText(empDetails.EmpID);
 tvType.setText(empDetails.EmpType);
 tvDept_code.setText(empDetails.DEPT_CODE);
</code>```

In MainActivity

```<code>    TextView  tvEmpId=(TextView)findViewById(R.id.tvEmpId);
    TextView  tvType=(TextView)findViewById(R.id.tvType);
    TextView  tvDept_code=(TextView)findViewById(R.id.tvDept_code);

    CheckLoginCredentialsTask checkLoginCredentialsTask =new CheckLoginCredentialsTask (getApplicationContext(),"id","password",tvEmpId,tvType,tvDept_code);
    checkLoginCredentialsTask.execute();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.

Body:
Pass the textview object from MainActivity in Constructor of CheckLoginCredentialsTask and create object of textview in MainActivity,Like this

TextView tvEmpId,tvType,tvDept_code;

 CheckLoginCredentialsTask (Context context,String id,String pwd,TextView tvEmpId,TextView tvType,TextView tvDept_code)
  {
  this.context=context;
  this.employeeId=id;
  this.password=pwd;
  this.tvEmpId=tvEmpId;
  this.tvType=tvType;
  this.tvDept_code=tvDept_code;
  }

and don't create object MainActivity like this

MainActivity obj = new MainActivity();

set text in TextView

 tvEmpId.setText(empDetails.EmpID);
 tvType.setText(empDetails.EmpType);
 tvDept_code.setText(empDetails.DEPT_CODE);

In MainActivity

    TextView  tvEmpId=(TextView)findViewById(R.id.tvEmpId);
    TextView  tvType=(TextView)findViewById(R.id.tvType);
    TextView  tvDept_code=(TextView)findViewById(R.id.tvDept_code);

    CheckLoginCredentialsTask checkLoginCredentialsTask =new CheckLoginCredentialsTask (getApplicationContext(),"id","password",tvEmpId,tvType,tvDept_code);
    checkLoginCredentialsTask.execute();


问:
Map activity does not show up in my phone because I have many activities
I created new activity which is map activity. I think I have problem in AndroidManofest.xml.
My phone works perfectly if I create new project with just map activity. If I add it to my project, which has a lot of activities, it does not work. I do not know why.

the problem is about the activities
  AndroidManofest.xml

I checked every thing APU is enable

AndroidManofest.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.abdullahalhajri.smarttutor">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activities.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.RegisterActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomePage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchPage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchRating"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchSubject"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.MathTutor"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.ReviewComment"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.TutorProfile"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.UsersActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".activities.MapsActivity"
            android:label="@string/title_activity_maps">

        </activity>
    </application>

</manifest>
</code>```

Error

```<code>12-04 04:31:22.639 25820-26431/com.example.abdullahalhajri.smarttutor E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
                                                                                Ensure that the "Google Maps Android API v2" is enabled.
                                                                                Ensure that the following Android Key exists:
                                                                                API Key: <<redacted>>
</code>```

答: change your google Map API key. you cant use Same Api key in different projects

Body:
I created new activity which is map activity. I think I have problem in AndroidManofest.xml.
My phone works perfectly if I create new project with just map activity. If I add it to my project, which has a lot of activities, it does not work. I do not know why.

the problem is about the activities
  AndroidManofest.xml

I checked every thing APU is enable

AndroidManofest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.abdullahalhajri.smarttutor">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activities.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.RegisterActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomePage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchPage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchRating"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchSubject"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.MathTutor"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.ReviewComment"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.TutorProfile"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.UsersActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".activities.MapsActivity"
            android:label="@string/title_activity_maps">

        </activity>
    </application>

</manifest>

Error

12-04 04:31:22.639 25820-26431/com.example.abdullahalhajri.smarttutor E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
                                                                                Ensure that the "Google Maps Android API v2" is enabled.
                                                                                Ensure that the following Android Key exists:
                                                                                API Key: <<redacted>>


问:
Jackson Deserialize to POJO Based On Object Properties
Is it possible to deserialize JSON using Jackson into one of two types based on the content of the JSON?

For example, I have the following Java (technically Groovy, but that's not important) interfaces and classes:

```<code>interface Id {
    Thing toThing()
}

class NaturalId implements Id {

    final String packageId

    final String thingId

    Thing toThing() {
        new PackageIdentifiedThing(packageId, thingId)
    }
}

class AlternateId implements Id {

    final String key

    Thing toThing() {
        new AlternatelyIdentifiedThing(key)
    }
}
</code>```

The JSON I will receive will look like either of the following:

This JSON should map to NaturalId {"packageId": "SomePackage", "thingId": "SomeEntity"}

This JSON should map to AlternateId {"key": "SomeUniqueKey"}

Does anyone know how I can accomplish this with Jackson 2.x WITHOUT including type id's?

答:
With Jackson2, you can easily  marshall to different classes using generics:</p>

```<code>private <T> T json2Object(String jsonString, String type, Class<T> clazz) {
    JsonNode jsonObjectNode = getChildNode(jsonString, type);
    T typeObject = null;
    try {
        typeObject = jacksonMapper.treeToValue(jsonObjectNode, clazz);
    } catch (JsonProcessingException jsonProcessingException) {
        LOGGER.severe(jsonProcessingException);
    }
    return typeObject;
}
</code>```

Body:
Is it possible to deserialize JSON using Jackson into one of two types based on the content of the JSON?

For example, I have the following Java (technically Groovy, but that's not important) interfaces and classes:

interface Id {
    Thing toThing()
}

class NaturalId implements Id {

    final String packageId

    final String thingId

    Thing toThing() {
        new PackageIdentifiedThing(packageId, thingId)
    }
}

class AlternateId implements Id {

    final String key

    Thing toThing() {
        new AlternatelyIdentifiedThing(key)
    }
}

The JSON I will receive will look like either of the following:

This JSON should map to NaturalId {"packageId": "SomePackage", "thingId": "SomeEntity"}

This JSON should map to AlternateId {"key": "SomeUniqueKey"}

Does anyone know how I can accomplish this with Jackson 2.x WITHOUT including type id's?

Body:
With Jackson2, you can easily  marshall to different classes using generics:

private <T> T json2Object(String jsonString, String type, Class<T> clazz) {
    JsonNode jsonObjectNode = getChildNode(jsonString, type);
    T typeObject = null;
    try {
        typeObject = jacksonMapper.treeToValue(jsonObjectNode, clazz);
    } catch (JsonProcessingException jsonProcessingException) {
        LOGGER.severe(jsonProcessingException);
    }
    return typeObject;
}


问:
How to connect to my http://localhost web server from MEmu Android emulator
How to connect to my http://localhost web server from MEmu Android emulator for development with android studio and MVC or PHP web service.</p>

答: I couldn't access localhost via http://10.0.3.2:<hostport> instead I had to use: http://10.0.2.2:<hostport>


问:
Should I use alias or alias_method?
I found a blog post on alias vs. alias_method. As shown in the example given in that blog post, I simply want to alias a method to another within the same class. Which should I use? I always see alias used, but someone told me alias_method is better.

Usage of alias

```<code>class User

  def full_name
    puts "Johnnie Walker"
  end

  alias name full_name
end

User.new.name #=>Johnnie Walker
</code>```

Usage of alias_method

```<code>class User

  def full_name
    puts "Johnnie Walker"
  end

  alias_method :name, :full_name
end

User.new.name #=>Johnnie Walker
</code>```

Blog post link here

答:
alias_method can be redefined if need be. (it's defined in the Module class.)

alias's behavior changes depending on its scope and can be quite unpredictable at times.

Verdict: Use alias_method - it gives you a ton more flexibility.

Usage:

```<code>def foo
  "foo"
end

alias_method :baz, :foo
</code>```

Title: Should I use alias or alias_method?

Body:
I found a blog post on alias vs. alias_method. As shown in the example given in that blog post, I simply want to alias a method to another within the same class. Which should I use? I always see alias used, but someone told me alias_method is better.

Usage of alias

class User

  def full_name
    puts "Johnnie Walker"
  end

  alias name full_name
end

User.new.name #=>Johnnie Walker

Usage of alias_method

class User

  def full_name
    puts "Johnnie Walker"
  end

  alias_method :name, :full_name
end

User.new.name #=>Johnnie Walker

Blog post link here

Body:
alias_method can be redefined if need be. (it's defined in the Module class.)

alias's behavior changes depending on its scope and can be quite unpredictable at times.

Verdict: Use alias_method - it gives you a ton more flexibility.

Usage:

def foo
  "foo"
end

alias_method :baz, :foo


问:
Symfony session handler default location tries to create directory
I have a Symfony 3.3.5 application for which I want to use the default session handler:

```<code>framework:
    session:
        handler_id: session.handler.native_file
        save_path: null
</code>```

However when I do this, Symfony tries to create the /var/lib/php/sessions directory, which already exists:

```<code>    [2017-08-01 14:24:37] request.CRITICAL: Uncaught PHP Exception RuntimeException: "Session Storage was not able to create directory "/var/lib/php/sessions"" at /home/infoodlebiz/www/site/vendor/symfony/symfony/src/
Symfony/Component/HttpFoundation/Session/Storage/Handler/NativeFileSessionHandler.php line 52 {"exception":"[object] (RuntimeException(code: 0): Session Storage was not able to create directory \"/var/lib/php/sessions\" at /home/infoodlebiz/www/site/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/NativeFileSessionHandler.php:52)"} []
</code>```

I cannot see why this would be, the directory is world readable, writeable:

```<code>ls -la /var/lib/php/sessions/
total 176
drwx-wx-wt 2 root       root       110592 Aug  1 14:28 .
drwxr-xr-x 4 root       root         4096 Oct 16  2016 ..
-rw------- 1 globalyear globalyear    305 Aug  1 14:04 sess_1u179qdaqcihhkmmi4qepj2na0
-rw------- 1 globalyear globalyear    305 Aug  1 14:15 sess_5p76n0falmf0rmogs4v2s9sss5
-rw------- 1 globalyear globalyear    304 Aug  1 13:49 sess_65i7jlca6ifhs8k1ucdkf8d091
-rw------- 1 cbc        cbc           213 Aug  1 14:28 sess_9hfobt8p6lu056avq2udiq7ck0
-rw------- 1 cbc        cbc           213 Aug  1 14:06 sess_b6mdvgj6v6ip1l1pi77upnc845
</code>```

directory above is not

```<code>ls -la /var/lib/php/
total 124
drwxr-xr-x  4 root root   4096 Oct 16  2016 .
drwxr-xr-x 49 root root   4096 Mar 29 13:39 ..
drwxr-xr-x  3 root root   4096 Oct 16  2016 modules
drwx-wx-wt  2 root root 110592 Aug  1 15:25 sessions
</code>```

PHP is running as PHP-FPM under its own user name using sockets

答:
I had identical symptoms using Apache 2.4 on a CentOS 7, running php-fpm 7.1 by the way of module fast-cgi.

Sessions storage folder was configured to be /var/lib/php/fpm/session, and /var/lib/php/fpm is a remote folder mounted by root user throught NFSv3.

And finally /etc/php-fpm.d/www.conf had following parameters:

```<code>user = apache
group = apache
</code>```

In my case, even having added user apache into php-fpm group, and having settled /var/lib/php/fpm/session permissions as following

```<code>$ ls -lad /var/lib/php/fpm/session
drwxrwx--- 2 root php-fpm 487 dic  4 11:54 /var/lib/php/fpm/session
</code>```

**In order to mitigate the error reported by Symfony 2.7, it was necessary to force apache user ownership of /var/lib/php/fpm and /var/lib/php/fpm/session this way:

```<code>chown apache /var/lib/php/fpm
chown apache /var/lib/php/fpm/session
</code>```

Hope it helps

Body:
I have a Symfony 3.3.5 application for which I want to use the default session handler:

framework:
    session:
        handler_id: session.handler.native_file
        save_path: null

However when I do this, Symfony tries to create the /var/lib/php/sessions directory, which already exists:

    [2017-08-01 14:24:37] request.CRITICAL: Uncaught PHP Exception RuntimeException: "Session Storage was not able to create directory "/var/lib/php/sessions"" at /home/infoodlebiz/www/site/vendor/symfony/symfony/src/
Symfony/Component/HttpFoundation/Session/Storage/Handler/NativeFileSessionHandler.php line 52 {"exception":"[object] (RuntimeException(code: 0): Session Storage was not able to create directory \"/var/lib/php/sessions\" at /home/infoodlebiz/www/site/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/NativeFileSessionHandler.php:52)"} []

I cannot see why this would be, the directory is world readable, writeable:

ls -la /var/lib/php/sessions/
total 176
drwx-wx-wt 2 root       root       110592 Aug  1 14:28 .
drwxr-xr-x 4 root       root         4096 Oct 16  2016 ..
-rw------- 1 globalyear globalyear    305 Aug  1 14:04 sess_1u179qdaqcihhkmmi4qepj2na0
-rw------- 1 globalyear globalyear    305 Aug  1 14:15 sess_5p76n0falmf0rmogs4v2s9sss5
-rw------- 1 globalyear globalyear    304 Aug  1 13:49 sess_65i7jlca6ifhs8k1ucdkf8d091
-rw------- 1 cbc        cbc           213 Aug  1 14:28 sess_9hfobt8p6lu056avq2udiq7ck0
-rw------- 1 cbc        cbc           213 Aug  1 14:06 sess_b6mdvgj6v6ip1l1pi77upnc845

directory above is not

ls -la /var/lib/php/
total 124
drwxr-xr-x  4 root root   4096 Oct 16  2016 .
drwxr-xr-x 49 root root   4096 Mar 29 13:39 ..
drwxr-xr-x  3 root root   4096 Oct 16  2016 modules
drwx-wx-wt  2 root root 110592 Aug  1 15:25 sessions

PHP is running as PHP-FPM under its own user name using sockets

Body:
I had identical symptoms using Apache 2.4 on a CentOS 7, running php-fpm 7.1 by the way of module fast-cgi.

Sessions storage folder was configured to be /var/lib/php/fpm/session, and /var/lib/php/fpm is a remote folder mounted by root user throught NFSv3.

And finally /etc/php-fpm.d/www.conf had following parameters:

user = apache
group = apache

In my case, even having added user apache into php-fpm group, and having settled /var/lib/php/fpm/session permissions as following

$ ls -lad /var/lib/php/fpm/session
drwxrwx--- 2 root php-fpm 487 dic  4 11:54 /var/lib/php/fpm/session

**In order to mitigate the error reported by Symfony 2.7, it was necessary to force apache user ownership of /var/lib/php/fpm and /var/lib/php/fpm/session this way:

chown apache /var/lib/php/fpm
chown apache /var/lib/php/fpm/session

Hope it helps


问:
How to store the result of each iteration of a for loop into an array in java
Score Finder (100 Marks)

Praveen is finding a job as a Computer Science teacher in school.
He has been rejected many times by different schools but this time he is determined to get the job.
He goes to the principal of the school St. Mary.

The principal says that in his school there is Grading and Credit system.
There are N subjects and each subject has a credit Ci attached to it (1 <= i <= N).
Each student gets a particular grade in each subject and each grade has a point value which are:

```<code>A = 10,
A(minus) = 9,
B = 8,
B(minus) = 7,
C = 6,
C(minus) = 5
</code>```

Now if there are 3 subjects of credits 4, 3 and 2 respectively and a particular student scores A(minus),
B and C in these 3 subjects respectively then his score would be calculated as follows:
Total Score=Summation of product of Grade point and corresponding credit for each subject.

```<code>= ( (9*4) + (3*8) + (2*6) ) = 72.
</code>```

He wants Praveen to tell total distinct Scores that are possible
to be given to a student given credits of N subjects by assigning different grades to each subject.

Input Format
Your function contains a single argument- a one-dimensional Integer Array A of N elements where each represents Credit of that subject.
The first line of input contains an Integer N denoting the size of the array.
Next N lines of input each containing an Integer denoting the credit Ci of ith subject

```<code>Constraints
1 <= N <= 100
1 <= Ci <= 5
</code>```

Output Format
You must return a single integer denoting the total number of scores that are possible to be given.

```<code>Sample TestCase 1
Input

2
1
2
Output

16
</code>```

now I am writing code like this

```<code>package javaapplication1;

import java.util.Scanner;

public class CandidateCode {
    private static void possibleCombination(int input) {
        int i=0;
        int[] a=new int[Grades.length];

        a[i]=input;
        System.out.println("the a is "+a[i]);
    }

    private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

    public static void main(String[] args) {
        int i=0,j,totalSummation=0;
        Scanner uInput = new Scanner(System.in);
        System.out.println("Enter length of Array:");
        int index = uInput.nextInt();
        int[] Credit = new int[index];
        for (i = 0; i <= Credit.length-1; i++) {
            Credit[i] = uInput.nextInt();
            System.out.println("credit is" + Credit[i]);
            for ( j = 0; j <= Grades.length - 1; j++) {
                totalSummation = +(Grades[j] * Credit[i]);
                possibleCombination(totalSummation);
                // System.out.println("total sum is " + totalSummation);
            }
        }
    }
}
</code>```

Now I want to store the values calculated in each iteration...
Meaning for
iteration first the values are 10,9,8,7,6,5,4,3,2,1
itertion second the values are 20,18,16,14,10,8,6,4,2

i want to sum each value of 1st iteration with all the values of 2nd iteration.
i,e 10+20, 10+18, 10+16, 10+14, 10+10, 10+8, 10+6, 10+4, 10+2
similarly for 9,8,7,6,5,4,3,2,1

To achieve this I need to store the values per iteration but I am stuck here, please guys help me to get rid of this problem thank you in advance.

答:
Ok, following our discussion in comments: you don't need two for loops.

```<code>for i = 0; i < array.size(); i++ {
    sum += grade[i]*credit[i]
 }
</code>```

Sorry for the generic coding style. Is it what you want?

Body:
Score Finder (100 Marks)

Praveen is finding a job as a Computer Science teacher in school.
He has been rejected many times by different schools but this time he is determined to get the job.
He goes to the principal of the school St. Mary.

The principal says that in his school there is Grading and Credit system.
There are N subjects and each subject has a credit Ci attached to it (1 <= i <= N).
Each student gets a particular grade in each subject and each grade has a point value which are:

A = 10,
A(minus) = 9,
B = 8,
B(minus) = 7,
C = 6,
C(minus) = 5

Now if there are 3 subjects of credits 4, 3 and 2 respectively and a particular student scores A(minus),
B and C in these 3 subjects respectively then his score would be calculated as follows:
Total Score=Summation of product of Grade point and corresponding credit for each subject.

= ( (9*4) + (3*8) + (2*6) ) = 72.

He wants Praveen to tell total distinct Scores that are possible
to be given to a student given credits of N subjects by assigning different grades to each subject.

Input Format
Your function contains a single argument- a one-dimensional Integer Array A of N elements where each represents Credit of that subject.
The first line of input contains an Integer N denoting the size of the array.
Next N lines of input each containing an Integer denoting the credit Ci of ith subject

Constraints
1 <= N <= 100
1 <= Ci <= 5

Output Format
You must return a single integer denoting the total number of scores that are possible to be given.

Sample TestCase 1
Input

2
1
2
Output

16

now I am writing code like this

package javaapplication1;

import java.util.Scanner;

public class CandidateCode {
    private static void possibleCombination(int input) {
        int i=0;
        int[] a=new int[Grades.length];

        a[i]=input;
        System.out.println("the a is "+a[i]);
    }

    private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

    public static void main(String[] args) {
        int i=0,j,totalSummation=0;
        Scanner uInput = new Scanner(System.in);
        System.out.println("Enter length of Array:");
        int index = uInput.nextInt();
        int[] Credit = new int[index];
        for (i = 0; i <= Credit.length-1; i++) {
            Credit[i] = uInput.nextInt();
            System.out.println("credit is" + Credit[i]);
            for ( j = 0; j <= Grades.length - 1; j++) {
                totalSummation = +(Grades[j] * Credit[i]);
                possibleCombination(totalSummation);
                // System.out.println("total sum is " + totalSummation);
            }
        }
    }
}

Now I want to store the values calculated in each iteration...
Meaning for
iteration first the values are 10,9,8,7,6,5,4,3,2,1
itertion second the values are 20,18,16,14,10,8,6,4,2

i want to sum each value of 1st iteration with all the values of 2nd iteration.
i,e 10+20, 10+18, 10+16, 10+14, 10+10, 10+8, 10+6, 10+4, 10+2
similarly for 9,8,7,6,5,4,3,2,1

To achieve this I need to store the values per iteration but I am stuck here, please guys help me to get rid of this problem thank you in advance.

Body:
Ok, following our discussion in comments: you don't need two for loops.

for i = 0; i < array.size(); i++ {
    sum += grade[i]*credit[i]
 }

Sorry for the generic coding style. Is it what you want?


问:
Heroku and GoDaddy DNS configuration
I have been struggling to configure my Heroku to point to my domain name registered with GoDaddy.

I've setup my Heroku domain:

And I've configured my CNAME www to point to www.ithhero.com.herokudns.com

So far all tutorials/examples I've seen have had a different DNS target e.g. www.ithero.herokuapp.com . And even though I have followed the steps no results have been yielded. Godaddy and Heroku have been bouncing responsibility between them when raising an issue with either.

What am I doing wrong?

答:
You postet it a while ago so I assume you found a solution already, but you should only change your CNAME value from:

```<code>www.ithehero.com.herokudns.com
</code>```

to

```<code>ithehero.com.herokudns.com
</code>```

Title: Heroku and GoDaddy DNS configuration

Body:
You postet it a while ago so I assume you found a solution already, but you should only change your CNAME value from:

www.ithehero.com.herokudns.com

to

ithehero.com.herokudns.com


问:
Obtaining one column of a RDD[Array[String]] and converting it to dataset/dataframe
I have a .csv file that I read in to a RDD:

```<code>val dataH = sc.textFile(filepath).map(line => line.split(",").map(elem => elem.trim))
</code>```

I would like to iterate over this RDD in order and compare adjacent elements, this comparison is only dependent of one column of the datastructure. It is not possible to iterate over RDDs so instead, the idea is to first convert the column of RDD to either a Dataset or Dataframe.

You can convert a RDD to a dataset like this (which doesn't work if my structure is RDD[Array[String]]:

```<code>val sc = new SparkContext(conf)
val sqc = new SQLContext(sc)
import sqc.implicits._
val lines = sqc.createDataset(dataH)
</code>```

How do I obtain just the one column that I am interested in from dataH and thereafter create a dataset just from it?

I am using Spark 1.6.0.

答:
You can just map your Array to the desired index, e.g. :

```<code>dataH.map(arr => arr(0)).toDF("col1")
</code>```

Or safer (avoids Exception in case the index is out of bound):

```<code>dataH.map(arr => arr.lift(0).orElse(None)).toDF("col1")
</code>```

Body:
I have a .csv file that I read in to a RDD:

val dataH = sc.textFile(filepath).map(line => line.split(",").map(elem => elem.trim))

I would like to iterate over this RDD in order and compare adjacent elements, this comparison is only dependent of one column of the datastructure. It is not possible to iterate over RDDs so instead, the idea is to first convert the column of RDD to either a Dataset or Dataframe.

You can convert a RDD to a dataset like this (which doesn't work if my structure is RDD[Array[String]]:

val sc = new SparkContext(conf)
val sqc = new SQLContext(sc)
import sqc.implicits._
val lines = sqc.createDataset(dataH)

How do I obtain just the one column that I am interested in from dataH and thereafter create a dataset just from it?

I am using Spark 1.6.0.

Body:
You can just map your Array to the desired index, e.g. :

dataH.map(arr => arr(0)).toDF("col1")

Or safer (avoids Exception in case the index is out of bound):

dataH.map(arr => arr.lift(0).orElse(None)).toDF("col1")


问:
onCreate not called when switching to Huawei phone
I have a very simple app with an empty activity. I just tried it over another phone (the Huawei P8 Lite 2017 to be precise), and it seems that onCreate never appears in logcat. Here is the code for the activity ("Empty activity" app created through wizard, using android studio, which recently received a major update).

```<code>package com.test.test;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.v("foo","OnCreate");
    }
}
</code>```

On every other phone I tried, it displays fine in logcat. On this phone I get a bunch of info/error messages (as usual I would say, but the messages are somewhat different), and no "OnCreate".

It works fine, for example, for the Galaxy S7 (running "7.0", just like the P8 Lite 2017).

Are there any adb settings that may hide this log from me? What could be the problem?

答:
As per ישו אוהב אות 's comment, it seems it's a Huawei feature : some (most?) logs are disabled by default. The method described in Huawei, logcat not showing the log for my app? works for me (menus are slightly different from what is in the answer, see comments).

Now verbose logs are showing out of logcat.

EDIT: after further testing, it seems the behavior of log activation feature is quite erratic on this phone (maybe other Huawei phones). I haven't been able to clearly understand what makes it work and what does not. I'm currently using the Log.i workaround.

Body:
I have a very simple app with an empty activity. I just tried it over another phone (the Huawei P8 Lite 2017 to be precise), and it seems that onCreate never appears in logcat. Here is the code for the activity ("Empty activity" app created through wizard, using android studio, which recently received a major update).

package com.test.test;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.v("foo","OnCreate");
    }
}

On every other phone I tried, it displays fine in logcat. On this phone I get a bunch of info/error messages (as usual I would say, but the messages are somewhat different), and no "OnCreate".

It works fine, for example, for the Galaxy S7 (running "7.0", just like the P8 Lite 2017).

Are there any adb settings that may hide this log from me? What could be the problem?


问:
How important is it to follow web standards?
I recently found out that most of the major websites fail W3C's markup and CSS validation tests. Therefore, how important is it really to follow web standards?</p>

答:
Well, as you said, most large websites don't follow standard, so if you want a large website, you'd better not follow the standards. :)

But no, it's best to follow standards, because that will give you the biggest change that your site will function on most browsers, and will continue to function on most future browsers too for a very long time.

There are some exceptions, and they mainly occur because of some browsers (or some versions of browsers) not following standards. Therefor, you might sometimes need some tricks or hacks to get your site to function in all browsers you want to support. Most of these tricks can be applied while still following standards, but some others may lead to better performance or easier implementation or maintenance.

So while it's best to follow standards in general, there could always be one or two exceptions...

ContentLicense: CC BY-SA 2.5


问:
SQL Server Query for account statement
How can I generate last three transactions from the below table?

```<code>Date        Tran        dr  cr  total
-------------------------------------
2017-04-13
2017-07-15
2017-07-15
2017-10-17
2017-10-17 abc              10  10
2017-11-12 def              10  20
2017-11-12 ghi          5       15
</code>```

I'm using SQL Server 2012

答:
Like this you should your expected result:</p>

```<code>SELECT * FROM
(
   SELECT TOP 3 *
   FROM TransactionTable
   ORDER BY [Date] DESC
) AS t
ORDER by t.[Date]
</code>```

Title: SQL Server Query for account statement

Body:
How can I generate last three transactions from the below table?

Date        Tran        dr  cr  total
-------------------------------------
2017-04-13
2017-07-15
2017-07-15
2017-10-17
2017-10-17 abc              10  10
2017-11-12 def              10  20
2017-11-12 ghi          5       15

I'm using SQL Server 2012

Body:
Like this you should your expected result:

SELECT * FROM
(
   SELECT TOP 3 *
   FROM TransactionTable
   ORDER BY [Date] DESC
) AS t
ORDER by t.[Date]


问:
Label doesn't display "_" character
My Label.Content in WPF doesn't  display the first occurrence  of "_" character. Why?

```<code><Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="148" Width="211">
    <Grid>
        <Label Content="L_abel" Height="28" HorizontalAlignment="Left" Margin="37,31,0,0" Name="label1" VerticalAlignment="Top" />
    </Grid>
</Window>
</code>```

When set Label.Content ="L__abel" :

There is no additional code in project.

答:
The easiest method to fix it would be:

Change

```<code><Label Content="L_abel" Height="28" HorizontalAlignment="Left" Margin="37,31,0,0" Name="label1" VerticalAlignment="Top" />
</code>```

to

```<code><Label Height="28" HorizontalAlignment="Left" Margin="37,31,0,0" Name="label1" VerticalAlignment="Top">
<TextBlock Text="L_abel"/>
</Label>
</code>```

Title: Label doesn't display "_" character

Body:
My Label.Content in WPF doesn't  display the first occurrence  of "_" character. Why?

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="148" Width="211">
    <Grid>

    </Grid>
</Window>

When set Label.Content ="L__abel" :

There is no additional code in project.

Body:
The easiest method to fix it would be:

Change

<Label Content="L_abel" Height="28" HorizontalAlignment="Left" Margin="37,31,0,0" Name="label1" VerticalAlignment="Top" />

to

<Label Height="28" HorizontalAlignment="Left" Margin="37,31,0,0" Name="label1" VerticalAlignment="Top">
<TextBlock Text="L_abel"/>
</Label>


问:
Geolocation coords not passing from javascript to php
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.

Here the code.

1.code from template-maps.php:

```<code>var pos;
var posZae = function(pos){
                    return {
                            coords: {
                                latitude: pos.coords.latitude,
                                longitude: pos.coords.longitude,
                                accuracy: pos.coords.accuracy.toFixed()
                            },
                            timestamp: pos.timestamp
                    }
            };
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(posZae(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : pos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};
</code>```

it should send the data to template-userslocation.phpwhere I have this code:

```<code><?php
    /**
    * Template Name: template-userslocation
    */

    $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
    $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>
</code>```

I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.

Solved:

The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.

Here the info

答:
The ajax function is sending pos which is an object but you are using array notation within the php script to access the lat/lng.

Perhaps if you did

```<code>$.ajax({
    type: 'POST',
    data:  { lat:pos.lat, lng:pos.lng },
    url: '/wp-content/themes/atripby/template-userslocation.php'
});
</code>```

You could then, in the PHP, try

```<code>$lat=!empty( $_POST['lat'] ) ? $_POST['lat'] : null;
$lng=!empty( $_POST['lng'] ) ? $_POST['lng'] : null;
</code>```

Body:
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.

Here the code.

1.code from template-maps.php:

var pos;
var posZae = function(pos){
                    return {
                            coords: {
                                latitude: pos.coords.latitude,
                                longitude: pos.coords.longitude,
                                accuracy: pos.coords.accuracy.toFixed()
                            },
                            timestamp: pos.timestamp
                    }
            };
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(posZae(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : pos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};

it should send the data to template-userslocation.phpwhere I have this code:

<?php
    /**
    * Template Name: template-userslocation
    */

    $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
    $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>

I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.

Solved:

The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.

Here the info

Body:
The ajax function is sending pos which is an object but you are using array notation within the php script to access the lat/lng.

Perhaps if you did

$.ajax({
    type: 'POST',
    data:  { lat:pos.lat, lng:pos.lng },
    url: '/wp-content/themes/atripby/template-userslocation.php'
});

You could then, in the PHP, try

$lat=!empty( $_POST['lat'] ) ? $_POST['lat'] : null;
$lng=!empty( $_POST['lng'] ) ? $_POST['lng'] : null;


答: Try to set public static all of textviews and access it from this class directly using MainActivity.obj.setText("");

Title: How to set the output of the Asynchronous Task to the text view of the Main Activity

Body:
public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.


问:
Cancel queued builds and aborting executing builds using Groovy for Jenkins
For Jenkins using a Groovy System Script, is there a way to easily search the build queue and list of executing builds for some criteria (specifically a parameter that matches some condition) and then kill/cancel them?

I cannot seem to find any way to do this, but it seems like it should be possible.

答:
I know it's kind of an old question, but Google points me to this one. The scripts shown here only remove the jobs from the queue, and don't stop running builds. The following script, just removes everything from the queue and kills all running builds:</p>

```<code>  import java.util.ArrayList
  import hudson.model.*;
  import jenkins.model.Jenkins

  // Remove everything which is currently queued
  def q = Jenkins.instance.queue
  for (queued in Jenkins.instance.queue.items) {
    q.cancel(queued.task)
  }

  // stop all the currently running jobs
  for (job in Jenkins.instance.items) {
    stopJobs(job)
  }

  def stopJobs(job) {
    if (job in com.cloudbees.hudson.plugins.folder.Folder) {
      for (child in job.items) {
        stopJobs(child)
      }
    } else if (job in org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) {
      for (child in job.items) {
        stopJobs(child)
      }
    } else if (job in org.jenkinsci.plugins.workflow.job.WorkflowJob) {

      if (job.isBuilding()) {
        for (build in job.builds) {
        build.doKill()
        }
      }
    }
  }
</code>```

Body:
I know it's kind of an old question, but Google points me to this one. The scripts shown here only remove the jobs from the queue, and don't stop running builds. The following script, just removes everything from the queue and kills all running builds:

  import java.util.ArrayList
  import hudson.model.*;
  import jenkins.model.Jenkins

  // Remove everything which is currently queued
  def q = Jenkins.instance.queue
  for (queued in Jenkins.instance.queue.items) {
    q.cancel(queued.task)
  }

  // stop all the currently running jobs
  for (job in Jenkins.instance.items) {
    stopJobs(job)
  }

  def stopJobs(job) {
    if (job in com.cloudbees.hudson.plugins.folder.Folder) {
      for (child in job.items) {
        stopJobs(child)
      }
    } else if (job in org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) {
      for (child in job.items) {
        stopJobs(child)
      }
    } else if (job in org.jenkinsci.plugins.workflow.job.WorkflowJob) {

      if (job.isBuilding()) {
        for (build in job.builds) {
        build.doKill()
        }
      }
    }
  }

ContentLicense: CC BY-SA 4.0


问:
Node.js "cannot set property firstName of undefined"
I am following this tutorial,

https://www.youtube.com/watch?v=OnuC3VtEQks

to create a login system for my node app, only thing is since he is using mongoDb and I'm using mySql, I had to think of a way around him setting up his mongoose schema (right around 7:14 of the video), so I just exported a user module and assigned properties to it in my create a user logic.

Here's the user module

```<code>//user.js in models
var bcrypt = require('bcryptjs');

var User = {
    firstName: "firstName",
    lastName: "lastName",
    email: "email",
    username: "username",
    password: "password",
}

module.exports = User;

module.exports.createUser = function(newUser, callback){
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}
</code>```

Here is my route for the registration form

```<code>// main.js in router folder
var user = require('../models/user').User;

router.post('/register', function(req, res){
    var firstName = req.body.firstName;
    var lastName = req.body.lastName;
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var cpassword = req.body.cpassword;

    //Validation
    // req.checkBody('firstName', 'First name is required!').notEmpty();
    // req.checkBody('lastName', 'Last name is required!').notEmpty();
    // req.checkBody('email', 'E-mail is invalid!').isEmail();
    // req.checkBody('username', 'Username is required!').notEmpty();
    // req.checkBody('password', 'Password is required!').notEmpty();
    // req.checkBody('cpassword', 'Passwords do not match!').equals(password);

    var errors = req.validationErrors();
    if(errors){
        res.render('register', {
            errors: errors
        });
        console.log(errors);
    } else {
        var newUser = user;

        newUser.firstName = firstName;
        newUser.lastName = lastName;
        newUser.email = email;
        newUser.username = username;
        newUser.password = password;

        User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
        });

        req.flash('success_msg', 'You are now registered!');
        res.redirect('login');
    }
});
</code>```

Now I keep getting "cannot set property firstName of undefined error", but I thought I had access to my User object from the user.js module? From what I can tell it looks like he's just using the form input to instantiate the user object and create it with some password hashing.

If this is a bad approach, I am completely open to any ideas to make this simpler. I am completely new to node and my senior project is due in 2 weeks, so any help will be immensely appreciated and rewarded with upvotes and internet credits :)

答:
You should change your user.js as follows:

```<code>//user.js in models
var bcrypt = require('bcryptjs');

var User = {
    firstName: "firstName",
    lastName: "lastName",
    email: "email",
    username: "username",
    password: "password",
}

module.exports = {
    User: User,
    createUser: function (newUser, callback) {
        bcrypt.genSalt(10, function (err, salt) {
            bcrypt.hash(newUser.password, salt, function (err, hash) {
                newUser.password = hash;
                newUser.save(callback);
            });
        });
    }
}
</code>```

This would solve all of your problems.

Body:
I am following this tutorial,

https://www.youtube.com/watch?v=OnuC3VtEQks

to create a login system for my node app, only thing is since he is using mongoDb and I'm using mySql, I had to think of a way around him setting up his mongoose schema (right around 7:14 of the video), so I just exported a user module and assigned properties to it in my create a user logic.

Here's the user module

//user.js in models
var bcrypt = require('bcryptjs');

var User = {
    firstName: "firstName",
    lastName: "lastName",
    email: "email",
    username: "username",
    password: "password",
}

module.exports = User;

module.exports.createUser = function(newUser, callback){
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

Here is my route for the registration form

// main.js in router folder
var user = require('../models/user').User;

router.post('/register', function(req, res){
    var firstName = req.body.firstName;
    var lastName = req.body.lastName;
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var cpassword = req.body.cpassword;

    //Validation
    // req.checkBody('firstName', 'First name is required!').notEmpty();
    // req.checkBody('lastName', 'Last name is required!').notEmpty();
    // req.checkBody('email', 'E-mail is invalid!').isEmail();
    // req.checkBody('username', 'Username is required!').notEmpty();
    // req.checkBody('password', 'Password is required!').notEmpty();
    // req.checkBody('cpassword', 'Passwords do not match!').equals(password);

    var errors = req.validationErrors();
    if(errors){
        res.render('register', {
            errors: errors
        });
        console.log(errors);
    } else {
        var newUser = user;

        newUser.firstName = firstName;
        newUser.lastName = lastName;
        newUser.email = email;
        newUser.username = username;
        newUser.password = password;

        User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
        });

        req.flash('success_msg', 'You are now registered!');
        res.redirect('login');
    }
});

Now I keep getting "cannot set property firstName of undefined error", but I thought I had access to my User object from the user.js module? From what I can tell it looks like he's just using the form input to instantiate the user object and create it with some password hashing.

If this is a bad approach, I am completely open to any ideas to make this simpler. I am completely new to node and my senior project is due in 2 weeks, so any help will be immensely appreciated and rewarded with upvotes and internet credits :)

Body:
You should change your user.js as follows:

//user.js in models
var bcrypt = require('bcryptjs');

var User = {
    firstName: "firstName",
    lastName: "lastName",
    email: "email",
    username: "username",
    password: "password",
}

module.exports = {
    User: User,
    createUser: function (newUser, callback) {
        bcrypt.genSalt(10, function (err, salt) {
            bcrypt.hash(newUser.password, salt, function (err, hash) {
                newUser.password = hash;
                newUser.save(callback);
            });
        });
    }
}

This would solve all of your problems.


问:
SQL Server to mySQL converter
Hai Techies,

I have some stored procedure which was written in SQL server.Now i want to migrate this to mysql.Is there any freeware tools which can do this for me.

答:
I don't think so. You could just execute the query to create the procedure, ie:

```<code>CREATE PROCEDURE Blah(foo int, bar text)

END;
</code>```

(I think) and then ask questions or Google any problems that occur.

Title: SQL Server to mySQL converter

LastEditorDisplayName: Cade Roux

Body:
I don't think so. You could just execute the query to create the procedure, ie:

CREATE PROCEDURE Blah(foo int, bar text)

END;

(I think) and then ask questions or Google any problems that occur.

OwnerDisplayName: person-b


问:
TSQL Merge Performance
Scenario:

I have a table with roughly 24 million records.  The table has pricing history related to individual customers and is computed daily.  There are on average 6 million records for each day. Every morning a the price list is generated and a merge statement is ran to reflect the changes in their pricing.

The merge statement begins with the previous day's previous data being inserted into a variable table, that table is then merged into the actual table.  The main problem is that the merge statement takes pretty long.

My real question centers around the performance of using a variable table vs physical table vs temp table. What is the best practice for large merges like this?

答:
Check if you indexes on the tables.  Indexes would be updated every time you add/delete records on that table.

Try removing the indexes before merging the records and then re-create it again after the merge.

Title: TSQL Merge Performance


问:
Send Crashlytics reports from Android instrumented tests
I'm running my instrumented tests on Firebase Test Lab and want non-fatal exceptions to be reported to Crashlytics.

However, calling Crashlytics.logException() doesn't send the report immediately. After enabling core.debuggable(true) I see this when sending report:

```<code>D/CrashlyticsCore: Crashlytics is logging non-fatal exception "java.lang.Throwable: java.lang.Throwable" from thread main
</code>```

But the report is not visible on Crashlytics dashboard until I restart the app, and then I see:

```<code>D/CrashlyticsCore: Checking for crash reports...
D/CrashlyticsCore: Found crash report /data/user/0/.../files/.Fabric/com.crashlytics.sdk.android.crashlytics-core/nonfatal-sessions/....cls
D/CrashlyticsCore: Attempting to send 1 report(s)
D/CrashlyticsCore: Adding single file ....cls to report ...
D/CrashlyticsCore: Sending report to: https://reports.crashlytics.com/spi/v1/platforms/android/apps/org.dasfoo.delern.instrumented/reports
D/CrashlyticsCore: Create report request ID: null
D/CrashlyticsCore: Result was: 202
I/CrashlyticsCore: Crashlytics report upload complete: ...
D/CrashlyticsCore: Removing report at /data/user/0/.../files/.Fabric/com.crashlytics.sdk.android.crashlytics-core/nonfatal-sessions/....cls
D/CrashlyticsCore: Checking for crash reports...
D/CrashlyticsCore: No reports found.
</code>```

This is not ideal for production use cases, but it will at least work when user restarts the app. In tests, this never works because Firebase Test Lab does not restart the app (restarting the app means tests will fail).

Is there any workaround to allow Crashlytics to send non-fatal reports from the instrumented tests?

Used packages:

```<code>com.crashlytics.sdk.android:crashlytics:2.6.8@aar
io.fabric.tools:gradle:1.24.0
</code>```

UPD: rephrased the question and title. I am looking for an option to alter Crashlytics default behavior, since it seems like a reasonable feature to have.

答:
```<code>import com.google.firebase.crash.FirebaseCrash;

FirebaseCrash.report(new Exception("Error in CreateMobileAlertNative "+e.getStackTrace()));
</code>```

I used to get non-fatal exception on crashlytics by using this FirebaseCrash class, I put some codes on my catch,via which i used to get those reports, try this once.

Body:
I'm running my instrumented tests on Firebase Test Lab and want non-fatal exceptions to be reported to Crashlytics.

However, calling Crashlytics.logException() doesn't send the report immediately. After enabling core.debuggable(true) I see this when sending report:

D/CrashlyticsCore: Crashlytics is logging non-fatal exception "java.lang.Throwable: java.lang.Throwable" from thread main

But the report is not visible on Crashlytics dashboard until I restart the app, and then I see:

D/CrashlyticsCore: Checking for crash reports...
D/CrashlyticsCore: Found crash report /data/user/0/.../files/.Fabric/com.crashlytics.sdk.android.crashlytics-core/nonfatal-sessions/....cls
D/CrashlyticsCore: Attempting to send 1 report(s)
D/CrashlyticsCore: Adding single file ....cls to report ...
D/CrashlyticsCore: Sending report to: https://reports.crashlytics.com/spi/v1/platforms/android/apps/org.dasfoo.delern.instrumented/reports
D/CrashlyticsCore: Create report request ID: null
D/CrashlyticsCore: Result was: 202
I/CrashlyticsCore: Crashlytics report upload complete: ...
D/CrashlyticsCore: Removing report at /data/user/0/.../files/.Fabric/com.crashlytics.sdk.android.crashlytics-core/nonfatal-sessions/....cls
D/CrashlyticsCore: Checking for crash reports...
D/CrashlyticsCore: No reports found.

This is not ideal for production use cases, but it will at least work when user restarts the app. In tests, this never works because Firebase Test Lab does not restart the app (restarting the app means tests will fail).

Is there any workaround to allow Crashlytics to send non-fatal reports from the instrumented tests?

Used packages:

com.crashlytics.sdk.android:crashlytics:2.6.8@aar
io.fabric.tools:gradle:1.24.0

UPD: rephrased the question and title. I am looking for an option to alter Crashlytics default behavior, since it seems like a reasonable feature to have.

Body:
import com.google.firebase.crash.FirebaseCrash;

FirebaseCrash.report(new Exception("Error in CreateMobileAlertNative "+e.getStackTrace()));

I used to get non-fatal exception on crashlytics by using this FirebaseCrash class, I put some codes on my catch,via which i used to get those reports, try this once.


问:
PHP/Laravel Time Feld Required

I have a Laravel project that manages users and stuff like that. I'm storing data entered in a time form (time format), however, it keeps telling me that the time field is required even if I filled it.

Model part of the object

<?php

protected $fillable = ['name', 'timee'];

public $validationMessages;

public function validationRules()
{
    return [
        'name' => 'required|string',
        'timee' => 'required|time',
    ];
}
```

<p><strong>Time form in edit and create.blade.php</strong></p>

<pre class="lang-php prettyprint-override"><code><div class="form-group">
    {!! Form::label('timee', '* enter time :') !!}
    {!! Form::time('timee',null, ['class' => 'form-control']) !!}
    {{ $errors->first('timee') }}
</div>
</code>```

Migration

public function up()
{
    Schema::create('reminds', function(Blueprint $table){
        $table->increments('id');
        $table->string('name');
        $table->time('timee');
    });
}
```

Each time I try to save it, it keeps telling me that the timee field is required even if I fill it. I don't get it, everything seems correct to me, thank you.

答:
Everything looks okay to me. I think error comes because of database column type might miss match. You should either use varchar or datetime type.
If you have a column type in datetime then please check your format. You can use Carbon to change date format.

Title: PHP/Laravel Time Feld Required

Body:
I have a Laravel project that manages users and stuff like that. I'm storing data entered in a time form (time format), however, it keeps telling me that the time field is required even if I filled it.

Model part of the object

<?php

protected $fillable = ['name', 'timee'];

public $validationMessages;

public function validationRules()
{
    return [
        'name' => 'required|string',
        'timee' => 'required|time',
    ];
}

Time form in edit and create.blade.php

    {!! Form::label('timee', '* enter time :') !!}
    {!! Form::time('timee',null, ['class' => 'form-control']) !!}
    {{ $errors->first('timee') }}

Migration

public function up()
{
    Schema::create('reminds', function(Blueprint $table){
        $table->increments('id');
        $table->string('name');
        $table->time('timee');
    });
}

Each time I try to save it, it keeps telling me that the timee field is required even if I fill it. I don't get it, everything seems correct to me, thank you.


问:
Can Django's ORM output the SQL query it is using?
I know that you can output the SQL to see tables that are created. Is it possible for Django to output the sql used for any query like:

```<code>Protocols.objects.filter(active=False)
</code>```

?  I couldn't find this in the docs, so hopefully someone can point them to me, if in fact Django can do this.

答:
Yes it can. You need to make sure that you have DEBUG=True in your settings file

you can see what sql queries have been executed by...

```<code>>>> from django.db import connection
>>> connection.queries
</code>```

You obviously need to have executed some queries to see them here.

To see what is executed to deliver a particular QuerySet you can do the following

```<code>str(MyModel.objects.filter(myvar__gte=15).query)
</code>```

It's documented here
http://docs.djangoproject.com/en/dev/faq/models/

Body:
I know that you can output the SQL to see tables that are created. Is it possible for Django to output the sql used for any query like:

Protocols.objects.filter(active=False)

?  I couldn't find this in the docs, so hopefully someone can point them to me, if in fact Django can do this.

Body:
Yes it can. You need to make sure that you have DEBUG=True in your settings file

you can see what sql queries have been executed by...

>>> from django.db import connection
>>> connection.queries

You obviously need to have executed some queries to see them here.

To see what is executed to deliver a particular QuerySet you can do the following

str(MyModel.objects.filter(myvar__gte=15).query)

It's documented here
http://docs.djangoproject.com/en/dev/faq/models/


问:
C# - Put newline "\n" into a string before I reach the stringnumber n
at the moment I need a simple idea of my problem, because my last idea was bullsh*t.
I have a string from a List which contains an amount of stringnumbers.

```<code>1.0, 1.1, 2.0, ..., 10.1, 10.2, 10.2.1, ...
</code>```

Now I want to put an /n into the string for a new line before the first digit will be changed. And the new line should be set before the commata.

For example:

```<code>1.0, 1.1\n, 2.0\n, 3.0, ..., 5.0, 5.1\n, 6.0, ..., 10.1, 10.2, 10.2.1, ...
</code>```

Do you know a better and efficient way?

Regards, C

答:
You can check for integer with (n % 1 == 0) to see if your first digit is going to change or not.

```<code>var input = "1.0, 1.1, 2.0, 10.1, 10.2, 10.2.1";
string result = string.Empty;
var temp = input.Split(','); //You can also trim here as @Steve did
foreach (var item in temp)
{
   //cast it to double, then check if it's an integer
   if ((double.Parse(item.Trim())) % 1 == 0)
   {
       //this is an integer, the first digit will be changed, put "\n"
       result += "\n" + item;
   }
   else
   {
       //this is not an integer, continue as usual.
       result += item;
   }
}

//on this line the variable result is formatted the way you want.
Console.WriteLine(result);
</code>```

Body:
at the moment I need a simple idea of my problem, because my last idea was bullsh*t.
I have a string from a List which contains an amount of stringnumbers.

1.0, 1.1, 2.0, ..., 10.1, 10.2, 10.2.1, ...

Now I want to put an /n into the string for a new line before the first digit will be changed. And the new line should be set before the commata.

For example:

1.0, 1.1\n, 2.0\n, 3.0, ..., 5.0, 5.1\n, 6.0, ..., 10.1, 10.2, 10.2.1, ...

Do you know a better and efficient way?

Regards, C

Body:
You can check for integer with (n % 1 == 0) to see if your first digit is going to change or not.

var input = "1.0, 1.1, 2.0, 10.1, 10.2, 10.2.1";
string result = string.Empty;
var temp = input.Split(','); //You can also trim here as @Steve did
foreach (var item in temp)
{
   //cast it to double, then check if it's an integer
   if ((double.Parse(item.Trim())) % 1 == 0)
   {
       //this is an integer, the first digit will be changed, put "\n"
       result += "\n" + item;
   }
   else
   {
       //this is not an integer, continue as usual.
       result += item;
   }
}

//on this line the variable result is formatted the way you want.
Console.WriteLine(result);


问:
What is the best way to achieve following design (attached image)?
All,

I know this is not difficult one, But I just want to know that which is the best way to achieve . You can see two icons exactly between two layouts (blackish and white). I know we can achieve this using margin but is there any other better way ?

P.S To clarify the confusion this is what my entire screen should look like

Thanks in advance.
Answer will be appreciated.

答:
Try This

Output:

```<code>   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="com.nct.dhruv.demotest.LogCatActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/colorPrimary" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/colorAccent" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_centerVertical="true"
        android:layout_alignParentStart="true">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_marginRight="10dp"
            android:orientation="vertical"
            android:layout_height="wrap_content">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/floatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_launcher"
                app:backgroundTint="#fff" />

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_height="wrap_content">

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                app:backgroundTint="#fff"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_launcher" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

Body:
Try This

Output:

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="com.nct.dhruv.demotest.LogCatActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/colorPrimary" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/colorAccent" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_centerVertical="true"
        android:layout_alignParentStart="true">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_marginRight="10dp"
            android:orientation="vertical"
            android:layout_height="wrap_content">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/floatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_launcher"
                app:backgroundTint="#fff" />

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_height="wrap_content">

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                app:backgroundTint="#fff"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_launcher" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


问:
Invoking a Lambda function every 5 seconds

My problem

I'd like to invoke an AWS Lambda function every 5 seconds, for some monitoring purposes.

According to the docs,

Rate frequencies of less than one minute are not supported.

What have I tried

STFW.

My Question

Can I autonomously invoke an AWS Lambda function every 5 seconds?

答:
Cron only allows for a minimum of one minute. What you could do is write a shell script with an infinite loop that runs your task, and then sleeps for 5 seconds. That way your task would be run more or less every 5 seconds, depending on how long the task itself takes.

But it really does sound like you're doing something that you probably shouldn't be doing though. This feels wrong.


问:
Strip leading dot from filenames bash script
I have some files in a bunch of directories that have a leading dot and thus are hidden. I would like to revert that and strip the leading dot.

I was unsuccessful with the following:

```<code>for file in `find files/ -type f`;
do
base=`basename $file`
if [ `$base | cut -c1-2` = "." ];
then newname=`$base | cut -c2-`;
dirs=`dirname $file`;
echo $dirs/$newname;
fi
done
</code>```

Which fails on the condition statement:

```<code>[: =: unary operator expected
</code>```

Furthermore, some files have a space in them and file returns them split.

Any help would be appreciated.

答:
```<code>find files/ -name '.*' -printf '%f\n'|while read f; do
        mv "files/$f" "files/${f#.}"
done
</code>```

Body:
I have some files in a bunch of directories that have a leading dot and thus are hidden. I would like to revert that and strip the leading dot.

I was unsuccessful with the following:

for file in `find files/ -type f`;
do
base=`basename $file`
if [ `$base | cut -c1-2` = "." ];
then newname=`$base | cut -c2-`;
dirs=`dirname $file`;
echo $dirs/$newname;
fi
done

Which fails on the condition statement:

[: =: unary operator expected

Furthermore, some files have a space in them and file returns them split.

Any help would be appreciated.


问:
Surface between contour lines in 3D
I have code like this:

```<code>load('something.mat');
[X,Y] = meshgrid(tx,ty);

tt1 = U_TV1(:,:,1);
tt2=U_TV1( :,:,2);
tt3=U_TV1( :,:,3);

figure(2);
% surf(X, Y, tt1, 'FaceAlpha', 0.3);
shading interp;
hold on;
e = [1 3]; % [ .001  .1 .3  1  3 10 ]; % epsilon
[c1, h1] = contour3(X, Y, tt1, e, 'r');
[c2, h2] = contour3(X, Y, tt2, e, 'b');
[c3, h3] = contour3(X, Y, tt3, e, 'g');
% legend('k=1', 'k=2', 'k=3');
clabel(c1, h1, e, 'fontsize', 10, 'fontweight', 'bold');
clabel(c2, h2, e, 'fontsize', 10, 'fontweight', 'bold');
clabel(c3, h3, e, 'fontsize', 10, 'fontweight', 'bold');
zlim([0 15]);
</code>```

And the result is following 3D plot:

How I can fill space (draw surface) between contours with the same number ?

I would like to have something like this (made with Paint):

Thanks for any help.

答:
The solution consists out of two steps:

Extract the points/lines through which you want to fit a plot

Fit a surface through that points using fit

Title: Surface between contour lines in 3D

Body:
I have code like this:

load('something.mat');
[X,Y] = meshgrid(tx,ty);

tt1 = U_TV1(:,:,1);
tt2=U_TV1( :,:,2);
tt3=U_TV1( :,:,3);

figure(2);
% surf(X, Y, tt1, 'FaceAlpha', 0.3);
shading interp;
hold on;
e = [1 3]; % [ .001  .1 .3  1  3 10 ]; % epsilon
[c1, h1] = contour3(X, Y, tt1, e, 'r');
[c2, h2] = contour3(X, Y, tt2, e, 'b');
[c3, h3] = contour3(X, Y, tt3, e, 'g');
% legend('k=1', 'k=2', 'k=3');
clabel(c1, h1, e, 'fontsize', 10, 'fontweight', 'bold');
clabel(c2, h2, e, 'fontsize', 10, 'fontweight', 'bold');
clabel(c3, h3, e, 'fontsize', 10, 'fontweight', 'bold');
zlim([0 15]);

And the result is following 3D plot:

How I can fill space (draw surface) between contours with the same number ?

I would like to have something like this (made with Paint):

Thanks for any help.


问:
Create button OnClientClick asp net
I'm creating button from code c#:

```<code>        Button btnAddCalculation = new Button();
        btnAddCalculation.ID = "btnAddCalculation";
        btnAddCalculation.Text = "Add count";
        btnAddCalculation.SkinID = "middleButton";
        btnAddCalculation.Visible = true;

        string sPath = String.Format(
            "WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
            SessionViewstateConstants.CalculationType,
            CalcType.New,
            Guid.NewGuid(),
            oEditedDocument.Id.ToString()
        );
        //          btnAddCalculation.Attributes.Add("onclick", @"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
        btnAddCalculation.Click += new EventHandler(btnClick_cl);
        btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";

    public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
    {
        return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
    }
</code>```

but in the client side the function OnClientClick does not work, when I click
nothing happens. What Did I do wrong???

Generated HTML:

```<code><input type="submit" name="ctl00$ctl00$Main$EditorMain$tabTabContainer$ctl00$Attr433$btnAddCalculation"
value="Add count"
id="ctl00_ctl00_Main_EditorMain_tabTabContainer_ctl00_Attr433_btnAddCalculation"
disabled="disabled" class="blue_button" />
</code>```

答:
Fix this:

```<code>    Button btnAddCalculation = new Button();
    btnAddCalculation.ID = "btnAddCalculation";
    btnAddCalculation.Text = "Add count";
    btnAddCalculation.SkinID = "middleButton";
    btnAddCalculation.Visible = true;
    btnAddCalculation.Enabled = true;

    string sPath = String.Format(
        "WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
        SessionViewstateConstants.CalculationType,
        CalcType.New,
        Guid.NewGuid(),
        oEditedDocument.Id.ToString()
    );
    //          btnAddCalculation.Attributes.Add("onclick", @"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
    btnAddCalculation.Click += new EventHandler(btnClick_cl);
    btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";

public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
{
    return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
}
</code>```

By default the asp.net server will create the button as disabled unless you specify explicitly otherwise.

Title: Create button OnClientClick asp net

Body:
I'm creating button from code c#:

        Button btnAddCalculation = new Button();
        btnAddCalculation.ID = "btnAddCalculation";
        btnAddCalculation.Text = "Add count";
        btnAddCalculation.SkinID = "middleButton";
        btnAddCalculation.Visible = true;

        string sPath = String.Format(
            "WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
            SessionViewstateConstants.CalculationType,
            CalcType.New,
            Guid.NewGuid(),
            oEditedDocument.Id.ToString()
        );
        //          btnAddCalculation.Attributes.Add("onclick", @"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
        btnAddCalculation.Click += new EventHandler(btnClick_cl);
        btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";

    public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
    {
        return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
    }

but in the client side the function OnClientClick does not work, when I click
nothing happens. What Did I do wrong???

Generated HTML:

<input type="submit" name="ctl00$ctl00$Main$EditorMain$tabTabContainer$ctl00$Attr433$btnAddCalculation"
value="Add count"
id="ctl00_ctl00_Main_EditorMain_tabTabContainer_ctl00_Attr433_btnAddCalculation"
disabled="disabled" class="blue_button" />

Body:
Fix this:

    Button btnAddCalculation = new Button();
    btnAddCalculation.ID = "btnAddCalculation";
    btnAddCalculation.Text = "Add count";
    btnAddCalculation.SkinID = "middleButton";
    btnAddCalculation.Visible = true;
    btnAddCalculation.Enabled = true;

    string sPath = String.Format(
        "WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
        SessionViewstateConstants.CalculationType,
        CalcType.New,
        Guid.NewGuid(),
        oEditedDocument.Id.ToString()
    );
    //          btnAddCalculation.Attributes.Add("onclick", @"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
    btnAddCalculation.Click += new EventHandler(btnClick_cl);
    btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";

public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
{
    return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
}

By default the asp.net server will create the button as disabled unless you specify explicitly otherwise.


问:
Passing arguments from a file to shell in Pipeline
Basically I'm trying to pass properties to shell from a file.

I have a file "docker_info" with following content in workspace

```<code>IMAGE_NAME='Docker-image'

IMAGE_VERIONS='Docker-1.3.5'
</code>```

Here is my pipeline script:

```<code>node
{

load "${WORKSPACE}/docker_info"

sh " echo ${IMAGE_NAME}" // here getting expected output: Docker-image

stage('Executing SHELL SCRIPING TO CHECK DOCKER IMAGE')

        sh '''

         echo "$DOCKER_IMAGE"

            if [ -z "${IMAGE_NAME}" ]     //(also tried "$IMAGE_NAME")
            then
            echo "Docker image not found."
            exit 0
            fi

             echo "${IMAGE_NAME}:started pushing image"

         '''
}
</code>```

OUTPUT:

```<code>[Test_BUILD_PIPELINE] Running shell script

+ echo Docker-image

Docker-image

**Entering stage Executing SHELL SCRIPTING TO CHECK DOCKER IMAGE**

Proceeding

[Pipeline] sh

[Test_BUILD_PIPELINE] Running shell script

+  echo ''
+ '[' -z '' ']'

+ echo 'Docker image not found. Skip pushing Docker image'

Docker image not found. Skip pushing Docker image

+ exit 0
</code>```

Kindly note after entering into the stage I Won't see the expected value(Docker-image)instead displaying:   echo ' '

I tried with several ways but that haven't worked.

答:
Try</p>

```<code>    sh """

     echo '$DOCKER_IMAGE'

        if [ -z '$IMAGE_NAME' ]
        then
        echo 'Docker image not found.'
        exit 0
        fi

         echo '$IMAGE_NAME:started pushing image'

     """
</code>```

Body:
Basically I'm trying to pass properties to shell from a file.

I have a file "docker_info" with following content in workspace

IMAGE_NAME='Docker-image'

IMAGE_VERIONS='Docker-1.3.5'

Here is my pipeline script:

node
{

load "${WORKSPACE}/docker_info"

sh " echo ${IMAGE_NAME}" // here getting expected output: Docker-image

stage('Executing SHELL SCRIPING TO CHECK DOCKER IMAGE')

        sh '''

         echo "$DOCKER_IMAGE"

            if [ -z "${IMAGE_NAME}" ]     //(also tried "$IMAGE_NAME")
            then
            echo "Docker image not found."
            exit 0
            fi

             echo "${IMAGE_NAME}:started pushing image"

         '''
}

OUTPUT:

[Test_BUILD_PIPELINE] Running shell script

+ echo Docker-image

Docker-image

**Entering stage Executing SHELL SCRIPTING TO CHECK DOCKER IMAGE**

Proceeding

[Pipeline] sh

[Test_BUILD_PIPELINE] Running shell script

+  echo ''
+ '[' -z '' ']'

+ echo 'Docker image not found. Skip pushing Docker image'

Docker image not found. Skip pushing Docker image

+ exit 0

Kindly note after entering into the stage I Won't see the expected value(Docker-image)instead displaying:   echo ' '

I tried with several ways but that haven't worked.

Body:
Try

    sh """

     echo '$DOCKER_IMAGE'

        if [ -z '$IMAGE_NAME' ]
        then
        echo 'Docker image not found.'
        exit 0
        fi

         echo '$IMAGE_NAME:started pushing image'

     """


问:
Linked List in a Array

I am currently doing a online Java course and am having a bit of trouble with a assignment. The assignment is to essentially create a Hashmap using just Arrays but no other Java Data Structures or methods. This is my code:

public class test {

    static String[] array = new String[10];

    class Cell<T> {
        T first;
        Cell<T> next;

        Cell(T h, Cell<T> t) {
            first = h;
            next = t;
        }
    }

    public static int hashFunction(String a) {
        int sum = 1;
        for (int i = 0; i < a.length(); i++) {
            char b = a.charAt(i);
            int value = (int) b;
            sum *= value;
        }
        return sum % array.length;
    }

    public static void arraySetter(String a) {
        int position = hashFunction(a);
        if (array[position] == null) {
            array[position] = a;

        } else {
            //Need a Linked List here for when there is already a item in the array at the same index.
        }
    }

    public static void printArray() {
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

    public static void main(String[] args) {
        arraySetter("abc");
        printArray();
    }
}
```

My code essentially creates a list of lists. At each position in the Array I now need to create a list which is only initialised when there are two items with the same value for the hashFunction. I haven't written that function yet but my problem now is I don't know how to create a linkedList at each position in the array. Can someone help me out here?

答:
If you want a linked list to avoid collision then you have to declare array which will contain head of the linked list.

```<code>Node<K,V>[] table;
</code>```

Sample code not fully implemented.

```<code>class Node<K,V>  {
        K key;
        V value;
        Node<K,V> next;
        }
</code>```

Node will contain current key and value .if key is same then you have to override and also next value if you want to use linked list.If you want to use array to avoid collision that time also use node which will contain key and value key is required to check equality and no next variable.

Title: Linked List in a Array

Body:
I am currently doing a online Java course and am having a bit of trouble with a assignment. The assignment is to essentially create a Hashmap using just Arrays but no other Java Data Structures or methods. This is my code:

public class test {

    static String[] array = new String[10];

    class Cell<T> {
        T first;
        Cell<T> next;

        Cell(T h, Cell<T> t) {
            first = h;
            next = t;
        }
    }

    public static int hashFunction(String a) {
        int sum = 1;
        for (int i = 0; i < a.length(); i++) {
            char b = a.charAt(i);
            int value = (int) b;
            sum *= value;
        }
        return sum % array.length;
    }

    public static void arraySetter(String a) {
        int position = hashFunction(a);
        if (array[position] == null) {
            array[position] = a;

        } else {
            //Need a Linked List here for when there is already a item in the array at the same index.
        }
    }

    public static void printArray() {
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

    public static void main(String[] args) {
        arraySetter("abc");
        printArray();
    }
}

My code essentially creates a list of lists. At each position in the Array I now need to create a list which is only initialised when there are two items with the same value for the hashFunction. I haven't written that function yet but my problem now is I don't know how to create a linkedList at each position in the array. Can someone help me out here?

Body:
If you want a linked list to avoid collision then you have to declare array which will contain head of the linked list.

Node<K,V>[] table;

Sample code not fully implemented.

class Node<K,V>  {
        K key;
        V value;
        Node<K,V> next;
        }

Node will contain current key and value .if key is same then you have to override and also next value if you want to use linked list.If you want to use array to avoid collision that time also use node which will contain key and value key is required to check equality and no next variable.