问:
How to remove Empty Rows from a list in Python 3.5
```<code>apple
mango
banana

tea

coffee
</code>```

Can someone please suggest a python code to remove the empty rows in this case after banana/tea/coffee so the actual result should be as below without any empty rows in between and after the end of lists

```<code>apple
mango
banana
tea
coffee
</code>```

答:
Given that your list is actually a python list like your title suggests, you can just use filter.

i.e.

```<code>>>> test_list = ['apple','mango','banana','','tea','','coffee']
>>> test_list = list(filter(None,test_list))
>>> test_list
['apple', 'mango', 'banana', 'tea', 'coffee']
</code>```

Body:
apple
mango
banana

tea

coffee

Can someone please suggest a python code to remove the empty rows in this case after banana/tea/coffee so the actual result should be as below without any empty rows in between and after the end of lists

apple
mango
banana
tea
coffee

Body:
Given that your list is actually a python list like your title suggests, you can just use filter.

i.e.

>>> test_list = ['apple','mango','banana','','tea','','coffee']
>>> test_list = list(filter(None,test_list))
>>> test_list
['apple', 'mango', 'banana', 'tea', 'coffee']


来源: stackexchange

问:
login returns error invalid credentials even the given credentials is correct
I'm trying to modify the default authentication to tailor my needs. I have this requirements like a user should be able to login using either user name or email but it always returns invalid credentials error even if the given credentials are correct, please refer to the code below:

```<code><?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        // return $request->only($this->username(), 'password');
        if(filter_var($request->username_email, FILTER_VALIDATE_EMAIL) ){
            return $request->only('email', 'password');
        }else{
            return $request->only('username', 'password');
        }
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        //
        return response()->json([ 'message' => 'authenticated']);
    }

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $errors = [$this->username() => trans('auth.failed')];

        if ($request->expectsJson()) {
            return response()->json($errors);
        }

        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors($errors);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'username_email';
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect('/');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }
}
</code>```

Inside credentials(), I check if its an username or email first and then return the corresponding database column, but it looks like it doesn't work at all. Any ideas, help please?

答:
Your method:

```<code>protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|string',
        'password' => 'required|string',
    ]);
}
</code>```

With username() returning username_email seems incoherent. I think what you looking for is required_without_all:

```<code>protected function validateLogin(Request $request)
{
    $this->validate($request, [
        'username' => 'required_without_all:email|string',
        'email' => 'required_without_all:username|string',
        'password' => 'required|string',
    ]);
}
</code>```

So username will be required when email is not present and vice versa.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to modify the default authentication to tailor my needs. I have this requirements like a user should be able to login using either user name or email but it always returns invalid credentials error even if the given credentials are correct, please refer to the code below:

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        // return $request->only($this->username(), 'password');
        if(filter_var($request->username_email, FILTER_VALIDATE_EMAIL) ){
            return $request->only('email', 'password');
        }else{
            return $request->only('username', 'password');
        }
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        //
        return response()->json([ 'message' => 'authenticated']);
    }

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $errors = [$this->username() => trans('auth.failed')];

        if ($request->expectsJson()) {
            return response()->json($errors);
        }

        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors($errors);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'username_email';
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect('/');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }
}

Inside credentials(), I check if its an username or email first and then return the corresponding database column, but it looks like it doesn't work at all. Any ideas, help please?

Body:
Your method:

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|string',
        'password' => 'required|string',
    ]);
}

With username() returning username_email seems incoherent. I think what you looking for is required_without_all:

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        'username' => 'required_without_all:email|string',
        'email' => 'required_without_all:username|string',
        'password' => 'required|string',
    ]);
}

So username will be required when email is not present and vice versa.


问:
Change tmp for ImageMagick
My tmp folder is getting spammed by imagemagick files. I want to change the path where the temporary files are saved so i can delete them with a script. For that I have tried changing the path in the policy.xml but it is still using the /tmp/ folder. The method setRegistry(), suggested in this post, does not seem to exist in the class Imagick and I don't know where find the enviornment variables like MAGICK_TEMPORARY_PATH. Can someone help me with that?

答:
In unix, you can edit your .profile or .bash_profile file located in our home directory to include:
export MAGICK_TEMPORARY_PATH="yourdesiredlocation"</p>

Title: Change tmp for ImageMagick


问:
How to find menu height
i want to create fixed navigation layout, but there is a problem when i rotate device, margin-top of this layout is more than it has to be, so the question - how can i find height of this dark-blue header ( to use it as margin ), or maybe there is another way

```<code>    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_marginTop="55dp"
    android:layout_height="80dp"
    android:background="@drawable/panel_border"
    android:layout_alignParentTop="true">
</code>```

答:
If I were you, I would go with this:

```<code>android:layout_marginTop="?attr/actionBarSize"
</code>```

This attribute indicates correct height of the ActionBar / Toolbar.

 The Toolbars height may be different for different APIs and that's the reason you should use ?android:attr or ?attr (when using support library).

 ? means that it comes from internal Android resources.

Title: How to find menu height

Body:
i want to create fixed navigation layout, but there is a problem when i rotate device, margin-top of this layout is more than it has to be, so the question - how can i find height of this dark-blue header ( to use it as margin ), or maybe there is another way

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_marginTop="55dp"
    android:layout_height="80dp"
    android:background="@drawable/panel_border"
    android:layout_alignParentTop="true">

Body:
If I were you, I would go with this:

android:layout_marginTop="?attr/actionBarSize"

This attribute indicates correct height of the ActionBar / Toolbar.

 The Toolbars height may be different for different APIs and that's the reason you should use ?android:attr or ?attr (when using support library).

 ? means that it comes from internal Android resources.


问:
How to check more gently that some part of the code running 4 times a day
I have the script running by crontab and I want some part of the code being executed 4 times a day.

I have the snippet of code which

```<code>from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time == time(10,00) or now_time == time(16,00) or now_time == time(22,00) or now_time == time (4,00):
    func()
</code>```

The minus of this solution is that this part of the code may be executed on 10.01, 10.02 and will be skipped this way.

Is there more gentle and shorter way to write down this part of code?

Thanks!

答:
If you have the flexibility to move to APScheduler (http://apscheduler.readthedocs.io/en/latest/userguide.html) your job becomes easier and the code is more reliable. </p>

```<code>from apscheduler.schedulers.background import BackgroundScheduler

# assuming tick is your function
scheduler = BackgroundScheduler()
#cron which runs once in 6 hours
scheduler.add_job(tick, 'cron', hour='*/6')
scheduler.start()
</code>```

Body:
I have the script running by crontab and I want some part of the code being executed 4 times a day.

I have the snippet of code which

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time == time(10,00) or now_time == time(16,00) or now_time == time(22,00) or now_time == time (4,00):
    func()

The minus of this solution is that this part of the code may be executed on 10.01, 10.02 and will be skipped this way.

Is there more gentle and shorter way to write down this part of code?

Thanks!

Body:
If you have the flexibility to move to APScheduler (http://apscheduler.readthedocs.io/en/latest/userguide.html) your job becomes easier and the code is more reliable.

from apscheduler.schedulers.background import BackgroundScheduler

# assuming tick is your function
scheduler = BackgroundScheduler()
#cron which runs once in 6 hours
scheduler.add_job(tick, 'cron', hour='*/6')
scheduler.start()


答:
There is a very handy jQuery function .uniqueSort() that you can call on an array to sort it and remove duplicate elements.

Try setting source: $.uniqueSort(postal_codes)

Title: jQuery autocomplete shows the same results

Body:
I'm using jQuery for autocomplete over a big array of data. My code is in this snippet:

$( function() {
  $( ".postal-code-autocomplete" ).autocomplete({
      source: postal_codes,
      minLength: 3,
  });
});

However when the autocomplete is done and I have my result back, it still shows a number of records with the same value, the one  I was looking for, as shown in the picture:

I would like this drop down list with the same results not to be appearing when my result is found.

Thank you very much!

EDIT: If I console.log(postal_codes)  I get the following results

(54767) ["15354", "13341", "13675", "13451", "17455", "15127", "15562", "14561", "13671", "12241", "13451", "15341", "13561", "17341", "17343", "12244", "15349", "13343", "16452", "16672", "16673", "15235", "16233", "15354", "16777", "14122", "13122", "13231", "13121", "13123", "17778", "17676", "13451", "14562", "14123", "15124", "15127", "14671", "15236", "17121", "14342", "15451", "12134", "12132", "15121", "15237", "12462", "15232", "15561", "15562", "15452", "12351", "15341", "13561", "12244", "13341", "16452", "13671", "15235", "16233", "16777", "15772", "14122", "13122", "13451", "14562", "14123", "15124", "15127", "14231", "15236", "14342", "15451", "17563", "15236", "12136", "12461", "13231", "15121", "15237", "15452", "13451", "16777", "13342", "16122", "17121", "16342", "16777", "16777", "15773", "16777", "15773", "15772", "13122", "10431", "10432", "10433", "10434", "11251", "16452"…]


问:
Loading Lots Of Images From Server In Android
Edit 2: Even after the bounty, no one could give a full solution. So I solved it myself. I have posted my solution below.

I searched about it on Google and also found various good results. But since I'm not expert in server and backend kind of terms, I would like to ask it in a separate question. I have a website hosting which helps me run an institution's website.

In my android app, there should be an option such as "Photo Gallery" which shows images from my website (where I upload images in a folder). I think it can be done by managing some JSON files.

Let there be a folder \public_html\MyApp\Images which consists of folders like "Event1", "Event2", and so on. I upload images to these different folders and my Android app should load them (maybe separately giving users a choice to pick a folder).

Is it possible? If any advanced database system is required, please give me some intro links for that. Is there any way a JSON is automatically generated containing the links to images?

Edit: I had recently bought website hosting for backend kind of things and I haven't done any server-side scripting or anything. That's why a detailed answer is required. I don't know how to manage those images, simply upload images and put links in JSON or use some MySQL, SQL or whatever terms which I've never used.

答:
I found the solution myself. It's pretty easy to understand and implement and requires the knowledge of JSON only. Firstly, see this image from a directory of my website:

"event1", "event2" folders are the album names. We can create as many needed.

"getfolders file is very important. Content:

```<code>{
   "test":[
      {
         "sub":"event1",
         "content":"https://i1.wp.com/www.downloadinformer.com/wp-content/uploads/2017/03/AMPFB.jpg?w=1366",
         "param":"1.php"
      },
      {
         "sub":"event2",
         "content":"myimageurl",
         "param":"myphpfilenamewithextension"
      }
   ]
}
</code>```

We store album names here as you can see in "sub" field. "content" field contains the link to the thumbnail of the album and "param" contains the name of the corresponding PHP file. Don't worry, you don't need to learn PHP. It's a readymade script.

1.php

```<code><?php

$indir = array_filter(scandir('event1'), function($item) {
        return $item[0] !== '.';
});

echo json_encode($indir);
?>
</code>```

What this PHP file does? It lists all the names of files present in a specified folder. As you can see, we've specified "event1" as the folder name in this PHP file. So it will return all the images' names in a JSON format. Don't forget to specify this PHP file in "getfolders" file's "param" field.

Ok fine. So this was a sort of algorithm. If you have some confusion, please re-read it again. Now I will show some code.

I made two activities (Didn't prefer Fragments). One to show albums and second to show the images present in it.

Activity 1-> Parses getfolders file and retrieves albums we specified earlier.

Album Title: sub field of the above JSON
, Album Thumbnail: content field of the above JSON
, (Hidden From User) Images Names List: param field

Thus we can show it in a Recyclerview with this information. Now we specify OnClickListener for its items.

On Click Of An Item-> Start second activity using Intent and pass on the album name which is essentially the Folder name on our server. Thus we get access to the folder which contains images. Also pass the "param" field value. This gives us a url "www.mywebsite.com/..../alreadyspecifieddirectory/1.php"

Activity->2 Implement a GridLayoutManager to show pictures to the user. Retrieve the earlier passed values using getIntent(). First we need to execute this PHP file and parse the JSON content. Here's some code:

```<code> private void loadJSON(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                URL_DATA,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            for (int i=2; i<jsonObject.length()+2;i++){
                                String value =jsonObject.getString(String.valueOf(i));
                                if (value.length()!=0) {
                                    ListItem item = new ListItem(value, mParam1+"/"+value, "nothing");
                                    listItems.add(item);
                                }
                            }
                            adapter = new PhotoLibraryAdapter(Photos.this,listItems,photosList,true);
                            photosList.setAdapter(adapter);
                            progressBar.setVisibility(View.GONE);
                        } catch (Exception e) {progressBar.setVisibility(View.GONE);}
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressBar.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
</code>```

Please note that we started for loop from 2 because PHP file returns values from index 2 because value 0 and value 1 are waste values and named "." and ".." respectively.

Hence we get the names of images which we can pass on with url as:
"www.mywebsite.com/.../albumnameretrievedearlier/imagenamegivenbyPHPfile"

and pass it on to the adapter so that we can load the images using Picasso library.

That's it! If you have any question, feel free to ask in comments.

EDIT 1: Here's how it looks:

Body:
I found the solution myself. It's pretty easy to understand and implement and requires the knowledge of JSON only. Firstly, see this image from a directory of my website:

"event1", "event2" folders are the album names. We can create as many needed.

"getfolders file is very important. Content:

{
   "test":[
      {
         "sub":"event1",
         "content":"https://i1.wp.com/www.downloadinformer.com/wp-content/uploads/2017/03/AMPFB.jpg?w=1366",
         "param":"1.php"
      },
      {
         "sub":"event2",
         "content":"myimageurl",
         "param":"myphpfilenamewithextension"
      }
   ]
}

We store album names here as you can see in "sub" field. "content" field contains the link to the thumbnail of the album and "param" contains the name of the corresponding PHP file. Don't worry, you don't need to learn PHP. It's a readymade script.

1.php

<?php

$indir = array_filter(scandir('event1'), function($item) {
        return $item[0] !== '.';
});

echo json_encode($indir);
?>

What this PHP file does? It lists all the names of files present in a specified folder. As you can see, we've specified "event1" as the folder name in this PHP file. So it will return all the images' names in a JSON format. Don't forget to specify this PHP file in "getfolders" file's "param" field.

Ok fine. So this was a sort of algorithm. If you have some confusion, please re-read it again. Now I will show some code.

I made two activities (Didn't prefer Fragments). One to show albums and second to show the images present in it.

Activity 1-> Parses getfolders file and retrieves albums we specified earlier.

Album Title: sub field of the above JSON
, Album Thumbnail: content field of the above JSON
, (Hidden From User) Images Names List: param field

Thus we can show it in a Recyclerview with this information. Now we specify OnClickListener for its items.

On Click Of An Item-> Start second activity using Intent and pass on the album name which is essentially the Folder name on our server. Thus we get access to the folder which contains images. Also pass the "param" field value. This gives us a url "www.mywebsite.com/..../alreadyspecifieddirectory/1.php"

Activity->2 Implement a GridLayoutManager to show pictures to the user. Retrieve the earlier passed values using getIntent(). First we need to execute this PHP file and parse the JSON content. Here's some code:

 private void loadJSON(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                URL_DATA,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            for (int i=2; i<jsonObject.length()+2;i++){
                                String value =jsonObject.getString(String.valueOf(i));
                                if (value.length()!=0) {
                                    ListItem item = new ListItem(value, mParam1+"/"+value, "nothing");
                                    listItems.add(item);
                                }
                            }
                            adapter = new PhotoLibraryAdapter(Photos.this,listItems,photosList,true);
                            photosList.setAdapter(adapter);
                            progressBar.setVisibility(View.GONE);
                        } catch (Exception e) {progressBar.setVisibility(View.GONE);}
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressBar.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

Please note that we started for loop from 2 because PHP file returns values from index 2 because value 0 and value 1 are waste values and named "." and ".." respectively.

Hence we get the names of images which we can pass on with url as:
"www.mywebsite.com/.../albumnameretrievedearlier/imagenamegivenbyPHPfile"

and pass it on to the adapter so that we can load the images using Picasso library.

That's it! If you have any question, feel free to ask in comments.

EDIT 1: Here's how it looks:


问:
Create DataTable Schema from SQL
I want to use a dataadapter with a datatable to insert thousands of record into a 30-column sql table.

```<code>SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
adapter.InsertCommand = new SqlCommand("INSERT INTO ...");
adapter.UpdateBatchSize = 1000;
DataRow r = null;
foreach(var entry in list)
{
    r = table.NewRow();
    r["lastchange"] = entry.TryGet("LastChangeTime");
    // <- throws System.ArgumentException: Column does not belong to table
    ...
}
</code>```

Is there any way to not manually define the schema of the datatable, but to read it from the table the insertions should take place in?

答:
Define SelectCommand and apply Fill method to get data first. If you need only table schema just make the query which returns no rows.

```<code>SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
adapter.SelectCommand = new SqlCommand("SELECT * FROM myTable WHERE 1=2");
adapter.Fill(table);
</code>```

Title: Create DataTable Schema from SQL

Body:
I want to use a dataadapter with a datatable to insert thousands of record into a 30-column sql table.

SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
adapter.InsertCommand = new SqlCommand("INSERT INTO ...");
adapter.UpdateBatchSize = 1000;
DataRow r = null;
foreach(var entry in list)
{
    r = table.NewRow();
    r["lastchange"] = entry.TryGet("LastChangeTime");
    // <- throws System.ArgumentException: Column does not belong to table
    ...
}

Is there any way to not manually define the schema of the datatable, but to read it from the table the insertions should take place in?

Body:
Define SelectCommand and apply Fill method to get data first. If you need only table schema just make the query which returns no rows.

SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
adapter.SelectCommand = new SqlCommand("SELECT * FROM myTable WHERE 1=2");
adapter.Fill(table);


问:
how to redirect to another page, that generates a gridview, after clicking a button in the first page
i have some different buttons in a page after clicking them i want them to redirect me to a page that has a gridview , but for each button it gives a different gridview which are generated by datatables . may you help to find ,how can i do that in asp.net, vb ??
i did two pages at the gridview page i made methods that are binding different gridviews for each button , and in the first page where i have the button click events i did the redirecting to this gridview page and called the corresponding methods. it redirects me but doen't give me any gridview at all :( </p>

答:
Call in button action

Response.Redirect("Your Page Name.aspx")

and call in that page a BindGrid Function that you create to bind the gridview


问:
How to find max of mysql varchar column
i have a table like this with a var char field reference_number
actually i need to get the max of number in that field

```<code> <<student>>

 |`id` | `reference_number`(varchar(25))
 --------------------------
 | 1   | L250
 | 2   | SP521
 | 3   | S120
 | 4   | SP500
 | 5   | S122
</code>```

the desired result is 521 because if we are avoiding the non numeric value then it will come like this

```<code>|`id` | `reference_number`
 --------------------------
 | 1   | 250
 | 2   | 521
 | 3   | 120
 | 4   | 500
 | 5   | 122
</code>```

how to get the the value 521 from the table

答:
I assume you have extracted 'reference_number' as shown in the second snippet from the first snippet. if so, try :::</p>

```<code>select max(cast (reference_number as int)) from student
</code>```

Title: How to find max of mysql varchar column

Body:
i have a table like this with a var char field reference_number
actually i need to get the max of number in that field

 <<student>>

 |`id` | `reference_number`(varchar(25))
 --------------------------
 | 1   | L250
 | 2   | SP521
 | 3   | S120
 | 4   | SP500
 | 5   | S122

the desired result is 521 because if we are avoiding the non numeric value then it will come like this

|`id` | `reference_number`
 --------------------------
 | 1   | 250
 | 2   | 521
 | 3   | 120
 | 4   | 500
 | 5   | 122

how to get the the value 521 from the table

Body:
I assume you have extracted 'reference_number' as shown in the second snippet from the first snippet. if so, try :::

select max(cast (reference_number as int)) from student


答:
You can create/define dataset in your project and can use it in your subsequent operation wherever you need.

Have a look at below link showing how to add dataset to your project and add tables into it and also how to use data adapters with this dataset.

https://msdn.microsoft.com/en-us/library/04y282hb.aspx

https://msdn.microsoft.com/en-us/library/ms171919.aspx

https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/populating-a-dataset-from-a-dataadapter

I hope this will help you. :)

Title: Create DataTable Schema from SQL


问:
IIS not redirecting to maped domain
I have set up IP on BigRock for domain redirection and done binding at IIS. Now when I am browsing my Url it is showing me default site of IIS instead of my hosted one.

Please help me to suggest possible cases.

答:
You need to create a dns record and specify a host header matching your domain name in IIS.

look here: http://www.visualwin.com/Host-Header/

Title: IIS not redirecting to maped domain


问:
Ambiguous Authentication in Netsuite Token Based API call
I am trying to make SOAP calls to the Netsuite API using Token Based Authentication. I have a C# client that is generated from WDSL and it is sending the following request (with the secrets replaced).

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:messages_2016_2.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2016_2.platform.webservices.netsuite.com">
   <soapenv:Header>
      <urn:partnerInfo>
         <urn:partnerId>[MyAccountId]</urn:partnerId>
      </urn:partnerInfo>
      <urn:applicationInfo>
         <urn:applicationId>[MyApplicationId]</urn:applicationId>
      </urn:applicationInfo>
      <urn:tokenPassport>
         <urn1:account>[MyAccountId]</urn1:account>
         <urn1:consumerKey>[MyConsumerKey]</urn1:consumerKey>
         <urn1:token>[MyTokenId]</urn1:token>
         <urn1:nonce>1574515852</urn1:nonce>
         <urn1:timestamp>1499135589</urn1:timestamp>
         <urn1:signature algorithm="HMAC-SHA1">Ll8DbLvTWsBh/G7UtenErR03OrM=</urn1:signature>
      </urn:tokenPassport>
   </soapenv:Header>
   <soapenv:Body>
      <urn:getDataCenterUrls>
         <urn:account>[MyAccountId]</urn:account>
      </urn:getDataCenterUrls>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I am getting the following response

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server.userException</faultcode>
         <faultstring>Ambiguous authentication</faultstring>
         <detail>
            <platformFaults:invalidCredentialsFault xmlns:platformFaults="urn:faults_2016_2.platform.webservices.netsuite.com">
               <platformFaults:code>USER_ERROR</platformFaults:code>
               <platformFaults:message>Ambiguous authentication</platformFaults:message>
            </platformFaults:invalidCredentialsFault>
            <ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">partners-java20004.sea.netledger.com</ns1:hostname>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I have tried lots of different ways of generating the signature, nonce and timestamp. Currently I have the following:

```<code>private string computeNonce()
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] data = new byte[20];
    rng.GetBytes(data);
    int value = Math.Abs(BitConverter.ToInt32(data, 0));
    return value.ToString();
}

private long computeTimestamp()
{
    return ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}

private TokenPassportSignature computeSignature(string accountId, string consumerKey, string consumerSecret, string tokenId, string tokenSecret, string nonce, long timestamp)
{
    string baseString = accountId + "&" + consumerKey + "&" + tokenId + "&" + nonce + "&" + timestamp;
    string key = consumerSecret + "&" + tokenSecret;
    string signature = "";
    var encoding = new System.Text.ASCIIEncoding();
    byte[] keyBytes = encoding.GetBytes(key);
    byte[] baseStringBytes = encoding.GetBytes(baseString);
    using (var hmacSha1 = new HMACSHA1(keyBytes))
    {
        byte[] hashBaseString = hmacSha1.ComputeHash(baseStringBytes);
        signature = Convert.ToBase64String(hashBaseString);
    }
    TokenPassportSignature sign = new TokenPassportSignature();
    sign.algorithm = "HMAC-SHA1";
    sign.Value = signature;
    return sign;
}
</code>```

Does anyone have any ideas? Thanks!

答:
I don't know how it's done in C# with HMAC-SHA1 but in Javascript with CryptoJS HMAC-SHA256 you first sign the string and then encode it in Base64:

```<code>var baseString = ACCOUNT_ID + "&" + NETSUITE_CONSUMER_KEY + "&" + NETSUITE_TOKEN_ID + "&" + NONCE + "&" + TIMESTAMP;
var key = NETSUITE_CONSUMER_SECRET + '&' + NETSUITE_TOKEN_SECRET;
var HMAC256_Sig = cryptoJS.HmacSHA256(baseString, key);
var HMAC256_Sig_Base64 = cryptoJS.enc.Base64.stringify(HMAC256_Sig);
</code>```

Then you output it like:

```<code>'<platformCore:signature algorithm = "HMAC_SHA256">' + HMAC256_Sig_Base64 + '</platformCore:signature>'
</code>```

Body:
I am trying to make SOAP calls to the Netsuite API using Token Based Authentication. I have a C# client that is generated from WDSL and it is sending the following request (with the secrets replaced).

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:messages_2016_2.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2016_2.platform.webservices.netsuite.com">
   <soapenv:Header>
      <urn:partnerInfo>
         <urn:partnerId>[MyAccountId]</urn:partnerId>
      </urn:partnerInfo>
      <urn:applicationInfo>
         <urn:applicationId>[MyApplicationId]</urn:applicationId>
      </urn:applicationInfo>
      <urn:tokenPassport>
         <urn1:account>[MyAccountId]</urn1:account>
         <urn1:consumerKey>[MyConsumerKey]</urn1:consumerKey>
         <urn1:token>[MyTokenId]</urn1:token>
         <urn1:nonce>1574515852</urn1:nonce>
         <urn1:timestamp>1499135589</urn1:timestamp>
         <urn1:signature algorithm="HMAC-SHA1">Ll8DbLvTWsBh/G7UtenErR03OrM=</urn1:signature>
      </urn:tokenPassport>
   </soapenv:Header>
   <soapenv:Body>
      <urn:getDataCenterUrls>
         <urn:account>[MyAccountId]</urn:account>
      </urn:getDataCenterUrls>
   </soapenv:Body>
</soapenv:Envelope>

I am getting the following response

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server.userException</faultcode>
         <faultstring>Ambiguous authentication</faultstring>
         <detail>
            <platformFaults:invalidCredentialsFault xmlns:platformFaults="urn:faults_2016_2.platform.webservices.netsuite.com">
               <platformFaults:code>USER_ERROR</platformFaults:code>
               <platformFaults:message>Ambiguous authentication</platformFaults:message>
            </platformFaults:invalidCredentialsFault>
            <ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">partners-java20004.sea.netledger.com</ns1:hostname>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

I have tried lots of different ways of generating the signature, nonce and timestamp. Currently I have the following:

private string computeNonce()
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] data = new byte[20];
    rng.GetBytes(data);
    int value = Math.Abs(BitConverter.ToInt32(data, 0));
    return value.ToString();
}

private long computeTimestamp()
{
    return ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}

private TokenPassportSignature computeSignature(string accountId, string consumerKey, string consumerSecret, string tokenId, string tokenSecret, string nonce, long timestamp)
{
    string baseString = accountId + "&" + consumerKey + "&" + tokenId + "&" + nonce + "&" + timestamp;
    string key = consumerSecret + "&" + tokenSecret;
    string signature = "";
    var encoding = new System.Text.ASCIIEncoding();
    byte[] keyBytes = encoding.GetBytes(key);
    byte[] baseStringBytes = encoding.GetBytes(baseString);
    using (var hmacSha1 = new HMACSHA1(keyBytes))
    {
        byte[] hashBaseString = hmacSha1.ComputeHash(baseStringBytes);
        signature = Convert.ToBase64String(hashBaseString);
    }
    TokenPassportSignature sign = new TokenPassportSignature();
    sign.algorithm = "HMAC-SHA1";
    sign.Value = signature;
    return sign;
}

Does anyone have any ideas? Thanks!

Body:
I don't know how it's done in C# with HMAC-SHA1 but in Javascript with CryptoJS HMAC-SHA256 you first sign the string and then encode it in Base64:

var baseString = ACCOUNT_ID + "&" + NETSUITE_CONSUMER_KEY + "&" + NETSUITE_TOKEN_ID + "&" + NONCE + "&" + TIMESTAMP;
var key = NETSUITE_CONSUMER_SECRET + '&' + NETSUITE_TOKEN_SECRET;
var HMAC256_Sig = cryptoJS.HmacSHA256(baseString, key);
var HMAC256_Sig_Base64 = cryptoJS.enc.Base64.stringify(HMAC256_Sig);

Then you output it like:

'<platformCore:signature algorithm = "HMAC_SHA256">' + HMAC256_Sig_Base64 + '</platformCore:signature>'


问:
Use VBA in ACCESS to run SQl with CASE statement
I am using VBA to write 0/1 in a column of my table in Access.
If the difference between the dates contained in the two columns [IsYTD?] and [SO Tarihi]) is <365 I would like to write 1 in [IsYTD?] while a 0 in the other case. This is my code for the moment but it doesn't seem to work. Can you help me?</p>

```<code>   SQL3 = "UPDATE [1 - CURRENT RAW DATA SOURCE] SET [IsYTD?] = CASE " & _
    "WHEN ([IsYTD?]-[SO Tarihi])<365 THEN 1 " & _
    "ELSE 0 " & _
    "END"
    DoCmd.RunSQL SQL3
</code>```

答:
CASE WHEN is not valid syntax in MS Access SQL. Use either switch or iif()

Since you only have 2 cases, iif is simpler to code

```<code> SQL3 = "UPDATE [1 - CURRENT RAW DATA SOURCE] SET [IsYTD?] = iif(([IsYTD?]-[SO Tarihi])<365, 1,0)"
</code>```

Body:
I am using VBA to write 0/1 in a column of my table in Access.
If the difference between the dates contained in the two columns [IsYTD?] and [SO Tarihi]) is <365 I would like to write 1 in [IsYTD?] while a 0 in the other case. This is my code for the moment but it doesn't seem to work. Can you help me?

   SQL3 = "UPDATE [1 - CURRENT RAW DATA SOURCE] SET [IsYTD?] = CASE " & _
    "WHEN ([IsYTD?]-[SO Tarihi])<365 THEN 1 " & _
    "ELSE 0 " & _
    "END"
    DoCmd.RunSQL SQL3

Body:
CASE WHEN is not valid syntax in MS Access SQL. Use either switch or iif()

Since you only have 2 cases, iif is simpler to code

 SQL3 = "UPDATE [1 - CURRENT RAW DATA SOURCE] SET [IsYTD?] = iif(([IsYTD?]-[SO Tarihi])<365, 1,0)"


问:
Why a java method is related to an object rather than a class?
I have a question about java's method reference in the following format;

acollection.foreach(System.out::println);

I would expect the code to be something similar to;

acollection.foreach(System.PrintStream::println);

Would you please explain the idea behind relating implementation(code) to an object?

答:
PrintStream.println() is an instance method and thus has to be executed on an instance (object).

acollection.foreach(System.out::println); does just that. It will execute println on System.out for each element in the collection.

acollection.foreach(System.PrintStream::println); can't work because no instance of PrintStream is given - and also because System.PrintStream is not a valid statement.


问:
Spring: Using GET parameters inside of a ModelAttribute
I'm trying to use GET parameters to alter the Model Attribute that's creates a table like object returned to the view. To be specific: I want to send the name of a column as a GET parameter and highlight that column by coloring it differently. My current setup looks like this:

```<code>private String highlightedCol;

  @ModelAttribute("model")
  public Model populateModel() {
    Model model = new Model();
    generateModel();
    //Use Highlighted Col
    return model;
  }

  @RequestMapping("/index")
  public String getIndex(@RequestParam(value="ts", required = false, defaultValue="") String col) {
    highlightedCol = col;
    return "index";
  }
</code>```

I'm having trouble using the "col" parameter in the ModelAttribute because the ModelAttribute gets executed before the RequestMapping. How would i go about using the GET parameter for my Model?

答:
After asking a colleague about my problem he came up with this answer:
I got rid of the @ModelAttribute Annotation and changed the getIndex method to this:

```<code>@RequestMapping("/index")
  public ModelAndView getIndex(@RequestParam(value="ts", required = false, defaultValue="") String col) {
    highlightedCol = col;

    Map<String, Object> model = new HashMap<>();
    model.put("model", populateModel());

    return new ModelAndView("index", model);
  }
</code>```

This way the populateModel method is no longer executed before the getIndex method, allowing me to set the highlightedCol before creating the model, where i need that field.

Body:
I'm trying to use GET parameters to alter the Model Attribute that's creates a table like object returned to the view. To be specific: I want to send the name of a column as a GET parameter and highlight that column by coloring it differently. My current setup looks like this:

private String highlightedCol;

  @ModelAttribute("model")
  public Model populateModel() {
    Model model = new Model();
    generateModel();
    //Use Highlighted Col
    return model;
  }

  @RequestMapping("/index")
  public String getIndex(@RequestParam(value="ts", required = false, defaultValue="") String col) {
    highlightedCol = col;
    return "index";
  }

I'm having trouble using the "col" parameter in the ModelAttribute because the ModelAttribute gets executed before the RequestMapping. How would i go about using the GET parameter for my Model?

Body:
After asking a colleague about my problem he came up with this answer:
I got rid of the @ModelAttribute Annotation and changed the getIndex method to this:

@RequestMapping("/index")
  public ModelAndView getIndex(@RequestParam(value="ts", required = false, defaultValue="") String col) {
    highlightedCol = col;

    Map<String, Object> model = new HashMap<>();
    model.put("model", populateModel());

    return new ModelAndView("index", model);
  }

This way the populateModel method is no longer executed before the getIndex method, allowing me to set the highlightedCol before creating the model, where i need that field.


问:
How to Give action to the tab bar item
This is my code for my tab bar

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"Crops ", @"Articles");

    UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 376, 320, 44)];
    item1 = [[UITabBarItem alloc] initWithTitle:@"TypesToTry" image:[UIImage imageNamed:@"crops.png"] tag:0];
    item2  = [[UITabBarItem alloc] initWithTitle:@"WhenToPlant" image:[UIImage imageNamed:@"crops.png"] tag:1];

    NSArray *items = [NSArray arrayWithObjects:item1,item2,item3,item4,item5, nil];
    [tabBar setItems:items animated:YES];
    [tabBar setSelectedItem:nil];
    tabBar.delegate=self;

    [self.view addSubview:tabBar];
 }
</code>```

what i want is whenever i tap on the 1st tab i want to go to that particular description ,so where to right this action.Please help me in this.
The questions may be simple,but for me they are difficult :),Please help this new developer

Thanks

答:
Hi i think you can add following line of code to make your tab bar item workable

```<code>[item1 performSelectorOnMainThread:@selector(Yourfunction) withObject:nil waitUntilDone:NO];

[item2 performSelectorOnMainThread:@selector(Yourfunction) withObject:nil waitUntilDone:NO];
</code>```

put this line at end of -(void) didLoad, i hope it will work for you

ContentLicense: CC BY-SA 2.5

Title: How to Give action to the tab bar item

Body:
This is my code for my tab bar

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"Crops ", @"Articles");

    UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 376, 320, 44)];
    item1 = [[UITabBarItem alloc] initWithTitle:@"TypesToTry" image:[UIImage imageNamed:@"crops.png"] tag:0];
    item2  = [[UITabBarItem alloc] initWithTitle:@"WhenToPlant" image:[UIImage imageNamed:@"crops.png"] tag:1];

    NSArray *items = [NSArray arrayWithObjects:item1,item2,item3,item4,item5, nil];
    [tabBar setItems:items animated:YES];
    [tabBar setSelectedItem:nil];
    tabBar.delegate=self;

    [self.view addSubview:tabBar];
 }

what i want is whenever i tap on the 1st tab i want to go to that particular description ,so where to right this action.Please help me in this.
The questions may be simple,but for me they are difficult :),Please help this new developer

Thanks

Body:
Hi i think you can add following line of code to make your tab bar item workable

[item1 performSelectorOnMainThread:@selector(Yourfunction) withObject:nil waitUntilDone:NO];

[item2 performSelectorOnMainThread:@selector(Yourfunction) withObject:nil waitUntilDone:NO];

put this line at end of -(void) didLoad, i hope it will work for you


问:
Manage sqlite in android system?
I want to know how to manage sqlite database in android system.
When I use SQLiteDatabase to save data, where is it save in android system?

I want to know it because when I save data via sqlite, other developer can or not to open and change it?

Thanks.

答: The data you save via SQLite in android is saved in the data->data->(your package name)->database->(your database name) of your android device. Other apps and developers cannot access your database if you selected the mode to be PRIVATE. And you can access this database using the ANDROID DEVICE MANAGER which you can open from the Tools->Android->Android Device Manager. It will open an eclipse DDMS in your android Studio. You can open file explorer and go to the directory of your database and pull it from there</p>

Title: Manage sqlite in android system?


问:
How to use SDL2 and SDL_image with cmake
I'm looking for the simplest way to compile a c++ program using SDL2 and SDL_image with cmake.

Here is my best attempt, after hours of searching:

CMakeLists.txt

```<code>project(shooter-cmake2)

cmake_minimum_required(VERSION 2.8)

set(SOURCES
shooter.cpp
classes.cpp
utils.cpp
)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")

add_executable(${PROJECT_NAME} ${SOURCES})

INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2_image REQUIRED sdl2_image)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIR})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARY})
</code>```

I get these errors:

```<code>In function `loadTexture(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, SDL_Renderer*)':
undefined reference to `IMG_LoadTexture'
collect2: ld returned 1 exit status
</code>```

Here is the function call:

```<code>#include "SDL.h"
#include "SDL_image.h"

SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){
    SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str());
    texture != nullptr or die("LoadTexture");
    return texture;
}
</code>```

答:
There are two blog posts about this here:

Using SDL2 with CMake

Using SDL2_image with CMake

Basically you need a FindSDL2.cmake and FindSDL2_image.cmake module. They can be based of the ones that work for SDL 1.2 which are included in CMake already. Using these Find modules will also work on Windows.

If you are on Linux and only need SDL2 you don't even need the FindSDL2.cmake as the following already works:

```<code>cmake_minimum_required(VERSION 3.7)

project(SDL2Test)

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})

add_executable(SDL2Test Main.cpp)
target_link_libraries(SDL2Test ${SDL2_LIBRARIES})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for the simplest way to compile a c++ program using SDL2 and SDL_image with cmake.

Here is my best attempt, after hours of searching:

CMakeLists.txt

project(shooter-cmake2)

cmake_minimum_required(VERSION 2.8)

set(SOURCES
shooter.cpp
classes.cpp
utils.cpp
)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")

add_executable(${PROJECT_NAME} ${SOURCES})

INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2_image REQUIRED sdl2_image)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIR})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARY})

I get these errors:

In function `loadTexture(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, SDL_Renderer*)':
undefined reference to `IMG_LoadTexture'
collect2: ld returned 1 exit status

Here is the function call:

#include "SDL.h"
#include "SDL_image.h"

SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){
    SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str());
    texture != nullptr or die("LoadTexture");
    return texture;
}

Body:
There are two blog posts about this here:

Using SDL2 with CMake

Using SDL2_image with CMake

Basically you need a FindSDL2.cmake and FindSDL2_image.cmake module. They can be based of the ones that work for SDL 1.2 which are included in CMake already. Using these Find modules will also work on Windows.

If you are on Linux and only need SDL2 you don't even need the FindSDL2.cmake as the following already works:

cmake_minimum_required(VERSION 3.7)

project(SDL2Test)

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})

add_executable(SDL2Test Main.cpp)
target_link_libraries(SDL2Test ${SDL2_LIBRARIES})


问:
CellStyle is applied only upon editing cell
I am using this sample to change the color of a particular cell in the file

```<code>InputStream inp = new FileInputStream("C:\\temp\\vineet.xlsx");
//InputStream inp = new FileInputStream("workbook.xlsx");

Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);

XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();

XSSFCellStyle defaultStyle = (XSSFCellStyle) wb.getCellStyleAt((short) 0);

style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
  cell = row.createCell(3);
cell.setCellType(CellType.STRING);
cell.setCellValue("a test");

if (cell.getCellStyle().equals(defaultStyle)) {
  cell.setCellStyle(style);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("C:\\temp\\vineet.xlsx");
wb.write(fileOut);
fileOut.close();
</code>```

at the first glance there are no changes, but when i try to edit the cell value using excel then the cell became yellow-backgrounded.

答:
you already got the needed line to do what you need but you commented it out.

```<code>//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
</code>```

and change this:

```<code>style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
</code>```

to

```<code>style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
</code>```

Body:
I am using this sample to change the color of a particular cell in the file

InputStream inp = new FileInputStream("C:\\temp\\vineet.xlsx");
//InputStream inp = new FileInputStream("workbook.xlsx");

Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);

XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();

XSSFCellStyle defaultStyle = (XSSFCellStyle) wb.getCellStyleAt((short) 0);

style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
  cell = row.createCell(3);
cell.setCellType(CellType.STRING);
cell.setCellValue("a test");

if (cell.getCellStyle().equals(defaultStyle)) {
  cell.setCellStyle(style);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("C:\\temp\\vineet.xlsx");
wb.write(fileOut);
fileOut.close();

at the first glance there are no changes, but when i try to edit the cell value using excel then the cell became yellow-backgrounded.

Body:
you already got the needed line to do what you need but you commented it out.

//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

and change this:

style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());

to

style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());


问:
Optimize the performance of SQL query
I need to fetch all the ID's from certain tables in between two timestamps

```<code>select Distinct PK1 from(
SELECT A.PK1
FROM  T1 A , T2 B, T3 C, T4 D
WHERE TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS' )>= '2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS' ) <= '2016-06-02 00:00:00' and a.PK2 is not null
AND A.PK2=B.PK2 AND B.PK3 IS NOT NULL AND B.PK3=C.PK3 AND C.PK4 IS NOT NULL
AND C.PK4=D.PK4 AND D.PK5 IS NOT NULL
union

SELECT A.PK1
FROM  T1 a, T2 B , T3 C, T4 D
WHERE TO_CHAR(A.DATE2,'YYYY-MM-DD HH24:MI:SS' )>= '2016-06-01 00:00:00'
AND TO_CHAR(A.DATE2,'YYYY-MM-DD HH24:MI:SS' )  <='2016-06-02 00:00:00'  and a.PK2 is not null
AND A.PK2=B.PK2 AND B.PK3 IS NOT NULL AND B.PK3=C.PK3 AND C.PK4 IS NOT NULL
AND C.PK4=D.PK4 AND D.PK5 IS NOT NULL
UNION
select A.PK1
from  T11 A, T1 B , T2 C, T3 D, T4 E  WHERE
TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')<='2016-06-02 00:00:00'
AND A.PK1=B.PK1 AND B.PK2 IS
NOT NULL AND B.PK2=C.PK2 AND C.PK3 IS NOT NULL AND C.PK3=D.PK3 AND D.PK4 IS NOT NULL
AND D.PK4=E.PK4 AND E.PK5 IS NOT NULL
UNION

select A.PK1
from  T15 A , T1 B, T2 C, T3 D, T4 E WHERE
TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'
AND A.PK1=B.PK1 AND B.PK2 IS NOT NULL
AND B.PK2=C.PK2 AND C.PK3 IS NOT NULL AND C.PK3=D.PK3 AND D.PK4 IS NOT NULL
AND D.PK4=E.PK4 AND E.PK5 IS NOT NULL

UNION

select A.PK1
from  T12 a, T6 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00' and A.PK6=b.PK6 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE2,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE2,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE3,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE3,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION
select A.PK1
from  T14 a, T8 b, T1 C, T2 D, T3 E,
 T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00' and A.PK8=b.PK8 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL
  AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

 )
</code>```

My question is how can I optimize the query for better performance.

答: You are converting your dates to chars. If you do the compares using the datetype date, and add indexes to the date columns your performance will probably increase. The conversions are really bad for performance and result in table scans.</p>

Title: Optimize the performance of SQL query

Body:
I need to fetch all the ID's from certain tables in between two timestamps

select Distinct PK1 from(
SELECT A.PK1
FROM  T1 A , T2 B, T3 C, T4 D
WHERE TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS' )>= '2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS' ) <= '2016-06-02 00:00:00' and a.PK2 is not null
AND A.PK2=B.PK2 AND B.PK3 IS NOT NULL AND B.PK3=C.PK3 AND C.PK4 IS NOT NULL
AND C.PK4=D.PK4 AND D.PK5 IS NOT NULL
union

SELECT A.PK1
FROM  T1 a, T2 B , T3 C, T4 D
WHERE TO_CHAR(A.DATE2,'YYYY-MM-DD HH24:MI:SS' )>= '2016-06-01 00:00:00'
AND TO_CHAR(A.DATE2,'YYYY-MM-DD HH24:MI:SS' )  <='2016-06-02 00:00:00'  and a.PK2 is not null
AND A.PK2=B.PK2 AND B.PK3 IS NOT NULL AND B.PK3=C.PK3 AND C.PK4 IS NOT NULL
AND C.PK4=D.PK4 AND D.PK5 IS NOT NULL
UNION
select A.PK1
from  T11 A, T1 B , T2 C, T3 D, T4 E  WHERE
TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')<='2016-06-02 00:00:00'
AND A.PK1=B.PK1 AND B.PK2 IS
NOT NULL AND B.PK2=C.PK2 AND C.PK3 IS NOT NULL AND C.PK3=D.PK3 AND D.PK4 IS NOT NULL
AND D.PK4=E.PK4 AND E.PK5 IS NOT NULL
UNION

select A.PK1
from  T15 A , T1 B, T2 C, T3 D, T4 E WHERE
TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'
AND A.PK1=B.PK1 AND B.PK2 IS NOT NULL
AND B.PK2=C.PK2 AND C.PK3 IS NOT NULL AND C.PK3=D.PK3 AND D.PK4 IS NOT NULL
AND D.PK4=E.PK4 AND E.PK5 IS NOT NULL

UNION

select A.PK1
from  T12 a, T6 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00' and A.PK6=b.PK6 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE2,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE2,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE3,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE3,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION
select A.PK1
from  T14 a, T8 b, T1 C, T2 D, T3 E,
 T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00' and A.PK8=b.PK8 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL
  AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

 )

My question is how can I optimize the query for better performance.


问:
How to calculate number of Sundays between two dates using mysql
I need to find number of Sundays between two dates using mysql. I know how to do it using PHP But i need it to be calculated using mysql.</p>

答:
```<code>    SELECT a.StartDate, a.EndDate,
    (DAY(EndDate - StartDate) / 7)
    +  iif(DAY(EndDate - StartDate)%7 + DATEPART(DW, StartDate) > 8 , 1, 0)
    Sundays FROM
    (SELECT GETDATE() StartDate, DATEADD(DAY, 11, GETDATE()) EndDate) a
</code>```

This is useful for multiple start and end dates in a table.
no need of variables and loops!

How it works: determines the number of full weeks between start and end date,

determines the days less than a week and add with the start day index(1,2,3,4,5,6,7) if that value Greater than count 8(means which is Sunday !)

For Sunday week day index is 1, day 8 is nothing but index 1.

Body:
    SELECT a.StartDate, a.EndDate,
    (DAY(EndDate - StartDate) / 7)
    +  iif(DAY(EndDate - StartDate)%7 + DATEPART(DW, StartDate) > 8 , 1, 0)
    Sundays FROM
    (SELECT GETDATE() StartDate, DATEADD(DAY, 11, GETDATE()) EndDate) a

This is useful for multiple start and end dates in a table.
no need of variables and loops!

How it works: determines the number of full weeks between start and end date,

determines the days less than a week and add with the start day index(1,2,3,4,5,6,7) if that value Greater than count 8(means which is Sunday !)

For Sunday week day index is 1, day 8 is nothing but index 1.


问:
Java two varargs in one method
Is there any way in Java to create a method, which is expecting two different varargs?
I know, with the same object kind it isn't possible because the compiler doesn't know where to start or to end. But why it also isn't possible with two different Object types?

For example:

```<code>public void doSomething(String... s, int... i){
    //...
    //...
}
</code>```

Is there any way to create a method like this?

Thank you!

答:
You can convert your varargs to arrays

```<code>public void doSomething(String[] s, int[] i) {
    ...
}
</code>```

then with some helper methods to convert your varargs to array like this:

```<code>public static int[] intsAsArray(int... ints) {
    return ints;
}

public static <T> T[] asArray(T... ts) {
    return ts;
}
</code>```

Then you can use those helper methods to convert your vararged parameters.

```<code>doSomething(asArray("a", "b", "c", "d"), intsAsArray(1, 2, 3));
</code>```

Title: Java two varargs in one method

Body:
Is there any way in Java to create a method, which is expecting two different varargs?
I know, with the same object kind it isn't possible because the compiler doesn't know where to start or to end. But why it also isn't possible with two different Object types?

For example:

public void doSomething(String... s, int... i){
    //...
    //...
}

Is there any way to create a method like this?

Thank you!

Body:
You can convert your varargs to arrays

public void doSomething(String[] s, int[] i) {
    ...
}

then with some helper methods to convert your varargs to array like this:

public static int[] intsAsArray(int... ints) {
    return ints;
}

public static <T> T[] asArray(T... ts) {
    return ts;
}

Then you can use those helper methods to convert your vararged parameters.

doSomething(asArray("a", "b", "c", "d"), intsAsArray(1, 2, 3));


问:
Grails 3 - forward with filtered params
In my Grails 3 controller have two actions

```<code>def one() {
    forward([ action: 'two', params: [ a: 3 ] ])
}

def two() {
    println params
}
</code>```

When I call /myController/one?a=1, the printed params are

```<code>[a:[3, 1], controller:myController, action:two]
</code>```

Said that I was somehow surprised of this outcome, I proceeded by changing the one action as follows

```<code>def one() {
    params.remove('a')
    println params
    forward([ action: 'two', params: [ a: 3 ] ])
}
</code>```

The two printlns combined showed

```<code>[controller:myController, action:one]
[a:[3, 1], controller:myController, action:two]
</code>```

with the latter again includign both the original a parameter's value and the new custom value.

My question is: is there something I can do to get rid of the original value, without putting ugly workarounds in place (like using a different name for my param)?

答:
I guess this comment from Graeme Rocher settles any doubts about the overall feasibility:

A forward is supposed to forward all of the origin params [...]

However there is no way with the way current servlets work to "override" a parameter, the originals are always retained on a forward.

Title: Grails 3 - forward with filtered params

Body:
In my Grails 3 controller have two actions

def one() {
    forward([ action: 'two', params: [ a: 3 ] ])
}

def two() {
    println params
}

When I call /myController/one?a=1, the printed params are

[a:[3, 1], controller:myController, action:two]

Said that I was somehow surprised of this outcome, I proceeded by changing the one action as follows

def one() {
    params.remove('a')
    println params
    forward([ action: 'two', params: [ a: 3 ] ])
}

The two printlns combined showed

[controller:myController, action:one]
[a:[3, 1], controller:myController, action:two]

with the latter again includign both the original a parameter's value and the new custom value.

My question is: is there something I can do to get rid of the original value, without putting ugly workarounds in place (like using a different name for my param)?


问:
Reverse the given number program in PL/SQL
I was trying to execute this program but it only outputs the ~ symbol.

This is the code:

```<code>DECLARE
   N_NUM   NUMBER := 234;
   N_REM   NUMBER;
   N_REV   NUMBER := 0;
BEGIN
   WHILE N_NUM != 0
   LOOP
      N_REM := MOD (N_NUM, 10);
      N_NUM := (N_NUM / 10);
      N_REV := N_REV * 10 + N_REM;
   END LOOP;

   DBMS_OUTPUT.PUT_LINE (N_REV);
END;
</code>```

答:
Use Floor function as shown below:

```<code>N_NUM := FLOOR(N_NUM/10)
</code>```

As this floor function returns only 23 instead of 23.4

Body:
I was trying to execute this program but it only outputs the ~ symbol.

This is the code:

DECLARE
   N_NUM   NUMBER := 234;
   N_REM   NUMBER;
   N_REV   NUMBER := 0;
BEGIN
   WHILE N_NUM != 0
   LOOP
      N_REM := MOD (N_NUM, 10);
      N_NUM := (N_NUM / 10);
      N_REV := N_REV * 10 + N_REM;
   END LOOP;

   DBMS_OUTPUT.PUT_LINE (N_REV);
END;

Body:
Use Floor function as shown below:

N_NUM := FLOOR(N_NUM/10)

As this floor function returns only 23 instead of 23.4


问:
Kubernetes Job: exactly one pod
I want to run only one pod of my kubernetes app at a time(relaunch in case of failure), I am using job controller.

But as per documentations, kubernetes may launch more than one pods and will eventually achieve specified replicas. Is there any way to achieve exactly one pod at a time or any recommended design pattern for such use cases.

My app is reading data from HDFS and writing it to a message queue. It exits after processing all the files. I want to minimize possibility of writing duplicate records.

答:
In principle, in the case of Jobs with no paralellism implied, there shouldn't be this kind of "race condition" ("should be 1" according to the documentation [1]). The job would be rescheduled only if an attempt fails. Did you come across the situation where 2 pods from the same job were being executed at the same time?

In any case, if you want to be completely sure, you may want to implement an extra coordination method or external solution.

[1] https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/

Title: Kubernetes Job: exactly one pod


问:
Finding best match in mongoengine database with Django
Suppose we have a a Django model similar to this:

```<code>from mongoengine import (Document, StringField, DateTimeField)

class MyModel(Document):
    car = StringField()
    plane = StringField()
    name = StringField()
    some_field = SecretField()
    date = DateTimeField()
    # some more fields ...
</code>```

Then, we want to take best matching object from our database for a given set of parameters, for example

```<code>@classmethod
def desired_method(cls, **kwargs):
    # for a given kwargs, choose the one that have fields in db
    # and return object for that parameter (ordered by date, say last one)
</code>```

For example, calling MyModel.desired_method(car='Ford', name='Bettsy') would return last object created in db, with Ford car having name Bettsy.

On the other hand, calling MyModel.desired_method(plane='Airbus', some_field='hashed_msg', pilot='Ron', age='7') would return last object with specified plane and some_field fields, but others are ignored, as they do not exists in our model.

The purpose for all that is to be able to flexible extend functionality - let's say we are using model to add new objects to db, with specified car, name and some_field fields. With some populated db, we got request from client to start distinguish objects by another field version. We can't do it backwards, but we may add field version to our model, populate db with new entries, and change code in application from:

```<code>my_car = return_car()
my_name = return_name()
result = MyModel.desired_method(car=my_car, name=my_name)
</code>```

to:

```<code>my_car = return_car()
my_name = return_name()
my_version = return_version()
result = MyModel.desired_method(car=my_car, name=my_name, version=my_version)
</code>```

such that if we call MyModel.desired_method(car='Ford', name='Bettsy',version='123') we still get object for a given car and name, even if given entry does not have version (it was not in the model while adding to db - backward compatibility).

More generally, solution could be create a model with dynamically added fields - so for example

```<code>new_item = MyModel(name='John Doe', age='90')
new_item.save()
</code>```

would create a new field age in the model, but I don't know if it is even possible

答:
```<code>In [12]: class MyModel(Document):
    ...:     car = StringField()
    ...:     plane = StringField()
    ...:     name = StringField()
    ...:     some_field = StringField()
    ...:     date = DateTimeField()
    ...:     @queryset_manager
    ...:     def desired_method(cls, queryset, **kwargs):
    ...:         return queryset(**kwargs)
    ...:

In [13]: MyModel.desired_method(car='Ford', name='Betsy')
Out[13]: []

In [14]: car = MyModel(car='Ford', name='Betsy').save()

In [15]: MyModel.desired_method(car='Ford', name='Betsy')
Out[15]: [<MyModel: MyModel object>]
</code>```

does that answer your question?

Body:
Suppose we have a a Django model similar to this:

from mongoengine import (Document, StringField, DateTimeField)

class MyModel(Document):
    car = StringField()
    plane = StringField()
    name = StringField()
    some_field = SecretField()
    date = DateTimeField()
    # some more fields ...

Then, we want to take best matching object from our database for a given set of parameters, for example

@classmethod
def desired_method(cls, **kwargs):
    # for a given kwargs, choose the one that have fields in db
    # and return object for that parameter (ordered by date, say last one)

For example, calling MyModel.desired_method(car='Ford', name='Bettsy') would return last object created in db, with Ford car having name Bettsy.

On the other hand, calling MyModel.desired_method(plane='Airbus', some_field='hashed_msg', pilot='Ron', age='7') would return last object with specified plane and some_field fields, but others are ignored, as they do not exists in our model.

The purpose for all that is to be able to flexible extend functionality - let's say we are using model to add new objects to db, with specified car, name and some_field fields. With some populated db, we got request from client to start distinguish objects by another field version. We can't do it backwards, but we may add field version to our model, populate db with new entries, and change code in application from:

my_car = return_car()
my_name = return_name()
result = MyModel.desired_method(car=my_car, name=my_name)

to:

my_car = return_car()
my_name = return_name()
my_version = return_version()
result = MyModel.desired_method(car=my_car, name=my_name, version=my_version)

such that if we call MyModel.desired_method(car='Ford', name='Bettsy',version='123') we still get object for a given car and name, even if given entry does not have version (it was not in the model while adding to db - backward compatibility).

More generally, solution could be create a model with dynamically added fields - so for example

new_item = MyModel(name='John Doe', age='90')
new_item.save()

would create a new field age in the model, but I don't know if it is even possible

Body:
In [12]: class MyModel(Document):
    ...:     car = StringField()
    ...:     plane = StringField()
    ...:     name = StringField()
    ...:     some_field = StringField()
    ...:     date = DateTimeField()
    ...:     @queryset_manager
    ...:     def desired_method(cls, queryset, **kwargs):
    ...:         return queryset(**kwargs)
    ...:

In [13]: MyModel.desired_method(car='Ford', name='Betsy')
Out[13]: []

In [14]: car = MyModel(car='Ford', name='Betsy').save()

In [15]: MyModel.desired_method(car='Ford', name='Betsy')
Out[15]: [<MyModel: MyModel object>]

does that answer your question?


问:
jQuery autocomplete: How to show an animated gif loading image
I'm using the jQuery AutoComplete plugin combined with ajax. Do you know how can I show a progress indicator while the ajax search is performed?

This is my current code.

```<code><script type="text/javascript">
    $("#autocomplete-textbox").autocomplete('http://www.example.com/AutoComplete/FindUsers');
</script>

<div>
    <input type="text" id="autocomplete-textbox" />
    <span class="autocomplete-animation"><img id="ajaxanimation" src="../img/indicator.gif")"/></span>
</div>
</code>```

The FindUsers URL returns a user list in the content.

答:
```<code>$("#autocomplete-textbox").autocomplete
(
search  : function(){$(this).addClass('working');},
open    : function(){$(this).removeClass('working');}
)
</code>```

where CSS class working is defined as follow:

```<code>.working{background:url('../img/indicator.gif') no-repeat right center;}
</code>```

EDIT

Sam's answer is a better approach to address the problem

Body:
I'm using the jQuery AutoComplete plugin combined with ajax. Do you know how can I show a progress indicator while the ajax search is performed?

This is my current code.

    <input type="text" id="autocomplete-textbox" />

The FindUsers URL returns a user list in the content.

Body:
$("#autocomplete-textbox").autocomplete
(
search  : function(){$(this).addClass('working');},
open    : function(){$(this).removeClass('working');}
)

where CSS class working is defined as follow:

.working{background:url('../img/indicator.gif') no-repeat right center;}

EDIT

Sam's answer is a better approach to address the problem


问:
How to access constants from a java class through other variable?
I have java class which has all constants as given below:

```<code>public final class CategoryIDs {

  public static final String Extraction_of_natural_gas = "1111";
  public static final String Mining_of_hard_coal = "2222";
  public static final String Mining_of_iron_ores = "3333";
  public static final String Mining_of_lignite = "4444";

}
</code>```

Now I want to access these constants in some other class through a variable which holds name of the variable.

For example:

```<code>String temp = "Extraction_of_natural_gas";
</code>```

Using this temp variable I want to access constants from above class. But I can't do  CategoryIDs.temp as it isn't allowed. So what is the best way to achieve this?

答:
You can use reflection to extract it:

```<code>String value = (String) CategoryIDs.class.getField(temp).get(null);
</code>```

The null argument passed to get signifies this is a static field, and no instance is required in order to get its value.

Note that this technique is very error prone. The code above doesn't contain any error checking or exception handling in order to make it easier to read, but a real application should probably contain them.

Body:
I have java class which has all constants as given below:

public final class CategoryIDs {

  public static final String Extraction_of_natural_gas = "1111";
  public static final String Mining_of_hard_coal = "2222";
  public static final String Mining_of_iron_ores = "3333";
  public static final String Mining_of_lignite = "4444";

}

Now I want to access these constants in some other class through a variable which holds name of the variable.

For example:

String temp = "Extraction_of_natural_gas";

Using this temp variable I want to access constants from above class. But I can't do  CategoryIDs.temp as it isn't allowed. So what is the best way to achieve this?

Body:
You can use reflection to extract it:

String value = (String) CategoryIDs.class.getField(temp).get(null);

The null argument passed to get signifies this is a static field, and no instance is required in order to get its value.

Note that this technique is very error prone. The code above doesn't contain any error checking or exception handling in order to make it easier to read, but a real application should probably contain them.


问:
pandas to_sql enforced dtype for sqlite - incompatibility with unicode_literals
I run into a problem when wanting to save pandas dataframe to a sqlite database with specified the datatype. I have the following module.py:

```<code># Import from future to make Python2 behave like Python3
from __future__ import unicode_literals

import os
import pandas as pd

from sqlalchemy import create_engine
engine=create_engine('sqlite:///foo.db')
cnx = engine.raw_connection()

df_out = pd.DataFrame({'col1': ['1', '1'] ,'col2': ['1.0', '1.2'],'col3': ['A', 'B']})

labels=['col1','col2','col3']
types=['TEXT','TEXT','TEXT']
mapping={k:v for k,v in zip(labels,types)}

df_out.to_sql(name='table',if_exists='replace',con=cnx,dtype=mapping)

df_in=pd.read_sql(sql='''SELECT * FROM "table" ''',con=cnx)
</code>```

When I  run this code into a Python interpreter, I get the following error message ValueError: col2 (TEXT) not a string.

For what I discovered the incompatibility comes from the statement from __future__ import unicode_literals. When removing it, I get the expected behaviour : df_in.dtypes describing 3 columns of object type.

I tried to used raw strings types=[r'TEXT',r'TEXT',r'TEXT'] but it did not change anything.

Does anyone have a solution or a workaround.

Best regards,

答:
In Python 2, the future-import unicode_literals makes string literals behave like in Python 3.
That means a prefix-less string literal gives you a unicode string:

```<code>>>> type('foo')
<type 'unicode'>
</code>```

If you want a legacy str, use a b prefix (because it corresponds to Python 3's bytes string):

```<code>>>> type(b'foo')
<type 'str'>
</code>```

The r prefix doesn't affect the type. It only changes how the interpreter treats backslashes when parsing string literals in the source code:

```<code>>>> r'\foo'
u'\\foo'
>>> '\\foo'
u'\\foo'
</code>```

It's just a different way of writing the literal, the same way you can write 1e-2 or 0.01 to get the same float value. From a string's value you can never tell if it was created through r'...' or '...' notation (or read from a file etc.).

You can combine the r prefix with the b prefix if you want to create a str with typing less backslashes:

```<code>>>> br'\foo'
'\\foo'
</code>```

But that's not needed too often because of Python 2's automatic type coercion between str and unicode.

Body:
I run into a problem when wanting to save pandas dataframe to a sqlite database with specified the datatype. I have the following module.py:

# Import from future to make Python2 behave like Python3
from __future__ import unicode_literals

import os
import pandas as pd

from sqlalchemy import create_engine
engine=create_engine('sqlite:///foo.db')
cnx = engine.raw_connection()

df_out = pd.DataFrame({'col1': ['1', '1'] ,'col2': ['1.0', '1.2'],'col3': ['A', 'B']})

labels=['col1','col2','col3']
types=['TEXT','TEXT','TEXT']
mapping={k:v for k,v in zip(labels,types)}

df_out.to_sql(name='table',if_exists='replace',con=cnx,dtype=mapping)

df_in=pd.read_sql(sql='''SELECT * FROM "table" ''',con=cnx)

When I  run this code into a Python interpreter, I get the following error message ValueError: col2 (TEXT) not a string.

For what I discovered the incompatibility comes from the statement from __future__ import unicode_literals. When removing it, I get the expected behaviour : df_in.dtypes describing 3 columns of object type.

I tried to used raw strings types=[r'TEXT',r'TEXT',r'TEXT'] but it did not change anything.

Does anyone have a solution or a workaround.

Best regards,

Body:
In Python 2, the future-import unicode_literals makes string literals behave like in Python 3.
That means a prefix-less string literal gives you a unicode string:

>>> type('foo')
<type 'unicode'>

If you want a legacy str, use a b prefix (because it corresponds to Python 3's bytes string):

>>> type(b'foo')
<type 'str'>

The r prefix doesn't affect the type. It only changes how the interpreter treats backslashes when parsing string literals in the source code:

>>> r'\foo'
u'\\foo'
>>> '\\foo'
u'\\foo'

It's just a different way of writing the literal, the same way you can write 1e-2 or 0.01 to get the same float value. From a string's value you can never tell if it was created through r'...' or '...' notation (or read from a file etc.).

You can combine the r prefix with the b prefix if you want to create a str with typing less backslashes:

>>> br'\foo'
'\\foo'

But that's not needed too often because of Python 2's automatic type coercion between str and unicode.


问:
How to find max of mysql varchar column
i have a table like this with a var char field reference_number
actually i need to get the max of number in that field

```<code> <<student>>

 |`id` | `reference_number`(varchar(25))
 --------------------------
 | 1   | L250
 | 2   | SP521
 | 3   | S120
 | 4   | SP500
 | 5   | S122
</code>```

the desired result is 521 because if we are avoiding the non numeric value then it will come like this

```<code>|`id` | `reference_number`
 --------------------------
 | 1   | 250
 | 2   | 521
 | 3   | 120
 | 4   | 500
 | 5   | 122
</code>```

how to get the the value 521 from the table

答:
In order to get the number 521 (and all the numbers from the reference_number column) you could try:

```<code>SELECT *
FROM yourtable
WHERE reference_number REGEXP '^[0-9]+$';
</code>```

And then you can add an order by statement.

Title: How to find max of mysql varchar column

Body:
i have a table like this with a var char field reference_number
actually i need to get the max of number in that field

 <<student>>

 |`id` | `reference_number`(varchar(25))
 --------------------------
 | 1   | L250
 | 2   | SP521
 | 3   | S120
 | 4   | SP500
 | 5   | S122

the desired result is 521 because if we are avoiding the non numeric value then it will come like this

|`id` | `reference_number`
 --------------------------
 | 1   | 250
 | 2   | 521
 | 3   | 120
 | 4   | 500
 | 5   | 122

how to get the the value 521 from the table

Body:
In order to get the number 521 (and all the numbers from the reference_number column) you could try:

SELECT *
FROM yourtable
WHERE reference_number REGEXP '^[0-9]+$';

And then you can add an order by statement.


问:
How to remove all but the last 3 parts of FQDN?
I have a list of IP lookups and I wish to remove all but the last 3 parts, so:
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
would become
163data.com.cn

I have spent hours searching for clues, including parameter substitution, but the closest I got was:

```<code>$ string="98.254.237.114.broad.lyg.js.dynamic.163data.com.cn"
$ string1=${string%.*.*.*}
$ echo $string1
</code>```

Which gives me the inverted answer of:
98.254.237.114.broad.lyg.js.dynamic
which is everything but the last 3 parts.

A script to do a list would be better than just the static example I have here.
Using CentOS 6, I don't mind if it by using sed, cut, awk, whatever.
Any help appreciated.

Thanks, now that I have working answers, may I ask as a follow up to then process the resulting list and if the last part (after last '.') is 3 characters - eg .com .net etc, then to just keep the last 2 parts.

If this is against protocol, please advise how to do a follow up question.

答:
```<code>$ echo $string | awk -F'.' '{printf "%s.%s.%s\n",$(NF-2),$(NF-1),$NF}'
163data.com.cn
</code>```

Brief explanation,

Set the field separator to .

Print only last 3 field using the awk parameter $(NF-2), $(NF-1),and $NF.

And there's also another option you may try,

```<code>$ echo $string | awk -v FPAT='[^.]+.[^.]+.[^.]+$' '{print $NF}'
163data.com.cn
</code>```

Body:
I have a list of IP lookups and I wish to remove all but the last 3 parts, so:
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
would become
163data.com.cn

I have spent hours searching for clues, including parameter substitution, but the closest I got was:

$ string="98.254.237.114.broad.lyg.js.dynamic.163data.com.cn"
$ string1=${string%.*.*.*}
$ echo $string1

Which gives me the inverted answer of:
98.254.237.114.broad.lyg.js.dynamic
which is everything but the last 3 parts.

A script to do a list would be better than just the static example I have here.
Using CentOS 6, I don't mind if it by using sed, cut, awk, whatever.
Any help appreciated.

Thanks, now that I have working answers, may I ask as a follow up to then process the resulting list and if the last part (after last '.') is 3 characters - eg .com .net etc, then to just keep the last 2 parts.

If this is against protocol, please advise how to do a follow up question.

Body:
$ echo $string | awk -F'.' '{printf "%s.%s.%s\n",$(NF-2),$(NF-1),$NF}'
163data.com.cn

Brief explanation,

Set the field separator to .

Print only last 3 field using the awk parameter $(NF-2), $(NF-1),and $NF.

And there's also another option you may try,

$ echo $string | awk -v FPAT='[^.]+.[^.]+.[^.]+$' '{print $NF}'
163data.com.cn


问:
How to get fat scroll bar on div using CSS?
If I use the CSS overflow property:

```<code>overflow: scroll;
</code>```

I get a thin scrollbar by default. How can I style it to get a fat (and flat) scrollbar?

答:
You can find here an answer for how to change the scrollbar's design on multiple browsers: https://stackoverflow.com/a/14150577/1564840

But that means different css settings for each browser (ie/chrome/mozilla..). That's why I suggest you to use a javascript library, here are a few examples: http://www.jqueryrain.com/2012/07/jquery-scrollbar-plugin-examples/ . These js libraries offer support for most of the browsers.

If you choose to edit CSS, be careful because the "position" property influences the scroll display. You might find some problems on safari browsers or on mobile devices.

Body:
If I use the CSS overflow property:

overflow: scroll;

I get a thin scrollbar by default. How can I style it to get a fat (and flat) scrollbar?


问:
nodejs express wildcard route not working
I'm doing an API in nodejs with express as router.

Now i'm trying to implement an client-id and an apikey to add some security to the API, and the problem that i'm facing is the next:

One of my API call is like this:
router.get("roles/get-objects/:mail/:filter*?")
So this means, that i can request an object like this:
/roles/get-objects/mail@mail.com/customer

Now the tricky part begins... when I needed to stablish a middleware to read an client-id and an apikey to verify that the client is authorized to se the API, so I did this:

In the declaration of the middleware, I use this wildcard:
router.all('/*', function (req, res, next) {
XXXX})

The thing is, I have tried in the middleware, as a wildcard everything...
I want that any API call is filtered thru that middleware, but apparently I can't find the right wildcard for it...

When I use /roles/* as wildcard, if I do a request to /roles it does work, but when I use the complete URL like: /roles/get-objects/mail@mail.com/customer it doesn't go thru my middleware.

So anybody has any idea? i'm starting to loose my mind

Thank you so much to all of you!

EDIT:
Now i'm using this middleware declaration:
router.use(function (req, res, next) {XXXX})

So when I call:
/roles/get-objects/

It's executed, the problem is when I add the email to the route:
/roles/get-objects/mail@mail.com

The app goes directly to the route that i have for that, but omits my middleware:
router.get("roles/get-objects/:mail",

I don't understand why is this happening, apparently everything should go thru my middleware first, or am I wrong?

答:
If you want to establish a middleware to check all HTTP request whose URL starting with /roles/, the middleware should be placed before any other specific router definition:

```<code>router.use('/roles', function(req, res, next) {...});
...
router.get('/roles/get-objects/:mail', ...);
</code>```

If the middleware is defined after specific route, when HTTP request comes in, the specific route is targeted and processed, the middleware won't be executed any more:

```<code>router.get('/roles/get-objects/:mail', ...);
...
router.use('/roles', function(req, res, next) {...}); // This middleware logic won't execute when request is sent to '/roles/get-objects/some-email', as the request has already been handled and response is already sent to browser.
</code>```

Body:
If you want to establish a middleware to check all HTTP request whose URL starting with /roles/, the middleware should be placed before any other specific router definition:

router.use('/roles', function(req, res, next) {...});
...
router.get('/roles/get-objects/:mail', ...);

If the middleware is defined after specific route, when HTTP request comes in, the specific route is targeted and processed, the middleware won't be executed any more:

router.get('/roles/get-objects/:mail', ...);
...
router.use('/roles', function(req, res, next) {...}); // This middleware logic won't execute when request is sent to '/roles/get-objects/some-email', as the request has already been handled and response is already sent to browser.


答:
Changing the scrollbar is never a good idea . There are solutions for changing the scrollbar with javascript or with just CSS ( for webkit browsers ), but i don't recommend it . Scrollbar is rendered by the browser and custom scrollbars with javascript never behave like a default browser one and might cause issues and also cross-browser incompatibilities .

You can find all sorts of scripts,plugins,codes for modifiying the scrollbar.

But anyway., here's an example of a custom scrollbar with only CSS ( webkit )

div {
height:1200px;
width:100%;
background:red;
}
::-webkit-scrollbar {
    width: 20px;
    height: 20px;
}
::-webkit-scrollbar-button {
    background: blue
}
::-webkit-scrollbar-track-piece {
    background: yellow
}
::-webkit-scrollbar-thumb {
    background: green
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
</div></code>```

Title: How to get fat scroll bar on div using CSS?

Body:
Changing the scrollbar is never a good idea . There are solutions for changing the scrollbar with javascript or with just CSS ( for webkit browsers ), but i don't recommend it . Scrollbar is rendered by the browser and custom scrollbars with javascript never behave like a default browser one and might cause issues and also cross-browser incompatibilities .

You can find all sorts of scripts,plugins,codes for modifiying the scrollbar.

But anyway., here's an example of a custom scrollbar with only CSS ( webkit )

div {
height:1200px;
width:100%;
background:red;
}
::-webkit-scrollbar {
    width: 20px;
    height: 20px;
}
::-webkit-scrollbar-button {
    background: blue
}
::-webkit-scrollbar-track-piece {
    background: yellow
}
::-webkit-scrollbar-thumb {
    background: green
}

<div>
</div>


问:
Build react-native to IOS
I have success to build a react-native application to an android signed apk. Now, Is that possible build (export) a react-native application to .ipa without using MAC? I'm using ubuntu linux btw</p>

答: To generate an .ipa you need a Mac or at least a VM with a MAC that has a developer account (something already bought if i'm not mistaken).

Title: Build react-native to IOS