问:
Intervention \ Image \ Exception \ NotReadableException using laravel 4
I'm using laravel 4 and I installed the Intervention Image package. When I'm using it in my code whith method ->resize, ->move etc etc etc... I have this error:

```<code>Intervention \ Image \ Exception \ NotReadableException
</code>```

Image source not readable

```<code>open: /Applications/MAMP/htdocs/myNameProject/vendor/intervention/image/src/Intervention/Image/AbstractSource.php

        break;

        case $this->isFilePath():
            return $this->initFromPath($this->data);
            break;

        default:
            throw new Exception\NotReadableException("Image source not readable");
            break;
    }
</code>```

I'm also using MAMP and Sublime Text 3 on MAC OS if it could help you.

This is my code in my controller:

```<code>public function upload() {

//***** UPLOAD FILE (on server it's an image but an Url in Database *****//

// get the input file
$file = Image::make('url_Avatar');

//set a register path to the uploaded file
$destinationPath = public_path().'upload/';

//have client extension loaded file and set a random name to the uploaded file, produce a random string of length 32 made up of alphanumeric characters [a-zA-z0-9]
$filename = $destinationPath . '' . str_random(32) . '.' . $file->getClientOriginalExtension();
//$file->move($destinationPath,$filename);

//set $file in order to resize the format and save as an url in database
$file= Image::make($image->getRealPath())->resize('200','200')->save('upload/'.$filename);

//*****VALIDATORS INPUTS and RULES*****
$inputs = Input::all();
$rules = array(
'pseudo' => 'required|between:1,64|unique:profile,pseudo',
//urlAvatar is an url in database but we register as an image on the server
'url_Avatar' => 'required|image|min:1',
);
</code>```

(I don't show you the redirect of my view, but it's worked fine for this section of my controller)

here is my form code (using blade laravel template):

```<code>@extends('layout.default')
@section('title')
Name Of My Project - EditProfile
@stop

@section('content')
{{Form::open(array('url'=>'uploadAvatar','files' => true))}}

<p>
{{Form::label('pseudo','pseudo (*): ')}}
{{Form::text('pseudo',Input::old('nom'))}}
</p>
@if ($errors->has('pseudo'))
<p class='error'> {{ $errors->first('pseudo')}}</p>
@endif
<br>
<br>

<p>
{{Form::label('url_Avatar','Avatar: ')}}
{{Form::file('url_Avatar',Input::old('Url_Avatar'))}}
</p>
@if ($errors->has('url_Avatar'))
<p class='error'> {{ $errors->first('url_Avatar')}}</p>
@endif
<br>
<br>

<p>
{{Form::submit('Validate your avatar')}}
</p>

{{Form::close()}}
@stop
</code>```

Of course I have installed Intervention Image package following the official website image.intervention.io/getting_started/installation (url).

How can I make my file "readable"? or resolve this error?

答:
I have the same problem. When I change image driver everything works fine.

Try to change image driver from app/config/packages/intervention/image/config.php from GD to Imagick

If you cant find config file try to run commands below:

Publish configuration in Laravel 5

$ php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"

Publish configuration in Laravel 4

$ php artisan config:publish intervention/image

Example content from config file:

```<code>return array(

    /*
    |--------------------------------------------------------------------------
    | Image Driver
    |--------------------------------------------------------------------------
    |
    | Intervention Image supports "GD Library" and "Imagick" to process images
    | internally. You may choose one of them according to your PHP
    | configuration. By default PHP's "GD Library" implementation is used.
    |
    | Supported: "gd", "imagick"
    |
    */

    'driver' => 'imagick'

);
</code>```

Body:
I'm using laravel 4 and I installed the Intervention Image package. When I'm using it in my code whith method ->resize, ->move etc etc etc... I have this error:

Intervention \ Image \ Exception \ NotReadableException

Image source not readable

open: /Applications/MAMP/htdocs/myNameProject/vendor/intervention/image/src/Intervention/Image/AbstractSource.php

        break;

        case $this->isFilePath():
            return $this->initFromPath($this->data);
            break;

        default:
            throw new Exception\NotReadableException("Image source not readable");
            break;
    }

I'm also using MAMP and Sublime Text 3 on MAC OS if it could help you.

This is my code in my controller:

public function upload() {

//***** UPLOAD FILE (on server it's an image but an Url in Database *****//

// get the input file
$file = Image::make('url_Avatar');

//set a register path to the uploaded file
$destinationPath = public_path().'upload/';

//have client extension loaded file and set a random name to the uploaded file, produce a random string of length 32 made up of alphanumeric characters [a-zA-z0-9]
$filename = $destinationPath . '' . str_random(32) . '.' . $file->getClientOriginalExtension();
//$file->move($destinationPath,$filename);

//set $file in order to resize the format and save as an url in database
$file= Image::make($image->getRealPath())->resize('200','200')->save('upload/'.$filename);

//*****VALIDATORS INPUTS and RULES*****
$inputs = Input::all();
$rules = array(
'pseudo' => 'required|between:1,64|unique:profile,pseudo',
//urlAvatar is an url in database but we register as an image on the server
'url_Avatar' => 'required|image|min:1',
);

(I don't show you the redirect of my view, but it's worked fine for this section of my controller)

here is my form code (using blade laravel template):

@extends('layout.default')
@section('title')
Name Of My Project - EditProfile
@stop

@section('content')
{{Form::open(array('url'=>'uploadAvatar','files' => true))}}

{{Form::label('pseudo','pseudo (*): ')}}
{{Form::text('pseudo',Input::old('nom'))}}

@if ($errors->has('pseudo'))

 {{ $errors->first('pseudo')}}

@endif

{{Form::label('url_Avatar','Avatar: ')}}
{{Form::file('url_Avatar',Input::old('Url_Avatar'))}}

@if ($errors->has('url_Avatar'))

 {{ $errors->first('url_Avatar')}}

@endif

{{Form::submit('Validate your avatar')}}

{{Form::close()}}
@stop

Of course I have installed Intervention Image package following the official website image.intervention.io/getting_started/installation (url).

How can I make my file "readable"? or resolve this error?

Body:
I have the same problem. When I change image driver everything works fine.

Try to change image driver from app/config/packages/intervention/image/config.php from GD to Imagick

If you cant find config file try to run commands below:

Publish configuration in Laravel 5

$ php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"

Publish configuration in Laravel 4

$ php artisan config:publish intervention/image

Example content from config file:

return array(

    /*
    |--------------------------------------------------------------------------
    | Image Driver
    |--------------------------------------------------------------------------
    |
    | Intervention Image supports "GD Library" and "Imagick" to process images
    | internally. You may choose one of them according to your PHP
    | configuration. By default PHP's "GD Library" implementation is used.
    |
    | Supported: "gd", "imagick"
    |
    */

    'driver' => 'imagick'

);


来源: stackexchange

问:
adding regular expression to js code
How can i add pattern="[0-9]+" to the div in this js code ?</p>

```<code>var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
    x++; //text box increment
    $(wrapper).append('<div class="delivery-num-input"><input type="text"  pattern="[0-9]+" class="form-control delivery_number_plus"/><a href="#" class="remove_field btn btn-sm btn-danger">Remove</a></div>'); //add input box
}
});
</code>```

答:
As it's said here. You can add programmatically the pattern to the input like this:</p>

```<code>var regex = /\d+/;
var element = wrapper.find('input');
element.setAttribute("pattern", regex.source);
</code>```

ContentLicense: CC BY-SA 3.0

Title: adding regular expression to js code

Body:
How can i add pattern="[0-9]+" to the div in this js code ?

var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
    x++; //text box increment
    $(wrapper).append('
<input type="text"  pattern="[0-9]+" class="form-control delivery_number_plus"/>Remove
'); //add input box
}
});

Body:
As it's said here. You can add programmatically the pattern to the input like this:

var regex = /\d+/;
var element = wrapper.find('input');
element.setAttribute("pattern", regex.source);


问:
stackoverflow exception was unhandled
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

```<code>        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }
</code>```

答:
you are getting "StackoverFlow" for the Recursive call. its better to mold the holes found in the code. I suggest you to change the logic.

static int callStack = 0;

```<code>    public double bigzarb(long u, long v)
    {
        callStack++;
         ............
         ............
</code>```

ContentLicense: CC BY-SA 2.5

Title: stackoverflow exception was unhandled

Body:
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }

Body:
you are getting "StackoverFlow" for the Recursive call. its better to mold the holes found in the code. I suggest you to change the logic.

static int callStack = 0;

    public double bigzarb(long u, long v)
    {
        callStack++;
         ............
         ............


问:
Magic quotes in PHP
According to the PHP manual, in order to make code more portable, they recommend using something like the following for escaping data:

```<code>if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}
</code>```

I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().

答:
Prepared statements of PDO and Mysqli are the better way to prevent SQL injection.

But if you are migrating a legacy code which is base on Magic Quotes for every SQL queries, you can refer yidas/php-magic-quotes for implementing Magic Quotes on the environment with PHP 5.4 above version.

https://github.com/yidas/php-magic-quotes

OwnerDisplayName: VirtuosiMedia

Title: Magic quotes in PHP

Body:
According to the PHP manual, in order to make code more portable, they recommend using something like the following for escaping data:

if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}

I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().

LastEditorDisplayName: VirtuosiMedia


问:
Implement a node transformer in arpeggio
I'm trying to implement a Node Transformer class in the Arpeggio PEG parser. However there's no support to copy nodes for modification (deep copy doesn't work on nodes for instance). The main goal is to implement preprocessing and syntactic sugar in a small programming language.

Any hints on how to do this are welcome

Thanks!

答:
The idiomatic approach to implement tree transformations in Arpeggio is by using visitors.

In Arpeggio a visitor pattern is used for semantic analysis. You write a python class that inherits PTNodeVisitor and has a methods of the form visit_(self, node, children) where rule name is a rule name from the grammar.

During a semantic analysis a parse tree is walked in the depth-first manner and for each node a proper visitor method is called to transform it to some other form. The results are than fed to the parent node visitor method. This is repeated until the final, top level parse tree node is processed (its visitor is called). The result of the top level node is the final output of the semantic analysis.

Edit: Do not edit PT nodes. Create your objects instead. This will require you to design your language AST model (meta-model) first and than instantiate elements of this model during tree node visiting.

For a complex transformations of parse trees you can investigate textX source code.

If you are developing a small language I highly recommend you to take a closer look at textX. It is much easier to use in comparison to classical parsing technologies.


问:
pythonic way for implementing interface for modules
I have a group of functions that define me an desired behavior (interface).

This group can be wrapped in a class, so I can "enforce" the desired behavior I want (raising not implemented errors).

But on the other hand, it is not very pythonic, and the class would be just a class with a bunch of static methods.

So if I use modules with functions, I can't enforce the module to implement all desired functions.

Any ideas how to enforce a module to implement all functions I want, without wrapping it in a class?

Thanks in advance!

答:
One solution is for your factory to have a method for "registering" an implementation and another method for "getting" a specific implementation.  A valid implementation would be an object having the required method names.

```<code>class MyFactory:
    def register(self, name, implementation):
        # check implementation somehow and raise an Exception if it's not valid
        # insure implementation has all required function names and they are callable

    def get_implementation(self, name):
        # returns a previously registered implementation
</code>```

The only thing you really accomplish here is that an invalid implementation will throw an exception when you register it, instead of throwing an exception when you use it.  Whether this sort of thing is worth the effort is questionable.  There are an infinite number of ways an implementation can fail to work properly when you use it, and registering can only catch the most obvious of them (missing function names).

Body:
One solution is for your factory to have a method for "registering" an implementation and another method for "getting" a specific implementation.  A valid implementation would be an object having the required method names.

class MyFactory:
    def register(self, name, implementation):
        # check implementation somehow and raise an Exception if it's not valid
        # insure implementation has all required function names and they are callable

    def get_implementation(self, name):
        # returns a previously registered implementation

The only thing you really accomplish here is that an invalid implementation will throw an exception when you register it, instead of throwing an exception when you use it.  Whether this sort of thing is worth the effort is questionable.  There are an infinite number of ways an implementation can fail to work properly when you use it, and registering can only catch the most obvious of them (missing function names).


问:
Triggering a remote job and blocking the actual job while the remote job is being built is not working in Jenkins
I have a Jenkins job that triggers a remote parameterized job. I have checked the box next to the Block until the remote triggered projects finish their builds.
option. Sometimes it works just fine, but occasionally the first job is not being blocked while the triggered remote job is being built.

Check the following snippet from the log:

16:07:00 Blocking local job until remote job completes

16:07:00 Remote build started!

16:07:00 Remote build finished with status SUCCESS.

It seems that the remote job finished succesfully in only 1 sec, but actually, the remote job has an approx. 10 minutes long build time and I checked that it is started correctly and was still running when the calling job logged this and went on.

Any idea on what is wrong with the blocking?

答:
I think that what is finishing in 1 sec is just the queuing and firing up of the remote job. Not sure if that's intended or a bug (you might want to ask this on plugin's JIRA page).
It seems though you need to block your parent job yourself until the remote job has actually finished. You might be able to work a polling scheme (say check status every 10 secs or so) based on the env vars that are available when you use the Block until... option. Especially TRIGGERED_BUILD_RESULT_<project name> (see here https://wiki.jenkins.io/display/JENKINS/Parameterized+Trigger+Plugin)


问:
Subset df on string condition
I want to subset df on an unknown condition (say, randomly defined as in the example below):

```<code>df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))
</code>```

I can do this with eval, which, vox populi, is suboptimal:

```<code>subset(df, eval(parse(text=condition)))
</code>```

Is there an alternative to eval(parse)?

答:
An alternative to the base subset is the filter function from dplyr:

```<code>df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))

library(dplyr)
df %>% filter(eval(parse(text=condition))
</code>```

Title: Subset df on string condition

Body:
I want to subset df on an unknown condition (say, randomly defined as in the example below):

df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))

I can do this with eval, which, vox populi, is suboptimal:

subset(df, eval(parse(text=condition)))

Is there an alternative to eval(parse)?

Body:
An alternative to the base subset is the filter function from dplyr:

df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))

library(dplyr)
df %>% filter(eval(parse(text=condition))


问:
How to set button style in android
Normal button looks like:

Now, please let me know, How can i make a simple button same as an attached image button (i.e. button corner shape is round and also there is no gap between two buttons)

答:
You can also use ImageView in your xml file and than give onClickable and onFocusable true and then create onClick event method on backend code and give the name of the method on xml , so that instead of dealing with all shape or button issues you just put the imageview there and make it act like a button.Here is sample code for you

```<code><ImageView
            android:id="@+id/test"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:onClick="testClickEvent"
            android:paddingRight="8dip"
            android:paddingBottom="8dip"
            android:src="@drawable/testImg"/>
</code>```

As I said on backend side create method with sign like this and this will do the job

```<code>public void testClickEvent(View v){}
</code>```

Then implement what you wanna do in this method

ContentLicense: CC BY-SA 4.0

Title: How to set button style in android

Body:
You can also use ImageView in your xml file and than give onClickable and onFocusable true and then create onClick event method on backend code and give the name of the method on xml , so that instead of dealing with all shape or button issues you just put the imageview there and make it act like a button.Here is sample code for you

<ImageView
            android:id="@+id/test"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:onClick="testClickEvent"
            android:paddingRight="8dip"
            android:paddingBottom="8dip"
            android:src="@drawable/testImg"/>

As I said on backend side create method with sign like this and this will do the job

public void testClickEvent(View v){}

Then implement what you wanna do in this method


问:
bootstrap site looks different localhost than server side - css not applying?
I noticed that while working in visual studio (2013) on a site using bootstrap (3) when previewing changes (localhost iisexpress) everything looks normal/as expected - specifically rounded edges, horizontal lines in menus, and font smoothing.

However, after publishing (file system), those elements disappear. The corners are hard, the lines in the menus are gone (and replaced with big space) , and the fonts don't seem to be smoothed.

both times I'm viewing/previewing in IE 11

The server is 2008 R2, IIS is 7 with .net 4.5 installed

Is there something I need installed on the server to make css3 work?

((I'd post an image, but I don't have enough rep, hopefully the link will work))

link to flickr image

update Sorry, I should've posted that I did notice , via inspector, that when running under localhost the style is properly identified as 'boostrap.css', however the server side version shows 'css (1)'
I also see that the serverside version has the very same elements underlined (red squiggle line) whereas the localhost version doesn't.

OH!!! I started poking around in the other tabs of the inspector .. and notice that serverside document mode was set to '7 (Default)' - localhost (as launched by visual studio) is set to 'Edge' -- I changed it on my browser, and it all looks perfect. SOOOOOOooooo is there a way to force the rendering? or is it a client/browser setting?

答:
In my case the problem is caused by browser cache memory.
there was already a folder on server like 'localhost/project',
I deleted that and uploaded another project with same name.
both projects have 'css/style.css' file.

When I press the refresh button, browser only refreshed index.php but not css/syle.css

So I browse to 'localhost/project/css/style.css' and refreshing did the job...


问:
Why do I get message: "Unhandled event loop exception Java heap space" in Eclipse when using javascript autocomplete?
When I try to use any javascript template Eclipse always hangs and I get this message:
"Unhandled event loop exception Java heap space" on a popup.

I started a top command (using Ubuntu) for the Eclipse process and for Java process and then tried to use an auto-complete on Eclipse. I notice that the Java process takes my CPU to 100% while memory stays the same(arround 22%).

I got this without any prior changes to my Eclipse IDE...

Any ideas on how to solve this?

EDIT:
I notice also that on the preferences window under:
Javascript / Content Assist / Advanced
the option "Other Javascript Proposals" is checked. When unchecked, the problem is solved. However, it lacks the content assist for variables and objects. So this partially solves my problem.

答:
you can change add below commands to AIDE.ini file and restart the IDE.</p>

```<code>-vmargs
-Dosgi.requiredJavaVersion=1.6
-Dlocaldev=true
-Xms256m
-Xmx512m
-XX:PermSize=128m
-XX:MaxPermSize=256m
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
</code>```

Body:
you can change add below commands to AIDE.ini file and restart the IDE.

-vmargs
-Dosgi.requiredJavaVersion=1.6
-Dlocaldev=true
-Xms256m
-Xmx512m
-XX:PermSize=128m
-XX:MaxPermSize=256m
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005


问:
C# Winform Storing and Passing Variables?
So for 99% of my learning of C# it has been with console applications, now I'd like to try simple GUI i.e win form apps. But I have no idea on how to get the input from a text box, store it as an int or double and pass it to a method that will just do a simple task like converting it into pounds (lb).
Sorry for such a noob question but how do I do this? I know how to make the method just not how to get input and pass variables from a textbox...</p>

答:
A textbox object has an "Text"-Attribute. A simple solution is (without any exception-handling):</p>

```<code>string tmp = myTextbox.Text;
int val1 = int.Parse(tmp);
double val2 = Double.Parse(tmp);
</code>```

Body:
A textbox object has an "Text"-Attribute. A simple solution is (without any exception-handling):

string tmp = myTextbox.Text;
int val1 = int.Parse(tmp);
double val2 = Double.Parse(tmp);


问:
Identify empty string in Perl
There is probably an easy solution to this, but I can't figure it out. I am looking to:

take a CSV file into an array

loop through the array and split fields into variables

if the array field is empty then set the variable to "N/A"

Note: It is only setting the $variable to "N/A" that I cannot get working.

For example:

```<code>foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);

}
</code>```

How would I set $date to "N/A" if the field in the array is empty?

so to produce:

```<code>$name = Jim
$date = N/A
$size = small
</code>```

I hope this makes sense and is easy to fix.
-Thanks

答:
What will be the input like if date is missing? If the input is: somename,200 (where 200 is size), then date would be set as 200 right?

If the input is like this
somename,,200

where 200 is size, and because date is unavailable it is set to empty. Then you can do a simple if-check:

```<code>if($date eq '')
{
  $date = "NA";
}
</code>```

Note $date will be defined, it will be just set to empty

Title: Identify empty string in Perl

Body:
There is probably an easy solution to this, but I can't figure it out. I am looking to:

take a CSV file into an array

loop through the array and split fields into variables

if the array field is empty then set the variable to "N/A"

Note: It is only setting the $variable to "N/A" that I cannot get working.

For example:

foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);

}

How would I set $date to "N/A" if the field in the array is empty?

so to produce:

$name = Jim
$date = N/A
$size = small

I hope this makes sense and is easy to fix.
-Thanks

Body:
What will be the input like if date is missing? If the input is: somename,200 (where 200 is size), then date would be set as 200 right?

If the input is like this
somename,,200

where 200 is size, and because date is unavailable it is set to empty. Then you can do a simple if-check:

if($date eq '')
{
  $date = "NA";
}

Note $date will be defined, it will be just set to empty


问:
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.

答:
if parameter expansion inside another parameter expansion is supported, you can use this:

```<code>$ s='98.254.237.114.broad.lyg.js.dynamic.163data.com.cn'
$ # removing last three fields
$ echo "${s%.*.*.*}"
98.254.237.114.broad.lyg.js.dynamic
$ # pass output of ${s%.*.*.*} plus the extra . to be removed
$ echo "${s#${s%.*.*.*}.}"
163data.com.cn
</code>```

can also reverse the line, get required fields and then reverse again.. this makes it easier to use change numbers

```<code>$ echo "$s" | rev | cut -d. -f1-3 | rev
163data.com.cn
$ echo "$s" | rev | cut -d. -f1-4 | rev
dynamic.163data.com.cn

$ # and easy to use with file input
$ cat ip.txt
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
foo.bar.123.baz.xyz
a.b.c.d.e.f
$ rev ip.txt | cut -d. -f1-3 | rev
163data.com.cn
123.baz.xyz
d.e.f
</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:
if parameter expansion inside another parameter expansion is supported, you can use this:

$ s='98.254.237.114.broad.lyg.js.dynamic.163data.com.cn'
$ # removing last three fields
$ echo "${s%.*.*.*}"
98.254.237.114.broad.lyg.js.dynamic
$ # pass output of ${s%.*.*.*} plus the extra . to be removed
$ echo "${s#${s%.*.*.*}.}"
163data.com.cn

can also reverse the line, get required fields and then reverse again.. this makes it easier to use change numbers

$ echo "$s" | rev | cut -d. -f1-3 | rev
163data.com.cn
$ echo "$s" | rev | cut -d. -f1-4 | rev
dynamic.163data.com.cn

$ # and easy to use with file input
$ cat ip.txt
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
foo.bar.123.baz.xyz
a.b.c.d.e.f
$ rev ip.txt | cut -d. -f1-3 | rev
163data.com.cn
123.baz.xyz
d.e.f


问:
How to change default_controller URI Routing in Codeigniter?
I want to change default controller URI Routing Codeigniter to this here is my code :

from->

```<code>$route['default_controller'] = 'home';
</code>```

to->

```<code>$route['default_controller'] = 'Home_controller/home';
</code>```

with this I have store class Home_controller in folder controller/public

thank for your help !!!

答:
I don't really know and understand why you use the folder public inside the folder of controllers and i strongly disagree with that if you don't know the purpose of this.

In this case you should change your base_url in application/config/config.php to:

```<code>$config['base_url'] = 'http://YOUR_DOMAIN/public/';
</code>```

Otherwise, try to set your route as:

```<code>$route['default_controller'] = 'public/Home_controller/home';
</code>```

If you definitely need the public folder inside controllers, because you have another folder inside controllers, comment me and i will suggest you another generic solution.

Body:
I want to change default controller URI Routing Codeigniter to this here is my code :

from->

$route['default_controller'] = 'home';

to->

$route['default_controller'] = 'Home_controller/home';

with this I have store class Home_controller in folder controller/public

thank for your help !!!

Body:
I don't really know and understand why you use the folder public inside the folder of controllers and i strongly disagree with that if you don't know the purpose of this.

In this case you should change your base_url in application/config/config.php to:

$config['base_url'] = 'http://YOUR_DOMAIN/public/';

Otherwise, try to set your route as:

$route['default_controller'] = 'public/Home_controller/home';

If you definitely need the public folder inside controllers, because you have another folder inside controllers, comment me and i will suggest you another generic solution.


问:
Adding delay or something between hundred of promises
I'm using node for requesting app details from another website but the problem i'm facing is, it sends hundreds ( or maybe thousands ) of request, and then I get error and I receive nothing.

Read comments in code for info...

```<code>// I'm reading links from another file using 'fs'
fs.readFile('./google_apps/GAME_ACTION.json', 'utf8', function (err, data) {
    if (err) throw err;

    obj = JSON.parse(data);
    // creating a empty array
    var promiseStack = [];

    for (var index in obj['GAME_ACTION']) {
        var linksArray = obj['GAME_ACTION'][index];
        linksArray.forEach( function(link, index) {
            var appID = link.match(/id=.*/g)
            var instr = appID.toString();

            var appIDSliced = instr.slice(3)
            // Here appIDSliced is ID, which is sliced from a link
            // there are thousands on link in this file which I opened

            console.log('sending') // for testing purpose

            // here i'm pushing promises into that empty array
            // store.app({id: appIDSliced}) is a promise I guess because I can use .then() on it...
            // and store.app sends request to another website from which it receives an object in return.
            // (Variable store is from another file 'require()' above in my node app fie )
            promiseStack.push( store.app({id: appIDSliced}))

        });
    }

    // After pushing all promises into array, now i'm trying to resolve them using Promise.all
    Promise.all(promiseStack).then((responses) => {
        console.log("Dealing with responses")

        // Dealing with response (which is an object coming)
        responses.map(response => {
            var title = response.title
            var package_name = response.appId
            var appCategory = response.primaryGenre
            var appSize = parseFloat((response.size/1024)/1024).toFixed(2)
            var developerName = response.developer
            var developerWebsite = response.developerWebsite
            if (typeof developerWebsite == 'undefined') {
                developerWebsite = "N/A"
            }
            var appPrice = response.price
            var lastUpdated = response.updated
            var contentRating = response.contentRating
            if (typeof contentRating == 'undefined') {
                contentRating = "N/A"
            }
            var userRating = response.score
            if (typeof userRating == 'undefined') {
                userRating = "N/A"
            }
            var dataRow = [appID, title, package_name, appCategory, appSize, developerName, developerWebsite, appPrice, lastUpdated, contentRating, userRating]
            var dataToAdd = [dataRow];
            console.log("Appending now")

            // here i'm using google API to append that into my sheet on google
            authentication.authenticate().then((auth)=>{
                appendData(auth, dataToAdd);
            });
        })
    })
})
</code>```

See the image below ... Those are the Errors I receive on my console
It keep logging 'sending' like for 80 secs and then I get error "UnhandledPromiseRejectionWarning" where I just get stuck for 2 mins and I keep pressing 'CTRL+C'.

Thanks.

答:
In for loop when you are pushing store.app({id: appIDSliced}) & I guess it starts requesting the server thus in a burst mode.
Promise.all is resolving requests which is getting stuck.

Why not run n numbers at a time and make them follow till all server requests get completed. This way there will be delay between most of the requests as at any point of time there will be max 5 request will be running instead of burst execution.

var functions = [];
var m;
for (var i = 0; i < 100; i++) {
  (function(j) {
    functions.push(function(callback) {
      var random = Math.floor(Math.random() * 10000) + 1;
      var s = document.getElementById('here');
      var d = document.createElement('div');
      d.innerHTML = 'function : ' + j + ' executed after :' + random;
      s.appendChild(d);
      setTimeout(callback, random);
      // the above code executes something like xhr. remove it
      // here you can write your own statements
      // store.app({id: appIDSliced}, (err, response) => {
      //     responses.map(response => {
      //         var title = response.title
      //         {...}
      //         here i'm using google API to append that into my sheet on google
      //         authentication.authenticate().then((auth)=>{
      //            appendData(auth, dataToAdd);
      //         });
      //     });
      //     callback(); // you can add callback here after all your statements execution
      // });
    });
  })(i);
}

function exec(method) {
  // here method will call the below function which is in your case promise.
  // function(callback) {
  //     console.log(j);
  //     callback();
  // }
  method(function() {
    if (functions.length > m) {
      exec(functions[m]);
      m++;
    }
  });
}

// lets start only 5 at a time.
// first to complete next to start
// function number:    1      2     3     4     5
// completes :        2nd    3rd   1st   5th   4th
// start new :         7      8     6     10    9
setTimeout(function() {
  for (m = 0; m < 5; m++) {
    (function(m) {
      exec(functions[m]); // this will execute 1,2,3,4,5 function
      m++;
    })(m);
  }
}, 0);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="here"></div></code>```

Body:
I'm using node for requesting app details from another website but the problem i'm facing is, it sends hundreds ( or maybe thousands ) of request, and then I get error and I receive nothing.

Read comments in code for info...

// I'm reading links from another file using 'fs'
fs.readFile('./google_apps/GAME_ACTION.json', 'utf8', function (err, data) {
    if (err) throw err;

    obj = JSON.parse(data);
    // creating a empty array
    var promiseStack = [];

    for (var index in obj['GAME_ACTION']) {
        var linksArray = obj['GAME_ACTION'][index];
        linksArray.forEach( function(link, index) {
            var appID = link.match(/id=.*/g)
            var instr = appID.toString();

            var appIDSliced = instr.slice(3)
            // Here appIDSliced is ID, which is sliced from a link
            // there are thousands on link in this file which I opened

            console.log('sending') // for testing purpose

            // here i'm pushing promises into that empty array
            // store.app({id: appIDSliced}) is a promise I guess because I can use .then() on it...
            // and store.app sends request to another website from which it receives an object in return.
            // (Variable store is from another file 'require()' above in my node app fie )
            promiseStack.push( store.app({id: appIDSliced}))

        });
    }

    // After pushing all promises into array, now i'm trying to resolve them using Promise.all
    Promise.all(promiseStack).then((responses) => {
        console.log("Dealing with responses")

        // Dealing with response (which is an object coming)
        responses.map(response => {
            var title = response.title
            var package_name = response.appId
            var appCategory = response.primaryGenre
            var appSize = parseFloat((response.size/1024)/1024).toFixed(2)
            var developerName = response.developer
            var developerWebsite = response.developerWebsite
            if (typeof developerWebsite == 'undefined') {
                developerWebsite = "N/A"
            }
            var appPrice = response.price
            var lastUpdated = response.updated
            var contentRating = response.contentRating
            if (typeof contentRating == 'undefined') {
                contentRating = "N/A"
            }
            var userRating = response.score
            if (typeof userRating == 'undefined') {
                userRating = "N/A"
            }
            var dataRow = [appID, title, package_name, appCategory, appSize, developerName, developerWebsite, appPrice, lastUpdated, contentRating, userRating]
            var dataToAdd = [dataRow];
            console.log("Appending now")

            // here i'm using google API to append that into my sheet on google
            authentication.authenticate().then((auth)=>{
                appendData(auth, dataToAdd);
            });
        })
    })
})

See the image below ... Those are the Errors I receive on my console
It keep logging 'sending' like for 80 secs and then I get error "UnhandledPromiseRejectionWarning" where I just get stuck for 2 mins and I keep pressing 'CTRL+C'.

Thanks.

Body:
In for loop when you are pushing store.app({id: appIDSliced}) & I guess it starts requesting the server thus in a burst mode.
Promise.all is resolving requests which is getting stuck.

Why not run n numbers at a time and make them follow till all server requests get completed. This way there will be delay between most of the requests as at any point of time there will be max 5 request will be running instead of burst execution.

var functions = [];
var m;
for (var i = 0; i < 100; i++) {
  (function(j) {
    functions.push(function(callback) {
      var random = Math.floor(Math.random() * 10000) + 1;
      var s = document.getElementById('here');
      var d = document.createElement('div');
      d.innerHTML = 'function : ' + j + ' executed after :' + random;
      s.appendChild(d);
      setTimeout(callback, random);
      // the above code executes something like xhr. remove it
      // here you can write your own statements
      // store.app({id: appIDSliced}, (err, response) => {
      //     responses.map(response => {
      //         var title = response.title
      //         {...}
      //         here i'm using google API to append that into my sheet on google
      //         authentication.authenticate().then((auth)=>{
      //            appendData(auth, dataToAdd);
      //         });
      //     });
      //     callback(); // you can add callback here after all your statements execution
      // });
    });
  })(i);
}

function exec(method) {
  // here method will call the below function which is in your case promise.
  // function(callback) {
  //     console.log(j);
  //     callback();
  // }
  method(function() {
    if (functions.length > m) {
      exec(functions[m]);
      m++;
    }
  });
}

// lets start only 5 at a time.
// first to complete next to start
// function number:    1      2     3     4     5
// completes :        2nd    3rd   1st   5th   4th
// start new :         7      8     6     10    9
setTimeout(function() {
  for (m = 0; m < 5; m++) {
    (function(m) {
      exec(functions[m]); // this will execute 1,2,3,4,5 function
      m++;
    })(m);
  }
}, 0);

<div id="here"></div>


问:
Where to call ASP.Net HTTP2 PushPromise
We're migrating our ASP.Net (4.6) Web Forms website to a shiny new 2016 Server and as part of that we're keen to make the most out of the new HTTP2 possibilities. Part of that is using Server Push to get css and js files to the client as quickly as possible. However, having found basically zero documentation around this online (please correct me if I'm wrong) I'm struggling to check the best place to call the HttpResponse.PushPromise() method.

On a standard page I'm assuming this would just sit in Page_Load()? However, most pages in this project actually derive from a BasePage class rather than from System.Web.UI.Page (basically just to provide common methods and custom properties) so what's the best-practice case here. Should we override Page_Load?
 Or call PushPromise() from somewhere else in the application?

Any assistance gratefully received. I know HTTP2 is fairly new, but I've found the lack of documentation/support/examples from Microsoft on this to be really poor.

Many thanks!

答:
Just to give an update on this: we initially tried to put PushPromise in the Page_Load() event of our BasePage class but we ran into some problems. We're not 100% sure it was this but the IIS worker process was crashing frequently after implementing it. There were a few other minor code changes at the same time and we rolled the whole lot back, but users with Chrome were also intermittently reporting ERR_SPDY_PROTOCOL_ERROR which would also seem to indicate this was the problem.

We're instead going to try and implement it in an HttpModule at Application_BeginRequest() so we'll see if that is more reliable.

Title: Where to call ASP.Net HTTP2 PushPromise


问:
problem with INIT=RUNSCRIPT and relative paths
I use maven conventions for source paths (src/main src/test) and i have my sql scripts in src/main/resources/scripts.

I want to run my app with H2 memory and i'd like to use the jdbc url to initialize my db :

```<code>database.url=jdbc:h2:mem:;INIT=RUNSCRIPT FROM 'src/main/resources/scripts/create.sql';
</code>```

My problem is that this relative path (src/main/... ) does not work, and that H2 won't crash if the init=runscript command targets nothing.

Does someone know what is the path i should use to make this work ?

Thanks

答:
I'd suggest trying to use an absolute path for starters, just to check everything works. Afterwards, check your classpath. For example, bin/main/resources/scripts/create.sql, assuming bin is where your classes are compiled, and is on your classpath.

Since src, where your source lives, usually isn't on the classpath, this could be the source of your problem.

Body:
I use maven conventions for source paths (src/main src/test) and i have my sql scripts in src/main/resources/scripts.

I want to run my app with H2 memory and i'd like to use the jdbc url to initialize my db :

database.url=jdbc:h2:mem:;INIT=RUNSCRIPT FROM 'src/main/resources/scripts/create.sql';

My problem is that this relative path (src/main/... ) does not work, and that H2 won't crash if the init=runscript command targets nothing.

Does someone know what is the path i should use to make this work ?

Thanks


问:
Uninstalling easy_install, pip, pip3, virtualenv and virtualenvwrapper
I'm struggling to see how all of these components are connected, - what installs what and so on. My installation is a mess. Several installations of Python (and I don't know which one is the native one - and which one can be removed). When I create a new virtualenv (mkvirtualenv venv) and activate it. If I then write pip3 install django, then it gives me the error: Could not find an activated virtualenv (required). Which tells me, that the virtualenvs are pointing to Python2.7 (instead of Python3), and pip (instead of pip3).

I've just had it with all this crap. How do I remove all that I can possibly remove, so I can start fresh? I want to install all version of:

pip

pip3

easy_install

python (all other installations than the native ones)

virtualenv

virtualenvwrapper

I have Homebrew installed - and my plan is to install most/all of it again afterwards properly using Homebrew. And how can I see, if the current program is installed using Homebrew?

答:
To see, if you have installed python with brew do:

```<code>brew info python
</code>```

and

```<code>brew info python3
</code>```

To see which python installation is used do:

```<code>which python
</code>```

and

```<code>which python3
</code>```

Original macos python binaries are in /usr/bin/, homebrew python binaries are in /usr/local/bin/. You can also use the which command on pip, pip3, easy_install, virtualenv and virtualenvwrapper.

Body:
To see, if you have installed python with brew do:

brew info python

and

brew info python3

To see which python installation is used do:

which python

and

which python3

Original macos python binaries are in /usr/bin/, homebrew python binaries are in /usr/local/bin/. You can also use the which command on pip, pip3, easy_install, virtualenv and virtualenvwrapper.


问:
How can I execute multiple SQL commands using c#
I was trying to use this code two run two commands in one connection, which I couldn't do, here is my code:

```<code>using (SqlConnection connection = new SqlConnection(""))
{
    string query = "SELECT DISTINCT quatro, tres FROM todos_cp ORDER BY quatro, tres ";

    using (SqlCommand RetriveCommand = new SqlCommand(query, conn))
    {
        conn.Open();
        SqlDataReader reader = RetriveCommand.ExecuteReader();

        while (reader.Read())
        {
            string coluna = reader.GetString(reader.GetOrdinal("quatro"));
            string coluna1 = reader.GetString(reader.GetOrdinal("tres"));

            Boolean ElementDisplayed;

            try
            {
            }
            catch (NoSuchElementException i)
            {
                ElementDisplayed = false;
                GDataPicker();
                for (int x = 0; x < dataGridView1.Rows.Count; x++)
                {
                    string query2 = @"INSERT INTO table_teste1(Rua, CodigoPostal, Distrito, Concelho, Freguesia, GPS) VALUES(" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";

                    for (int x = 0; x < dataGridView1.Rows.Count; x++)
                        {
                            string query2 = @"INSERT INTO table_teste1 (Rua, CodigoPostal,Distrito,Concelho,Freguesia,GPS ) VALUES (" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";

                            using(SqlCommand InsertCommand = new SqlCommand(query2,connection))
                            {

                                InsertCommand.CommandText = query2;
                                InsertCommand.ExecuteNonQuery();

                            }
                        }
                }
            }
        }
        conn.Close();
    }
}
</code>```

My problem is most likely in the lines where I do:

```<code>InsertCommand.CommandText = query2;
InsertCommand.ExecuteNonQuery();
</code>```

And says i already have one datareader.

Help would be really appreciated, thanks in advance!

答: Append you second command in "query2". As it is inline query Sql will consider that as two different query (Append after semicolon) and will execute in the same connection</p>

Body:
I was trying to use this code two run two commands in one connection, which I couldn't do, here is my code:

using (SqlConnection connection = new SqlConnection(""))
{
    string query = "SELECT DISTINCT quatro, tres FROM todos_cp ORDER BY quatro, tres ";

    using (SqlCommand RetriveCommand = new SqlCommand(query, conn))
    {
        conn.Open();
        SqlDataReader reader = RetriveCommand.ExecuteReader();

        while (reader.Read())
        {
            string coluna = reader.GetString(reader.GetOrdinal("quatro"));
            string coluna1 = reader.GetString(reader.GetOrdinal("tres"));

            Boolean ElementDisplayed;

            try
            {
            }
            catch (NoSuchElementException i)
            {
                ElementDisplayed = false;
                GDataPicker();
                for (int x = 0; x < dataGridView1.Rows.Count; x++)
                {
                    string query2 = @"INSERT INTO table_teste1(Rua, CodigoPostal, Distrito, Concelho, Freguesia, GPS) VALUES(" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";

                    for (int x = 0; x < dataGridView1.Rows.Count; x++)
                        {
                            string query2 = @"INSERT INTO table_teste1 (Rua, CodigoPostal,Distrito,Concelho,Freguesia,GPS ) VALUES (" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";

                            using(SqlCommand InsertCommand = new SqlCommand(query2,connection))
                            {

                                InsertCommand.CommandText = query2;
                                InsertCommand.ExecuteNonQuery();

                            }
                        }
                }
            }
        }
        conn.Close();
    }
}

My problem is most likely in the lines where I do:

InsertCommand.CommandText = query2;
InsertCommand.ExecuteNonQuery();

And says i already have one datareader.

Help would be really appreciated, thanks in advance!


问:
Generic Type to be of class type only in java
C# code:

```<code>public class XYZ<T> where T : class, new()
</code>```

In .net you can force the generic to be of class type using the above syntex.

My Question is that how we can achieve the same using Java?

答:
Java does not have this special case. Typically you would do the standard thing of using an Abstract Factory.

Constraining the type to have a particular constructor is a static issue, and therefore erasure/reification is not necessary to implement it.

Body:
C# code:

public class XYZ<T> where T : class, new()

In .net you can force the generic to be of class type using the above syntex.

My Question is that how we can achieve the same using Java?


问:
chart.js number of labels equal to number of datapoints
This is probably a really easy question but I just started using javascript a couple of weeks ago and haven't really gotten a good hang of it yet.

I am generating a line chart using chart.js and the array containing the datasets data has a variable length depending on users input.
I can't get the number of labels to equal the number of data points, so if the array has a lenght of 10, it only has 10 point on the chart instead of 15 or whatever number I hardcodeded into the "labels:" attribute

```<code>var count = dataArray.length;
var labelnames = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th"];
</code>```

So here if dataArray has length of 10 I would want a string with 10 labels like this one:

```<code>var labelsOnChart =  ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"];
</code>```

To place on my chart.

答:
Interesting question. Moreover interesting library 'Chart.js'. Even i am also working on same from past 2 months.

Solution

For this you need to create a predefined array which will be global.

```<code>var labelnames = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", .....];
</code>```

When ever you want your chart specific dataarrayset then do following

```<code>var count = dataArray.length;
var requiredLabels = labelnames .slice(0,count);
</code>```

Hope this will solve your problem!!

Body:
This is probably a really easy question but I just started using javascript a couple of weeks ago and haven't really gotten a good hang of it yet.

I am generating a line chart using chart.js and the array containing the datasets data has a variable length depending on users input.
I can't get the number of labels to equal the number of data points, so if the array has a lenght of 10, it only has 10 point on the chart instead of 15 or whatever number I hardcodeded into the "labels:" attribute

var count = dataArray.length;
var labelnames = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th"];

So here if dataArray has length of 10 I would want a string with 10 labels like this one:

var labelsOnChart =  ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"];

To place on my chart.

Body:
Interesting question. Moreover interesting library 'Chart.js'. Even i am also working on same from past 2 months.

Solution

For this you need to create a predefined array which will be global.

var labelnames = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", .....];

When ever you want your chart specific dataarrayset then do following

var count = dataArray.length;
var requiredLabels = labelnames .slice(0,count);

Hope this will solve your problem!!


问:
Should I commit yarn.lock and package-lock.json files?
We're using yarn for all our deterministic pkg installations but don't prevent the user from using npm - I'm guessing having both these files will cause issues however. Should one be added to your .gitignore dir?</p>

答:
I was thinking about the same question. Here are my thoughts, hope it helps :

The npm package-lock.json documentation says the following :

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

This is great because it prevents the "works on my machine" effect.

Without this file, if you npm install --save A, npm will add "A": "^1.2.3" to your package.json. When somebody else runs npm install on your project, it is possible that the version 1.2.4 of A has been released. Since it is the latest available version that satisfies the semver range specified in your package.json, it will install this version. But what if there's a new bug introduced in this version ? This person will have a problem that you can't reproduce because you have the previous version, without any bug.

By fixing the state of your node_modules directory, package-lock.json file prevents this problem because everybody will have the same versions of every packages.

But, what if you're writing and publishing a npm module ? The documentation says the following :

One key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the toplevel package.

So, even if you commit it, when the user installs your module, he/she will not get the package-lock.json file, but only the package.json file. So npm will install the latest version that satisfies the semver ranges of all your dependencies. It means that you always want to test your module with theses verions of your dependencies, and not the one you installed when you started writing your module. So, in that case, package-lock.json is clearly useless. More, it can be annoying.


问:
JavaScript update field in another UserControl
I try to explain better. I have one user control in page, and inside this have UC2 (modal pop up). And I try to achieve this: When I close UC2(modal) i try to update some fields on UC1. And this works fine for one(I have UC2(modal) and on button Save OnClientClick="SaveInfoCI()"), and in UC1 on top of page

function SaveInfoCI() {
     document.getElementById("<%=frmData.FindControl("txtImplementingCI").ClientID%>").value
 = document.getElementById("<%=UC2.GetClientID%>").value;   }

but because i reuse this control in another place i want to update another field. Basically now i Have 3 JS function that update 3 fields. And I try when I click save in UC2(modal) I must execute one of this 3 javascript f, to update right field. I don't want to have 3 same UC with only difference in OnClientClick="SaveInfoCI().

答:
Two problems: first, your syntax is off, when inside code behind you can't use the <%= like this.

Second problem, by the time this script is executed (on top of the page) the elements still does not exist. You have to change the value in the client side page load event.

So this should work, though it's better done server side:

```<code>sb.Append("window.onload = function() { document.getElementById('" + frmData.FindControl("txtTextBox").ClientID + "').value = document.getElementById('" + MyUserControl.GetJs + "').value; };</")
</code>```

Also, you really don't need StringBuilder here.. use ordinary string instead.

Body:
Two problems: first, your syntax is off, when inside code behind you can't use the <%= like this.

Second problem, by the time this script is executed (on top of the page) the elements still does not exist. You have to change the value in the client side page load event.

So this should work, though it's better done server side:

sb.Append("window.onload = function() { document.getElementById('" + frmData.FindControl("txtTextBox").ClientID + "').value = document.getElementById('" + MyUserControl.GetJs + "').value; };</")

Also, you really don't need StringBuilder here.. use ordinary string instead.


问:
Markdown editor with tables
Is there any client-side markdown editor that could work with tables? I just need something like Stack Overflow's editor or markdownDeep -- both of those are great. But these editors doesn't let me customize tables, like Dreamweaver does it with HTML tables.</p>

答:
Typora is a very promising MarkDown editor : https://typora.io/

Tables support is very good for creation or edition, as long as many other features.

It is using GitHub Flavored Markdown ... which is good, but cannot produce CommonMark only for now.

Title: Markdown editor with tables


问:
How to extract a title of nodes in Network graph in Vis.js
I see this example at http://visjs.org/examples/network/events/interactionEvents.html.

I want to set up a onclick handler and I want to extract the title of the node (not limited to the ID such as 1, 2 and so on). I couldn't find a good example and I am wondering if anyone knows how?

Cheers,
K

答:
You might want to look at the following parts of the documentation:

select event: http://visjs.org/docs/network/#Events

dataSet.get(): http://visjs.org/docs/data/dataset.

```

    network.on('select', function(selection){
      let selectedNodeIds = selection.nodes; // array of selected node's ids
      let selectedNodes = nodes.get(selectedNodeIds); // retrive node objects from dataSet object
      let selectedNodesLabels = [];
      for( let i in selectedNodes ) {
        selectedNodesLabels.push(selectedNodes[i].label);
      }
    });

```

Body:
You might want to look at the following parts of the documentation:

select event: http://visjs.org/docs/network/#Events

dataSet.get(): http://visjs.org/docs/data/dataset.

    network.on('select', function(selection){
      let selectedNodeIds = selection.nodes; // array of selected node's ids
      let selectedNodes = nodes.get(selectedNodeIds); // retrive node objects from dataSet object
      let selectedNodesLabels = [];
      for( let i in selectedNodes ) {
        selectedNodesLabels.push(selectedNodes[i].label);
      }
    });


答:
E.g.</p>

```<code>SELECT DISTINCT DATE(a.startdatetime)
              , COALESCE(b.status,a.status) status
  FROM
     ( SELECT x.*
         FROM batch x
         JOIN
            ( SELECT id
                   , stepid
                   , DATE(startdatetime) dt
                   , MAX(startdatetime) max_dt
                FROM batch
               GROUP
                  BY id
                   , stepid
                   , dt
            ) y
           ON y.id = x.id
          AND y.stepid = x.stepid
          AND y.dt = DATE(x.startdatetime)
          AND y.max_dt = x.startdatetime
     ) a
  LEFT
  JOIN
     ( SELECT x.*
         FROM batch x
         JOIN
            ( SELECT id
                   , stepid
                   , DATE(startdatetime) dt
                   , MAX(startdatetime) max_dt
                FROM batch
               GROUP
                  BY id
                   , stepid
                   , dt
            ) y
           ON y.id = x.id
          AND y.stepid = x.stepid
          AND y.dt = DATE(x.startdatetime)
          AND y.max_dt = x.startdatetime
     ) b
    ON b.id = a.id
   AND DATE(b.startdatetime) = DATE(a.startdatetime)
   AND b.status = 'failed'
 WHERE a.status = 'success';
+-----------------------+---------+
| DATE(a.startdatetime) | status  |
+-----------------------+---------+
| 2017-06-21            | SUCCESS |
| 2017-06-22            | FAILED  |
| 2017-06-24            | FAILED  |
| 2017-06-23            | SUCCESS |
+-----------------------+---------+
</code>```

Title: How to get latest status from the table in Mysql

Body:
Below is the table description and insert scripts to load data into the table. I am working on Aurora Mysql database.

 DROP TABLE IF EXISTS batch;

 CREATE TABLE `Batch` (
      `ID` varchar(50) DEFAULT NULL,
      `StepID` varchar(50) DEFAULT NULL,
      `FileName` varchar(200) DEFAULT NULL,
      `StartDateTime` datetime DEFAULT NULL,
      `EndDateTime` datetime DEFAULT NULL,
      `Status` varchar(50) DEFAULT NULL,
      `ETLLoadDate` datetime NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The below are the two scenarios where i am getting Success for two. Ideally the status failure for 10 and success for 20.

insert into Batch values(10,10.1,'a.csv','2017-07-06 11:16:07','2017-07-06 11:17:07','FAILED','2017-07-06 11:17:07');
insert into Batch values(10,10.1,'b.csv','2017-07-06 11:18:08','2017-07-06 11:19:07','SUCCESS','2017-07-06 11:19:07');
insert into Batch values(10,10.1,'c.csv','2017-07-06 11:19:08','2017-07-06 11:20:07','SUCCESS','2017-07-06 11:20:07');
insert into Batch values(10,10.1,'d.csv','2017-07-06 11:20:08','2017-07-06 11:21:07','SUCCESS','2017-07-06 11:21:07');
insert into Batch values(10,10.2,'e.csv','2017-07-06 11:21:08','2017-07-06 11:22:07','SUCCESS','2017-07-06 11:22:07');
insert into Batch values(10,10.3,'f.csv','2017-07-06 11:22:08','2017-07-06 11:23:07','SUCCESS','2017-07-06 11:23:07');

insert into Batch values(20,20.1,'a.csv','2017-07-06 11:16:07','2017-07-06 11:17:07','FAILED','2017-07-06 11:17:07');
insert into Batch values(20,20.1,'b.csv','2017-07-06 11:18:08','2017-07-06 11:19:07','SUCCESS','2017-07-06 11:19:07');
insert into Batch values(20,20.1,'c.csv','2017-07-06 11:19:08','2017-07-06 11:20:07','SUCCESS','2017-07-06 11:20:07');
insert into Batch values(20,20.1,'d.csv','2017-07-06 11:20:08','2017-07-06 11:21:07','SUCCESS','2017-07-06 11:21:07');
insert into Batch values(20,20.2,'e.csv','2017-07-06 11:21:08','2017-07-06 11:22:07','SUCCESS','2017-07-06 11:22:07');
insert into Batch values(20,20.3,'f.csv','2017-07-06 11:22:08','2017-07-06 11:23:07','SUCCESS','2017-07-06 11:23:07');
insert into Batch values(20,20.1,'a.csv','2017-07-06 11:16:07','2017-07-06 11:17:07','SUCCESS','2017-07-06 11:17:07');

Body:
E.g.

SELECT DISTINCT DATE(a.startdatetime)
              , COALESCE(b.status,a.status) status
  FROM
     ( SELECT x.*
         FROM batch x
         JOIN
            ( SELECT id
                   , stepid
                   , DATE(startdatetime) dt
                   , MAX(startdatetime) max_dt
                FROM batch
               GROUP
                  BY id
                   , stepid
                   , dt
            ) y
           ON y.id = x.id
          AND y.stepid = x.stepid
          AND y.dt = DATE(x.startdatetime)
          AND y.max_dt = x.startdatetime
     ) a
  LEFT
  JOIN
     ( SELECT x.*
         FROM batch x
         JOIN
            ( SELECT id
                   , stepid
                   , DATE(startdatetime) dt
                   , MAX(startdatetime) max_dt
                FROM batch
               GROUP
                  BY id
                   , stepid
                   , dt
            ) y
           ON y.id = x.id
          AND y.stepid = x.stepid
          AND y.dt = DATE(x.startdatetime)
          AND y.max_dt = x.startdatetime
     ) b
    ON b.id = a.id
   AND DATE(b.startdatetime) = DATE(a.startdatetime)
   AND b.status = 'failed'
 WHERE a.status = 'success';
+-----------------------+---------+
| DATE(a.startdatetime) | status  |
+-----------------------+---------+
| 2017-06-21            | SUCCESS |
| 2017-06-22            | FAILED  |
| 2017-06-24            | FAILED  |
| 2017-06-23            | SUCCESS |
+-----------------------+---------+


问:
Java libGDX different sizes of animation frames
How to deal with different sizes of frames? If I setBounds(0, 0, 100, 100) in constructor then some frames are smaller but if I update it then frames are moved to left and up. How to make that every frame will be in the same place?

mayby you can see it
http://imgur.com/a/AN8Gc

```<code>public class Player extends Sprite{

//floats
private float animationTimer;

//box2d variables
public World world;
public Body body;

//enums
public enum State{STANDING, MOVING, SHOOTING, RELOAD, MALEE_ATTACK}
public State currentState;
public State previousState;

//booleans
boolean shoot;
boolean reload;
boolean maleeAttack;

private TextureRegion region;

public PlayScreen playScreen;

public Player(PlayScreen playScreen){
    this.playScreen = playScreen;
    this.world = playScreen.getWorld();
    definePlayer();

    animationTimer = 0;

    region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);

    setRegion(region);
    setBounds(0, 0, getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM);
    setPosition(0, 0);

    currentState = State.STANDING;
    previousState = State.STANDING;

    shoot = false;
    reload = false;
    maleeAttack = false;
}

public void definePlayer(){
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(100 / Constants.PPM, 100 / Constants.PPM);
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    body = world.createBody(bodyDef);

    FixtureDef fixtureDef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(50 / Constants.PPM);
    fixtureDef.shape = shape;
    body.createFixture(fixtureDef).setUserData(this);

    body.setLinearDamping(Constants.LINEAR_DAMPING);
}

public void update(float delta){
    region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);
    setRegion(getFrame(delta));
    moving();
    //rotate();

}

public void moving(){
    setPosition(body.getPosition().x - getWidth() / 2,  body.getPosition(). y - getHeight() / 2);
//setBounds(0, 0, getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM); update bounds
    if (input.isKeyPressed(Input.Keys.W) && body.getLinearVelocity().y < 5){
        body.applyLinearImpulse(new Vector2(0, 1), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.S) && body.getLinearVelocity().y > -5){
        body.applyLinearImpulse(new Vector2(0, -1), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.D) && body.getLinearVelocity().x < 5){
        body.applyLinearImpulse(new Vector2(1, 0), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.A) && body.getLinearVelocity().x > -5){
        body.applyLinearImpulse(new Vector2(-1, 0), body.getWorldCenter(), true);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.R)){
        reload = true;
    }

    if (Gdx.input.isKeyPressed(Input.Keys.F)){
        maleeAttack = true;
    }
    if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
        shoot = true;
    }

}

public TextureRegion getFrame(float delta){
    TextureRegion region;

    currentState = getState();

    switch (currentState){
        case MOVING:
            region = Assets.instance.playerAssets.moveAnimation.getKeyFrame(animationTimer);
            break;
        case SHOOTING:
            maleeAttack = false;
            region = Assets.instance.playerAssets.shootAniamtion.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.shootAniamtion.isAnimationFinished(animationTimer)){
                shoot = false;
            }
            break;
        case RELOAD:
            region = Assets.instance.playerAssets.reloadAnimation.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.reloadAnimation.isAnimationFinished(animationTimer)){
                reload = false;
            }
            break;
        case MALEE_ATTACK:
            region = Assets.instance.playerAssets.maleeAttackAnimation.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.maleeAttackAnimation.isAnimationFinished(animationTimer)) {
                maleeAttack = false;
            }
            break;
        default:
            region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);
            break;
    }

    animationTimer = currentState == previousState ? animationTimer + delta : 0;
    previousState = currentState;

    return region;
}

public State getState(){
    if ((body.getLinearVelocity().x > 1 || body.getLinearVelocity().x < -1 || body.getLinearVelocity().y > 1 || body.getLinearVelocity().y < - 1)  && !reload && !shoot && !maleeAttack){
        return State.MOVING;
    }
    if (shoot && !reload){
        return State.SHOOTING;
    }
    if (reload && !maleeAttack){
        return State.RELOAD;
    }
    if (maleeAttack){
        return State.MALEE_ATTACK;
    }
    else {
        return State.STANDING;
    }
}

public Vector2 getMousePosition(){
    Vector2 mousePosition;
    mousePosition = playScreen.getViewport().unproject(new Vector2(Gdx.input.getX(), Gdx.input.getY()));
    return mousePosition;
}

public float getMouseAngle(){
    float angle = (float) Math.atan2(getMousePosition().y - body.getPosition().y, getMousePosition().x -  body.getPosition().x);
    return angle;
}

public void rotate(){
    setOrigin(getWidth() / 2, getHeight() / 2 );
    setRotation((float) (getMouseAngle() * (180/Math.PI)));
    body.setTransform(body.getPosition(), getMouseAngle());
}
</code>```

}

答:
To avoid the resizing of the texture just create a variable size used to set the bounds. The bound needs to set every frame.</p>

```<code>public class Player extends Sprite {

    private Body body;
    private Vector2 size;

    public Player(){

        this.size = new Vector2( getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM );
    }

    public void update( float delta ){

        Vector2 position = body.getPosition();

        setRegion( getFrame( delta ) );
        setRotation( MathUtils.radDeg * body.getAngle() );
        setBounds( position.x, position.y, size.x, size.y );
        setOriginCenter();
    }

    public void rotate(){

        this.body.setTransform( body.getPosition(), getMouseAngle() );
    }
}
</code>```

Body:
How to deal with different sizes of frames? If I setBounds(0, 0, 100, 100) in constructor then some frames are smaller but if I update it then frames are moved to left and up. How to make that every frame will be in the same place?

mayby you can see it
http://imgur.com/a/AN8Gc

public class Player extends Sprite{

//floats
private float animationTimer;

//box2d variables
public World world;
public Body body;

//enums
public enum State{STANDING, MOVING, SHOOTING, RELOAD, MALEE_ATTACK}
public State currentState;
public State previousState;

//booleans
boolean shoot;
boolean reload;
boolean maleeAttack;

private TextureRegion region;

public PlayScreen playScreen;

public Player(PlayScreen playScreen){
    this.playScreen = playScreen;
    this.world = playScreen.getWorld();
    definePlayer();

    animationTimer = 0;

    region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);

    setRegion(region);
    setBounds(0, 0, getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM);
    setPosition(0, 0);

    currentState = State.STANDING;
    previousState = State.STANDING;

    shoot = false;
    reload = false;
    maleeAttack = false;
}

public void definePlayer(){
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(100 / Constants.PPM, 100 / Constants.PPM);
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    body = world.createBody(bodyDef);

    FixtureDef fixtureDef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(50 / Constants.PPM);
    fixtureDef.shape = shape;
    body.createFixture(fixtureDef).setUserData(this);

    body.setLinearDamping(Constants.LINEAR_DAMPING);
}

public void update(float delta){
    region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);
    setRegion(getFrame(delta));
    moving();
    //rotate();

}

public void moving(){
    setPosition(body.getPosition().x - getWidth() / 2,  body.getPosition(). y - getHeight() / 2);
//setBounds(0, 0, getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM); update bounds
    if (input.isKeyPressed(Input.Keys.W) && body.getLinearVelocity().y < 5){
        body.applyLinearImpulse(new Vector2(0, 1), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.S) && body.getLinearVelocity().y > -5){
        body.applyLinearImpulse(new Vector2(0, -1), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.D) && body.getLinearVelocity().x < 5){
        body.applyLinearImpulse(new Vector2(1, 0), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.A) && body.getLinearVelocity().x > -5){
        body.applyLinearImpulse(new Vector2(-1, 0), body.getWorldCenter(), true);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.R)){
        reload = true;
    }

    if (Gdx.input.isKeyPressed(Input.Keys.F)){
        maleeAttack = true;
    }
    if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
        shoot = true;
    }

}

public TextureRegion getFrame(float delta){
    TextureRegion region;

    currentState = getState();

    switch (currentState){
        case MOVING:
            region = Assets.instance.playerAssets.moveAnimation.getKeyFrame(animationTimer);
            break;
        case SHOOTING:
            maleeAttack = false;
            region = Assets.instance.playerAssets.shootAniamtion.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.shootAniamtion.isAnimationFinished(animationTimer)){
                shoot = false;
            }
            break;
        case RELOAD:
            region = Assets.instance.playerAssets.reloadAnimation.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.reloadAnimation.isAnimationFinished(animationTimer)){
                reload = false;
            }
            break;
        case MALEE_ATTACK:
            region = Assets.instance.playerAssets.maleeAttackAnimation.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.maleeAttackAnimation.isAnimationFinished(animationTimer)) {
                maleeAttack = false;
            }
            break;
        default:
            region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);
            break;
    }

    animationTimer = currentState == previousState ? animationTimer + delta : 0;
    previousState = currentState;

    return region;
}

public State getState(){
    if ((body.getLinearVelocity().x > 1 || body.getLinearVelocity().x < -1 || body.getLinearVelocity().y > 1 || body.getLinearVelocity().y < - 1)  && !reload && !shoot && !maleeAttack){
        return State.MOVING;
    }
    if (shoot && !reload){
        return State.SHOOTING;
    }
    if (reload && !maleeAttack){
        return State.RELOAD;
    }
    if (maleeAttack){
        return State.MALEE_ATTACK;
    }
    else {
        return State.STANDING;
    }
}

public Vector2 getMousePosition(){
    Vector2 mousePosition;
    mousePosition = playScreen.getViewport().unproject(new Vector2(Gdx.input.getX(), Gdx.input.getY()));
    return mousePosition;
}

public float getMouseAngle(){
    float angle = (float) Math.atan2(getMousePosition().y - body.getPosition().y, getMousePosition().x -  body.getPosition().x);
    return angle;
}

public void rotate(){
    setOrigin(getWidth() / 2, getHeight() / 2 );
    setRotation((float) (getMouseAngle() * (180/Math.PI)));
    body.setTransform(body.getPosition(), getMouseAngle());
}

}

Body:
To avoid the resizing of the texture just create a variable size used to set the bounds. The bound needs to set every frame.

public class Player extends Sprite {

    private Body body;
    private Vector2 size;

    public Player(){

        this.size = new Vector2( getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM );
    }

    public void update( float delta ){

        Vector2 position = body.getPosition();

        setRegion( getFrame( delta ) );
        setRotation( MathUtils.radDeg * body.getAngle() );
        setBounds( position.x, position.y, size.x, size.y );
        setOriginCenter();
    }

    public void rotate(){

        this.body.setTransform( body.getPosition(), getMouseAngle() );
    }
}


问:
Is it possible to do sub-query join using ServiceStack's OrmLite?
Is it possible to do sub-query join using ServiceStack's OrmLite?

Something like this?

```<code>var q = Db.From<Customer>()
    .Join<Customer, subq>((c, subq) => c.CustomerID == subq.CustomerID)
</code>```

答:
There's no Typed API support for joining on a sub select but you can use a CustomJoin to do this, e.g:

```<code>var q = Db.From<Customer>()
    .CustomJoin("INNER JOIN (SELECT Id FROM ...) sub ON sub.Id = Customer.Id")
</code>```

Body:
Is it possible to do sub-query join using ServiceStack's OrmLite?

Something like this?

var q = Db.From<Customer>()
    .Join<Customer, subq>((c, subq) => c.CustomerID == subq.CustomerID)

Body:
There's no Typed API support for joining on a sub select but you can use a CustomJoin to do this, e.g:

var q = Db.From<Customer>()
    .CustomJoin("INNER JOIN (SELECT Id FROM ...) sub ON sub.Id = Customer.Id")


问:
What is wrong with putting Using Blocks in Repository?
I have using blocks in each method of my repository. If I want to cross reference methods, it seems it would be against best practices to initialize another Datacontext  What am i doing wrong? If I declare a Datacontext in the class instead of using blocks in methods will I not lose power to dispose ??</p>

```<code>public IList<something> GetSomething()
{
   using (DB db=new DB())

   { ...GetListofSomethingElse(id)

   }
}

public IList<somethingelse> GetListofSomethingElse(int id)
{
    using (DB db=new DB())
   {
     ... return IList

   }
}
</code>```

答: The using statement is syntactic sugar.  It compiles to a try/finally block with the Dispose() call in the finally section.  It ensures that Dispose will be called even if an exception occurs.</p>

OwnerDisplayName: zsharp

Body:
I have using blocks in each method of my repository. If I want to cross reference methods, it seems it would be against best practices to initialize another Datacontext  What am i doing wrong? If I declare a Datacontext in the class instead of using blocks in methods will I not lose power to dispose ??

public IList<something> GetSomething()
{
   using (DB db=new DB())

   { ...GetListofSomethingElse(id)

   }
}

public IList<somethingelse> GetListofSomethingElse(int id)
{
    using (DB db=new DB())
   {
     ... return IList

   }
}

OwnerDisplayName: Ed Swangren


问:
kotlin lambda expressions as optional parameter
How can I pass lambda expression as optional parameter in Kotlin language

```<code>val max = { a: Int, b: Int ->
  if (a > b)
      a
  else
      b
}
</code>```

I have to pass above thing is like optional parameter

答:
The following defines a function that accepts a function, and specifies a default value for the passed function if none is supplied.

```<code>fun foobar(fn: (a: Int, b: Int) -> Int = { a: Int, b: Int -> if (a > b) a else b }) {
  println(fn(42, 99))
}
</code>```

You can pass your own functions:

```<code>val min = { a: Int, b: Int -> if (a <= b) a else b }
foobar(min)

val max = { a: Int, b: Int -> if (a > b) a else b }
foobar(max)
</code>```

You can omit the function and use the default:

```<code>foobar()
</code>```

Alternatively you could refer to the standard library maxOf function as the default, rather than write your own:

```<code>fun foobar(fn: (a: Int, b: Int) -> Int = ::maxOf) {
  println(fn(42, 99))
}
</code>```

Body:
How can I pass lambda expression as optional parameter in Kotlin language

val max = { a: Int, b: Int ->
  if (a > b)
      a
  else
      b
}

I have to pass above thing is like optional parameter

Body:
The following defines a function that accepts a function, and specifies a default value for the passed function if none is supplied.

fun foobar(fn: (a: Int, b: Int) -> Int = { a: Int, b: Int -> if (a > b) a else b }) {
  println(fn(42, 99))
}

You can pass your own functions:

val min = { a: Int, b: Int -> if (a <= b) a else b }
foobar(min)

val max = { a: Int, b: Int -> if (a > b) a else b }
foobar(max)

You can omit the function and use the default:

foobar()

Alternatively you could refer to the standard library maxOf function as the default, rather than write your own:

fun foobar(fn: (a: Int, b: Int) -> Int = ::maxOf) {
  println(fn(42, 99))
}