问:
how to get dropdown selected rows from gridview in yii2
I am using yii2 advanced framework. There is a select2 dropdown list of companies name.
 In view/companies/index.php

```<code>Select2::widget([
    'id' => 'front_companies_select',
    'name' => 'state_10',
    'data' => $companyNameList,
    'options' => [
        'placeholder' => 'Select ...',
        'multiple' => true
    ],
]);
</code>```

and a button get info

```<code><?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'info']) ?>
</code>```

here is myjsfile

```<code>  $("#getinfo").click(function(){
    var selval = '';
    $("#front_companies_select option:selected").each(function () {
     var $this = $(this);
     if ($this.length) {
      var selText = $this.val();
      selval = selText+','+selval;
    }
  });
    var searchurl = 'index.php?r=companies&id'+selval;
    window.location.replace(searchurl);
    alert (selval); //here I can get id of selected rows but I want complete row
  });
</code>```

I want to show gridview rows of selected companies.
how to solve this ?

答:
use this in _form just put your field and table:-

     <?= $form->field($model, 'your_field')->widget(Select2::classname(), [
        'data' => arrayhelper::map(your_table::find()->all(),'id','your_field'),
        'language' => 'en',
        'options' => ['placeholder' => 'Select a state ...'],
        'pluginOptions' => [
        'allowClear' => true
        ],
    ]); ?>```

Body:
I am using yii2 advanced framework. There is a select2 dropdown list of companies name.
 In view/companies/index.php

Select2::widget([
    'id' => 'front_companies_select',
    'name' => 'state_10',
    'data' => $companyNameList,
    'options' => [
        'placeholder' => 'Select ...',
        'multiple' => true
    ],
]);

and a button get info

<?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'info']) ?>

here is myjsfile

  $("#getinfo").click(function(){
    var selval = '';
    $("#front_companies_select option:selected").each(function () {
     var $this = $(this);
     if ($this.length) {
      var selText = $this.val();
      selval = selText+','+selval;
    }
  });
    var searchurl = 'index.php?r=companies&id'+selval;
    window.location.replace(searchurl);
    alert (selval); //here I can get id of selected rows but I want complete row
  });

I want to show gridview rows of selected companies.
how to solve this ?


来源: stackexchange

问:
Pythonic way to loop over dictionary
I am practicing Pandas and have the following task:

Create a list whose elements are the # of columns of each .csv file

.csv files are stored in the dictionary directory keyed by year

I use a dictionary comprehension dataframes (again keyed by year) to store the .csv files as pandas dataframes

```<code>directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}
</code>```

```<code># My Approach 1
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]
</code>```

Which way is more "Pythonic"? Or is there a better way to approach this?

答:
```<code>import os
#use this to find files under certain dir, you can filter it if there are other files
target_files = os.listdir('path_to_file/')
columns = list()
for filename in train_files:
    #in your scenario @piRSquared's answer would be more efficient.
    columns.append(#column_numbers)
</code>```

If you want columns with the key by year from the filename, you can filter the filename and update dictionary like this:

```<code>year = filename.replace(r'[^0-9]', '')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pythonic way to loop over dictionary

Body:
I am practicing Pandas and have the following task:

Create a list whose elements are the # of columns of each .csv file

.csv files are stored in the dictionary directory keyed by year

I use a dictionary comprehension dataframes (again keyed by year) to store the .csv files as pandas dataframes

directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}

# My Approach 1
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]

Which way is more "Pythonic"? Or is there a better way to approach this?

Body:
import os
#use this to find files under certain dir, you can filter it if there are other files
target_files = os.listdir('path_to_file/')
columns = list()
for filename in train_files:
    #in your scenario @piRSquared's answer would be more efficient.
    columns.append(#column_numbers)

If you want columns with the key by year from the filename, you can filter the filename and update dictionary like this:

year = filename.replace(r'[^0-9]', '')


问:
navigator.geolocation.getCurrentPosition slow on Android stock browser
I'm calling

```<code>navigator.geolocation.getCurrentPosition
</code>```

on a stock (i.e. 'default') Android browser, on an Android tablet, to get the user's current position. The 1st time it's really quick, then it becomes really slow (5-10 secs) for subsequent calls. When I debug the stock Android browser using the Chrome developer tools, then it's always quick. I'm using https, and it makes no difference if I set:

```<code>enableHighAccuracy: false
</code>```

And if I use navigator.geolocation.watchPosition for the 2nd call and above, it doesn't help (so it's not like the IE issue where navigator.geolocation.getCurrentPosition can only be successfully called once).

What is going on and what could be causing this? There's no indication of anything in the console. I can't see any timeouts on other functions that could be interfering with this. It also always works quickly using the stock Android browser on an Android phone. I've tried opening maps on the tablet device I'm using, and restarting the device, but I still get the behaviour. If I disable 'settings > connections > Location (High accuracy) on the device, then detecting the current location doesn't work at all.

答: It's a Samsung Galaxy Tab 2. I did a soft-reset (hold down power and volume down key for 10s). Now it works. This is a known fix that can help reset GPS, however I'm not using a mobile network, I'm using wi-fi so I don't understand why this would make a difference. Any answers that could help explain this are appreciated!</p>

Body:
I'm calling

navigator.geolocation.getCurrentPosition

on a stock (i.e. 'default') Android browser, on an Android tablet, to get the user's current position. The 1st time it's really quick, then it becomes really slow (5-10 secs) for subsequent calls. When I debug the stock Android browser using the Chrome developer tools, then it's always quick. I'm using https, and it makes no difference if I set:

enableHighAccuracy: false

And if I use navigator.geolocation.watchPosition for the 2nd call and above, it doesn't help (so it's not like the IE issue where navigator.geolocation.getCurrentPosition can only be successfully called once).

What is going on and what could be causing this? There's no indication of anything in the console. I can't see any timeouts on other functions that could be interfering with this. It also always works quickly using the stock Android browser on an Android phone. I've tried opening maps on the tablet device I'm using, and restarting the device, but I still get the behaviour. If I disable 'settings > connections > Location (High accuracy) on the device, then detecting the current location doesn't work at all.


问:
SonarQube plugin with Android Studio
Has anyone succeeded in getting either the SonarQube Community IntelliJ plugin OR the 'official' SonarQube IntelliJ plugin to show results of static code analysis in Android Studio projects?

The second of these requires Maven but the first of these is supposed to be agnostic.

Somehow I managed to run a sonarRunner on my project in the past but I can't manage to do it now.  But there's not much point in getting that working again if I can't see my results in the IDE.

答:
Open Android studio

File -> Settings -> Plugins -> then type sonarqube and click on Browse repositories at the bottom.

Restart Android Studio.

now right click on project -> Analyze -> Sonarlint -> Analyze all files with Sonarlint

The results will be displayed in Sonarlint view at bottom

Title: SonarQube plugin with Android Studio


问:
how to display all snapshots in my aws account using python boto3
the aim of this program is to delete snapshots that are older than 60 days. when run it displays the following error " a=snapshot[s].start_time
AttributeError: 'dict' object has no attribute 'start_time' " This is my code</p>

```<code>    #!/usr/bin/env python
   import boto3
   import datetime
   client = boto3.client('ec2')
   snapshot= client.describe_snapshots()
   for s in snapshot:
     a=snapshot[s].start_time
     b=a.date()
     c=datetime.datetime.now().date()
     d=c-b
       if d.days>60 :
           snapshot[s].delete(dry_run=True)
</code>```

答:
Your error is in the line a=snapshot[s].start_time, use a=s.start_time

Note I would change "snapshot" to "snapshots". then in your for loop:

```<code>for snapshot in snapshots:
</code>```

This makes the code easier to read and clear on what your variables represent.

Another item is that start_time is a string. You will need to parse this to get a number. Here is an example to help you:

```<code>delete_time = datetime.utcnow() - timedelta(days=days)
for snapshot in snapshots:
    start_time = datetime.strptime(
        snapshot.start_time,
        '%Y-%m-%dT%H:%M:%S.000Z'
    )

    if start_time < delete_time:
        ***delete your snapshot here***
</code>```

Body:
the aim of this program is to delete snapshots that are older than 60 days. when run it displays the following error " a=snapshot[s].start_time
AttributeError: 'dict' object has no attribute 'start_time' " This is my code

    #!/usr/bin/env python
   import boto3
   import datetime
   client = boto3.client('ec2')
   snapshot= client.describe_snapshots()
   for s in snapshot:
     a=snapshot[s].start_time
     b=a.date()
     c=datetime.datetime.now().date()
     d=c-b
       if d.days>60 :
           snapshot[s].delete(dry_run=True)

Body:
Your error is in the line a=snapshot[s].start_time, use a=s.start_time

Note I would change "snapshot" to "snapshots". then in your for loop:

for snapshot in snapshots:

This makes the code easier to read and clear on what your variables represent.

Another item is that start_time is a string. You will need to parse this to get a number. Here is an example to help you:

delete_time = datetime.utcnow() - timedelta(days=days)
for snapshot in snapshots:
    start_time = datetime.strptime(
        snapshot.start_time,
        '%Y-%m-%dT%H:%M:%S.000Z'
    )

    if start_time < delete_time:
        ***delete your snapshot here***


问:
Regular Expression for Validating Bitcoin Addresses
I'm trying to write a function that returns true or false if it's a valid bitcoin address.

I currently have a QR Code Scanner that returns a string like this:

bitcoin:18YCdhPsd5gdf6WD4ioMZZJKTNdajUJyTM

Here's my function:

```<code>func isValidBitcoinAddress() -> Bool {
    var fullAddress = self.components(separatedBy: ":")
    let r = fullAddress[1].startIndex..<fullAddress[1].endIndex
    let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
    let r2 = self.range(of: pattern, options: .regularExpression)
    if r2 == r {
        return true
    } else {
        return false
    }
}
</code>```

Unfortunately this is returning false every time.

I got the RegEx patter from this site: http://mokagio.github.io/tech-journal/2014/11/21/regex-bitcoin.html

Is the format perhaps different in Swift?

Thanks!

答:
@rmaddy and @Alexander have answered your question.

I am just adding my implemented code:

```<code>func isValidBitcoinAddress(stringBitCoinID:String) -> Bool {
    let fullAddress = stringBitCoinID.components(separatedBy: ":")

    guard fullAddress.count == 2, fullAddress[0] == "bitcoin" else {
        return false
    }

    let r = fullAddress[1]
    let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"

    let bitCoinIDTest = NSPredicate(format:"SELF MATCHES %@", pattern)
    let result = bitCoinIDTest.evaluate(with: r)

    return result
}
</code>```

Body:
I'm trying to write a function that returns true or false if it's a valid bitcoin address.

I currently have a QR Code Scanner that returns a string like this:

bitcoin:18YCdhPsd5gdf6WD4ioMZZJKTNdajUJyTM

Here's my function:

func isValidBitcoinAddress() -> Bool {
    var fullAddress = self.components(separatedBy: ":")
    let r = fullAddress[1].startIndex..<fullAddress[1].endIndex
    let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
    let r2 = self.range(of: pattern, options: .regularExpression)
    if r2 == r {
        return true
    } else {
        return false
    }
}

Unfortunately this is returning false every time.

I got the RegEx patter from this site: http://mokagio.github.io/tech-journal/2014/11/21/regex-bitcoin.html

Is the format perhaps different in Swift?

Thanks!

Body:
@rmaddy and @Alexander have answered your question.

I am just adding my implemented code:

func isValidBitcoinAddress(stringBitCoinID:String) -> Bool {
    let fullAddress = stringBitCoinID.components(separatedBy: ":")

    guard fullAddress.count == 2, fullAddress[0] == "bitcoin" else {
        return false
    }

    let r = fullAddress[1]
    let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"

    let bitCoinIDTest = NSPredicate(format:"SELF MATCHES %@", pattern)
    let result = bitCoinIDTest.evaluate(with: r)

    return result
}


问:
Laravel questions about using One to One relationship between 2 tables
I have 2 tables which is district and address. Suppose these 2 tables have relations between each other. address table holds district foreign key. The problem is that it returns null in views. How do I display/output the district name? I followed the instruction exactly based on Laravel documentation.

DISTRICT TABLE

District Model

```<code>public function address()
{
    return $this->hasOne('App\Address');
}
</code>```

ADDRESS TABLE

Address Model

```<code>public function district()
{
    return $this->belongsTo('App\District', 'district');
}
</code>```

View

```<code>$getAddress = App\Address::all();

foreach($getAddress as $add)
{
   Address name: {{ $add->address_name }}
   District name : {{ $add->district['district_name'] }} //this returns null, WHY?
}
</code>```

答:
Instead you should get all value in one stroke by using with

```<code>$getAddress = App\Address::with('district')->all();
</code>```

And get value as

```<code>{{ $add->district->district_name }}
</code>```

Body:
I have 2 tables which is district and address. Suppose these 2 tables have relations between each other. address table holds district foreign key. The problem is that it returns null in views. How do I display/output the district name? I followed the instruction exactly based on Laravel documentation.

DISTRICT TABLE

District Model

public function address()
{
    return $this->hasOne('App\Address');
}

ADDRESS TABLE

Address Model

public function district()
{
    return $this->belongsTo('App\District', 'district');
}

View

$getAddress = App\Address::all();

foreach($getAddress as $add)
{
   Address name: {{ $add->address_name }}
   District name : {{ $add->district['district_name'] }} //this returns null, WHY?
}

Body:
Instead you should get all value in one stroke by using with

$getAddress = App\Address::with('district')->all();

And get value as

{{ $add->district->district_name }}


问:
on refresh redirect to path in angular2
Hi in my application if i refresh it is going to home page,I need to avoid this and want to redirect to particular desired path, Not able to find where to implement this like in routing or somewhere,Can anyone please help me.
my app.component file

```<code>import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute, Params} from "@angular/router";
import {AppService} from "../../services/app.service";

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
    islogin: boolean = true;
    currentPage: string = '';
    constructor(
      private router: Router,
      public appService: AppService
    ) {
    }
  ngOnInit() {
      this.islogin = !this.islogin;
  }
}
</code>```

Routing file:

```<code>export const appRoutes: Routes = [
     {
    path: 'login',
    component: LoginComponent
},
    {
        path: 'superuser-miscsuperusers',
        component: miscsuperusersComponent
    },
    {
        path: '**',
        component: LoginComponent
    },
{
    path: 'clients',
    component: ClientsComponent
}

];

export const appRoutingProviders: any[] = [];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes/*, { enableTracing: true }*/);
</code>```

答:
You can navigate to particular page from app.component.ts file. on launch or on load

```<code>//Decide the page based on your logic .
let link = ['/landingpage'];
this.router.navigate(link);
</code>```

Here the problem is you will lose all temporary data on refresh so you should use some other storage to get back your old state of application ex : localstorage.

Title: on refresh redirect to path in angular2

Body:
Hi in my application if i refresh it is going to home page,I need to avoid this and want to redirect to particular desired path, Not able to find where to implement this like in routing or somewhere,Can anyone please help me.
my app.component file

import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute, Params} from "@angular/router";
import {AppService} from "../../services/app.service";

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
    islogin: boolean = true;
    currentPage: string = '';
    constructor(
      private router: Router,
      public appService: AppService
    ) {
    }
  ngOnInit() {
      this.islogin = !this.islogin;
  }
}

Routing file:

export const appRoutes: Routes = [
     {
    path: 'login',
    component: LoginComponent
},
    {
        path: 'superuser-miscsuperusers',
        component: miscsuperusersComponent
    },
    {
        path: '**',
        component: LoginComponent
    },
{
    path: 'clients',
    component: ClientsComponent
}

];

export const appRoutingProviders: any[] = [];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes/*, { enableTracing: true }*/);

Body:
You can navigate to particular page from app.component.ts file. on launch or on load

//Decide the page based on your logic .
let link = ['/landingpage'];
this.router.navigate(link);

Here the problem is you will lose all temporary data on refresh so you should use some other storage to get back your old state of application ex : localstorage.


答:
you should try this:</p>

```<code><php $getAddress = App\Address::with('district')->get(); ?>

@foreach($getAddress as $add)

   Address name: {{ $add->address_name }}

   @foreach($add->district as $districrt)
    District name : {{ $districrt->district_name }}
  @endforeach

@endforeach
</code>```

Title: Laravel questions about using One to One relationship between 2 tables

Body:
you should try this:

<php $getAddress = App\Address::with('district')->get(); ?>

@foreach($getAddress as $add)

   Address name: {{ $add->address_name }}

   @foreach($add->district as $districrt)
    District name : {{ $districrt->district_name }}
  @endforeach

@endforeach


问:
SubString across different string lengths
I have the following SUBSTRING command:

```<code>RTRIM(LTRIM(SUBSTRING(FileName, CHARINDEX('-', FileName, 0)+1, CHARINDEX('-', FileName, 0)-7 )))
</code>```

and have file paths like the below:

```<code>"C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf"    returns "V0001514"
"C:\James\test(100) - V0001585 MRS A SMITH.pdf  returns "V0001585 MR"
</code>```

The first one returns the correct result, but the second returns extra characters. Does anyone see a way of ensuring the V* number is always returned correctly?

答:
Try the following, hope it helps you:</p>

```<code>DECLARE @FileName VARCHAR(100)='C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf'
SELECT @FileName=SUBSTRING(@FileName,CHARINDEX('-',@FileName)+2,LEN(@FileName)-CHARINDEX('-',@FileName))
SELECT LEFT(@FileName,CHARINDEX(' ',@FileName)-1)
</code>```

Body:
I have the following SUBSTRING command:

RTRIM(LTRIM(SUBSTRING(FileName, CHARINDEX('-', FileName, 0)+1, CHARINDEX('-', FileName, 0)-7 )))

and have file paths like the below:

"C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf"    returns "V0001514"
"C:\James\test(100) - V0001585 MRS A SMITH.pdf  returns "V0001585 MR"

The first one returns the correct result, but the second returns extra characters. Does anyone see a way of ensuring the V* number is always returned correctly?

Body:
Try the following, hope it helps you:

DECLARE @FileName VARCHAR(100)='C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf'
SELECT @FileName=SUBSTRING(@FileName,CHARINDEX('-',@FileName)+2,LEN(@FileName)-CHARINDEX('-',@FileName))
SELECT LEFT(@FileName,CHARINDEX(' ',@FileName)-1)


问:
Use literal numbers in Fin patterns
On one hand, I can use #_ to construct Fins from literals:

```<code>open import Data.Fin

data I'mFinnish : Set where
  Mk : Fin 5 → I'mFinnish

foo : I'mFinnish
foo = Mk (# 3)
</code>```

On the other hand, I can use literals to pattern match on naturals:

```<code>open import Data.Nat

data I'mANatural : Set where
  Mk : ℕ → I'mANatural

open import Data.Bool
bar : I'mANatural → Bool
bar (Mk 3) = true
bar _      = false
</code>```

My question is, can I, on the gripping hand, use literals when matching on Fins? I.e., what can I do to approximate the following, invalid as-is, Agda code:

```<code>open import Data.Bool
bar′ : I'mFinnish → Bool
bar′ (Mk 3) = true
bar′ _      = false
</code>```

答:
You're looking for literal overloading. Quoting documentation, the Agda.Builtin.FromNat module provides a type class

```<code>record Number {a} (A : Set a) : Set (lsuc a) where
  field
    Constraint : Nat → Set a
    fromNat : ∀ n → {{_ : Constraint n}} → A

open Number {{...}} public using (fromNat)

{-# BUILTIN FROMNAT fromNat #-}
</code>```

which allows to overload natural literals. An instance for Fin can be found at the former link too. And you can directly define an instance for I'mFinnish.

Title: Use literal numbers in Fin patterns

Body:
On one hand, I can use #_ to construct Fins from literals:

open import Data.Fin

data I'mFinnish : Set where
  Mk : Fin 5 → I'mFinnish

foo : I'mFinnish
foo = Mk (# 3)

On the other hand, I can use literals to pattern match on naturals:

open import Data.Nat

data I'mANatural : Set where
  Mk : ℕ → I'mANatural

open import Data.Bool
bar : I'mANatural → Bool
bar (Mk 3) = true
bar _      = false

My question is, can I, on the gripping hand, use literals when matching on Fins? I.e., what can I do to approximate the following, invalid as-is, Agda code:

open import Data.Bool
bar′ : I'mFinnish → Bool
bar′ (Mk 3) = true
bar′ _      = false

Body:
You're looking for literal overloading. Quoting documentation, the Agda.Builtin.FromNat module provides a type class

record Number {a} (A : Set a) : Set (lsuc a) where
  field
    Constraint : Nat → Set a
    fromNat : ∀ n → {{_ : Constraint n}} → A

open Number {{...}} public using (fromNat)

{-# BUILTIN FROMNAT fromNat #-}

which allows to overload natural literals. An instance for Fin can be found at the former link too. And you can directly define an instance for I'mFinnish.


问:
iOS paint features to my app
I'm trying to add a drawing feature to my app. I have two UIImageViews... the bottom one contains a picture, let's say a photograph, and the second one on top of it is the one I want to paint on.

```<code>- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
    UIView *tappedView = [gesture.view hitTest:[gesture locationInView:gesture.view] withEvent:nil];

    CGPoint currentPoint = [gesture locationInView:_paintOverlay];

    UIGraphicsBeginImageContext(_paintOverlay.frame.size);
    [_paintOverlay.image drawInRect:CGRectMake(0, 0, _paintOverlay.frame.size.width, _paintOverlay.frame.size.height)];
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), 5, 5);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

    CGContextStrokePath(UIGraphicsGetCurrentContext());
   _paintOverlay.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSLog(@"Touch event on view: %@",[tappedView class]);
}
</code>```

This simply isn't working. I can't find any tutorials to help me with this, the one I found (where I derived this code from) wasn't so understandable.

答:
try with touches methods instead of tap gesture since one can move the fingers around to draw, touches will be good to implement.
refer the sample at: https://www.raywenderlich.com/18840/how-to-make-a-simple-drawing-app-with-uikit</p>

Title: iOS paint features to my app

Body:
I'm trying to add a drawing feature to my app. I have two UIImageViews... the bottom one contains a picture, let's say a photograph, and the second one on top of it is the one I want to paint on.

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
    UIView *tappedView = [gesture.view hitTest:[gesture locationInView:gesture.view] withEvent:nil];

    CGPoint currentPoint = [gesture locationInView:_paintOverlay];

    UIGraphicsBeginImageContext(_paintOverlay.frame.size);
    [_paintOverlay.image drawInRect:CGRectMake(0, 0, _paintOverlay.frame.size.width, _paintOverlay.frame.size.height)];
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), 5, 5);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

    CGContextStrokePath(UIGraphicsGetCurrentContext());
   _paintOverlay.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSLog(@"Touch event on view: %@",[tappedView class]);
}

This simply isn't working. I can't find any tutorials to help me with this, the one I found (where I derived this code from) wasn't so understandable.


问:
Issue requests from local Google App Engine devserver with TLSv1.2
I'm running an AppEngine on Java 1.7, using the Spring framework. I need to do request to the Stripe API , which requires TLSv1.2 when doing a request. This works fine when deploying the application to the Google environment, but it refuses to use this protocol when running the server locally. It gives the following error:

Stripe no longer supports API requests made with TLS 1.0. Please
  initiate HTTPS connections with TLS 1.2 or later. You can learn more
  about this at https://stripe.com/blog/upgrading-tls.

I'm using IntelliJ, AppEngine SDK version 1.9.42 in combination with Maven. I've tried adding build options in multiple places (-Ddeployment.security.TLSv1.2=true -Dhttps.protocols=TLSv1.2), in the IntelliJ Run/Debug configuration, in the XML JVM flags, in the dev_appserver.py file, but none of them worked. How can I enable TLSv1.2 in my Java 7 local development server, and talk to the Stripe API?

答:
From the blog entry referenced in the error log:

You can proactively check whether your Stripe integration is ready,
  and how to upgrade, by following the steps on our TLS deprecation
  page.

And from that link which points to How do I upgrade my Stripe integration from TLS 1.0 to TLS 1.2? you can find the Java-specific instructions:

You can determine whether your Java integration is affected from the
  Java version you are running, and the stripe-java version you are
  using.

You can find your Java version by running java -version at the
  command line, and your stripe-java version by looking for the version
  number in your jar file’s name, for example stripe-java-1.40.0.jar
  or by finding the version of the Stripe dependency in your POM file.

If you are running Java

version 1.6, you will need to upgrade to at least Java version 1.7, and stripe-java version 1.36.0.

version 1.7, and you have a stripe-java version earlier than 1.36.0, you will need to upgrade to at least stripe-java version 1.36.0.

version 1.8, you will not need to change anything.

You can upgrade your stripe-java version by downloading a new
  jar, or by upgrading the version number in your POM, and
  rebuilding your project.

You can upgrade your Java version by downloading a new copy, or
  installing a newer version of OpenJDK.


问:
C# how calculate my price in my listbox
I am a beginner and trying to create a simple inventory for our future business :)

How can I do to this problem ?

I want to calculate the price when I click every button to my listbox.

Example:

When I add items and the price is 6 he display to the bottom (Total) 6 and when I add another and the price is 7 is added to 6 so the total will 13 what can I do to this scenario can I use foreach or something or I revise my code ? help guys thank you :)

enter image description here

```<code>private void button4_Click(object sender, EventArgs e)
{
    int sum = 0;
    if (listBox1.Items.Count >= 0)
    {
        listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
        sum += Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());

    }
    label7.Text = sum.ToString();
}
</code>```

and I cannot deduct when I void the list of transaction

```<code>private void button6_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1)
    {
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        sum -= Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());
    }
}
</code>```

答:
Another way to do using LINQ.

```<code>using System.Linq; //import this namespace
//...
//...

private void button4_Click(object sender, EventArgs e)
{
    if (listBox1.Items.Count >= 0)
    {
        listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
    }
    label7.Text = listBox1.Items.OfType<int>().ToArray().Sum().ToString();
}
</code>```

You don't have to keep track of the items added or removed from the listbox in a separate variable- sum. Just use below LINQ sum() operation on your listBox whenever you want to sum the values.

```<code>listBox1.Items.OfType<int>().ToArray().Sum()
</code>```

Title: C# how calculate my price in my listbox

Body:
I am a beginner and trying to create a simple inventory for our future business :)

How can I do to this problem ?

I want to calculate the price when I click every button to my listbox.

Example:

When I add items and the price is 6 he display to the bottom (Total) 6 and when I add another and the price is 7 is added to 6 so the total will 13 what can I do to this scenario can I use foreach or something or I revise my code ? help guys thank you :)

enter image description here

private void button4_Click(object sender, EventArgs e)
{
    int sum = 0;
    if (listBox1.Items.Count >= 0)
    {
        listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
        sum += Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());

    }
    label7.Text = sum.ToString();
}

and I cannot deduct when I void the list of transaction

private void button6_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1)
    {
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        sum -= Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());
    }
}

Body:
Another way to do using LINQ.

using System.Linq; //import this namespace
//...
//...

private void button4_Click(object sender, EventArgs e)
{
    if (listBox1.Items.Count >= 0)
    {
        listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
    }
    label7.Text = listBox1.Items.OfType<int>().ToArray().Sum().ToString();
}

You don't have to keep track of the items added or removed from the listbox in a separate variable- sum. Just use below LINQ sum() operation on your listBox whenever you want to sum the values.

listBox1.Items.OfType<int>().ToArray().Sum()


答:
The problem is you have fixed your data length by -7

You could try :

```<code>SELECT SUBSTRING (@DATA, CHARINDEX('-', @DATA)+1,
           CHARINDEX(' ', LTRIM(SUBSTRING(@DATA, CHARINDEX('-', @DATA)+1, LEN(@DATA)))))
</code>```

Result :

```<code>"C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf"    returns "V0001514"
"C:\James\test(100) - V0001585 MRS A SMITH.pdf  returns "V0001585"
</code>```

Title: SubString across different string lengths

Body:
The problem is you have fixed your data length by -7

You could try :

SELECT SUBSTRING (@DATA, CHARINDEX('-', @DATA)+1,
           CHARINDEX(' ', LTRIM(SUBSTRING(@DATA, CHARINDEX('-', @DATA)+1, LEN(@DATA)))))

Result :

"C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf"    returns "V0001514"
"C:\James\test(100) - V0001585 MRS A SMITH.pdf  returns "V0001585"


问:
How to reverse a number in java in a user generated program
My teacher wants me to be able to ask this question an infinite number of times until the user decides to terminate it themselves. This works for the most part however, If I input a number too big I get an error because its a int data type. I have tried longs and doubles to but for some reason I get answers like infinity or the negative of the numbers. How do I fix this so I can put in as long of a number that I want and still get the positive integer reversal? Thank You so Much. Please keep it simple. This is literally my 5th computer class in my life.

```<code>import java.util.Scanner;
public class reverseInt3
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        int number;
        int reverse = 0;
        int number2;
        int reverse2 = 0;
        char repeat;

        System.out.println("Please enter any numbers you choose and I will reverse them for you");
        number = keyboard.nextInt();
        keyboard.nextLine();

        while( number != 0 )
        {
            reverse = reverse * 10;
            reverse = reverse + number%10;
            number = number/10;
        }

        System.out.println("Reverse of entered number is "+reverse);

        System.out.println("Do you want to repeat the process using different numbers? Y or N");
        repeat = keyboard.nextLine().charAt(0);

        while( repeat == 'Y' || repeat == 'y')
        {
            System.out.println("Please enter your new set of numbers");
            number2 = keyboard.nextInt();
            keyboard.nextLine();

            while( number2 != 0 )
            {
                reverse2 = reverse2 * 10;
                reverse2 = reverse2 + number2%10;
                number2 = number2/10;
            }
        System.out.println("The reverse of entered number is "+reverse2);

        System.out.println("Do you want to repeat the process using different numbers? Y or N");
        repeat = keyboard.nextLine().charAt(0);
        }
    }

}
</code>```

答:
First let's talk about your problem:

If the user input goes beyond the bound of int, long or double your program provides a negative reverse.

That's because when you try to store a very big number in smaller capacity variable, an overflow happens and after that your stored number is not valid and if you try to print it you will get a negative number instead which is not the exact negative for the user input.

If you want to overcome this, one way is to store the user input in a String variable. Then you can check if the input (which is stored in a String type variable) is really an integer or not, and if it was, you can reverse it.

I don't think this is actually what your teacher want you to do. Because the algorithm of reversing an integer (you implemented) can not be used to reverse such a big integer stored in a String variable. So I think your code is good and get it easy because probably your teacher don't expect you to maintain very big integers now. If you so worry about some bigger integers you can use long instead of int but as you know it has its own limitation about 18 digits approximately and it should not be bigger than Long.MAX_VALUE.

Your code is good for the start and I'm going to express some advice in order to provide a better and cleaner code:

It's obvious that you've repeated these part of codes:

```<code>System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
</code>```

and

```<code>while( number != 0 )
{
    reverse = reverse * 10;
    reverse = reverse + number%10;
    number = number/10;
}
</code>```

and

```<code>System.out.println("Reverse of entered number is "+reverse);
</code>```

If you studied methods so far, you may want to define these two first blocks in two different methods. One is responsible for getting input from user and the other one is responsible for getting an int as input and return the reversed int (If you used long for user input, this method's input and output should be of type long).

Another tip is why repeat those blocks? Why have two number and number2 variables and also reverse and reverse2?

Isn't it better to omit them and write your while for the repetition of the process in the first time too? Start by initializing the char repeat = 'Y'; and omit the first time you manually get the job done outside of the while( repeat == 'Y' || repeat == 'y') loop.

Hope this helps.

Body:
My teacher wants me to be able to ask this question an infinite number of times until the user decides to terminate it themselves. This works for the most part however, If I input a number too big I get an error because its a int data type. I have tried longs and doubles to but for some reason I get answers like infinity or the negative of the numbers. How do I fix this so I can put in as long of a number that I want and still get the positive integer reversal? Thank You so Much. Please keep it simple. This is literally my 5th computer class in my life.

import java.util.Scanner;
public class reverseInt3
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        int number;
        int reverse = 0;
        int number2;
        int reverse2 = 0;
        char repeat;

        System.out.println("Please enter any numbers you choose and I will reverse them for you");
        number = keyboard.nextInt();
        keyboard.nextLine();

        while( number != 0 )
        {
            reverse = reverse * 10;
            reverse = reverse + number%10;
            number = number/10;
        }

        System.out.println("Reverse of entered number is "+reverse);

        System.out.println("Do you want to repeat the process using different numbers? Y or N");
        repeat = keyboard.nextLine().charAt(0);

        while( repeat == 'Y' || repeat == 'y')
        {
            System.out.println("Please enter your new set of numbers");
            number2 = keyboard.nextInt();
            keyboard.nextLine();

            while( number2 != 0 )
            {
                reverse2 = reverse2 * 10;
                reverse2 = reverse2 + number2%10;
                number2 = number2/10;
            }
        System.out.println("The reverse of entered number is "+reverse2);

        System.out.println("Do you want to repeat the process using different numbers? Y or N");
        repeat = keyboard.nextLine().charAt(0);
        }
    }

}

Body:
First let's talk about your problem:

If the user input goes beyond the bound of int, long or double your program provides a negative reverse.

That's because when you try to store a very big number in smaller capacity variable, an overflow happens and after that your stored number is not valid and if you try to print it you will get a negative number instead which is not the exact negative for the user input.

If you want to overcome this, one way is to store the user input in a String variable. Then you can check if the input (which is stored in a String type variable) is really an integer or not, and if it was, you can reverse it.

I don't think this is actually what your teacher want you to do. Because the algorithm of reversing an integer (you implemented) can not be used to reverse such a big integer stored in a String variable. So I think your code is good and get it easy because probably your teacher don't expect you to maintain very big integers now. If you so worry about some bigger integers you can use long instead of int but as you know it has its own limitation about 18 digits approximately and it should not be bigger than Long.MAX_VALUE.

Your code is good for the start and I'm going to express some advice in order to provide a better and cleaner code:

It's obvious that you've repeated these part of codes:

System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();

and

while( number != 0 )
{
    reverse = reverse * 10;
    reverse = reverse + number%10;
    number = number/10;
}

and

System.out.println("Reverse of entered number is "+reverse);

If you studied methods so far, you may want to define these two first blocks in two different methods. One is responsible for getting input from user and the other one is responsible for getting an int as input and return the reversed int (If you used long for user input, this method's input and output should be of type long).

Another tip is why repeat those blocks? Why have two number and number2 variables and also reverse and reverse2?

Isn't it better to omit them and write your while for the repetition of the process in the first time too? Start by initializing the char repeat = 'Y'; and omit the first time you manually get the job done outside of the while( repeat == 'Y' || repeat == 'y') loop.

Hope this helps.