问:
Entity Framework Inheritance
I have looked at several possible solutions to my issue but did not find the right one.

I need a full set, that is, I need to fetch the types that are also of a base type. i.e. the ActionHistory type, as well as all others, which inherit from the ActionHistory base class. My problem was that I was getting all entities but those of the ActionUpdate type did not have the ActionUpdateDetails collection filled.

My problem is that I am unable to retrieve the ActionUpdateDetails data within the derived ActionUpdate class.

There are three classes in the model:

```<code>public class ActionHistory
{
public int Id {get;set;}
}

public class ActionUpdate : ActionHistory
{
public ICollection<ActionUpdateDetail> ActionUpdateDetails{get;set;}
}

public class ActionUpdateDetail
{
int Id{get;set;}
public string Field{get;set;}
public string Value{get;set;}
}
</code>```

I tried implementing the solution from this suggestion:
Entity Framework: Inheritance and Include

Like this:

```<code>var result = from actionHistory in ActionHistories
select new {
actionHistory,
actionUpdateDetails = actionHistory is ActionUpdate ?
(actionHistory as ActionUpdate).ActionUpdateDetails : null
};
</code>```

All I get is the exception message:

Unable to create a constant value of type 'System.Collections.Generic.ICollection`1'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

Then I tried to simulate the situation outside the EF and it worked. I am using a POCO model and have extracted the involved classes into a separate project, filled the structure sample with data, and tested it with a success, i.e. ActionUpdateDetails collection was filled with the data.

Any help on this will be appreciated!

N.

答:
With regards to your answer, actually, the correct way is to use OfType<T>:

```<code>var actionUpdateDetails = ctx.ActionHistories
                       .OfType<ActionUpdate>()
                       .Select(x => x.ActionUpdateDetails)
                       .ToList();
</code>```

This causes a database-side filter (inner join), whereas your solution performs implicit casting on items that may not be of that type - in which case you could get a null reference exception.

Title: Entity Framework Inheritance

Body:
I have looked at several possible solutions to my issue but did not find the right one.

I need a full set, that is, I need to fetch the types that are also of a base type. i.e. the ActionHistory type, as well as all others, which inherit from the ActionHistory base class. My problem was that I was getting all entities but those of the ActionUpdate type did not have the ActionUpdateDetails collection filled.

My problem is that I am unable to retrieve the ActionUpdateDetails data within the derived ActionUpdate class.

There are three classes in the model:

public class ActionHistory
{
public int Id {get;set;}
}

public class ActionUpdate : ActionHistory
{
public ICollection<ActionUpdateDetail> ActionUpdateDetails{get;set;}
}

public class ActionUpdateDetail
{
int Id{get;set;}
public string Field{get;set;}
public string Value{get;set;}
}

I tried implementing the solution from this suggestion:
Entity Framework: Inheritance and Include

Like this:

var result = from actionHistory in ActionHistories
select new {
actionHistory,
actionUpdateDetails = actionHistory is ActionUpdate ?
(actionHistory as ActionUpdate).ActionUpdateDetails : null
};

All I get is the exception message:

Unable to create a constant value of type 'System.Collections.Generic.ICollection`1'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

Then I tried to simulate the situation outside the EF and it worked. I am using a POCO model and have extracted the involved classes into a separate project, filled the structure sample with data, and tested it with a success, i.e. ActionUpdateDetails collection was filled with the data.

Any help on this will be appreciated!

N.

Body:
With regards to your answer, actually, the correct way is to use OfType<T>:

var actionUpdateDetails = ctx.ActionHistories
                       .OfType<ActionUpdate>()
                       .Select(x => x.ActionUpdateDetails)
                       .ToList();

This causes a database-side filter (inner join), whereas your solution performs implicit casting on items that may not be of that type - in which case you could get a null reference exception.


来源: stackexchange

问:
batch: ampersand causing issues with findstr
This part works well until there is an ampersand in the filename, in which case it crashes my script completely.

```<code>echo %filename% | findstr /i /b /c:"%name% (%year%)"
</code>```

I can't just put the filename into quotation marks because I need to find the string at the beginning. So how can I do both?

答:
Another option is to use delayed expansion, which requires an explicit cmd with the /v:on option.

```<code>cmd /v:on /c "(echo !filename!)" | findstr /i /b /c:"%name% (%year%)"
</code>```

If your batch script already has enabled delayed expansion, then parentheses around the left side are needed to prevent the delayed expansion from occurring within the parent script (see Why does delayed expansion fail when inside a piped block of code?). The child process will still default to disabled delayed expansion, so the cmd /v:on /c ... is still needed.

```<code>@echo off
setlocal enableDelayedExpansion
...
(cmd /v:on /c "(echo !filename!)") | findstr /i /b /c:"%name% (%year%)"
</code>```

Another way to delay the expansion until the sub-process is to escape the expansion

```<code>@echo off
setlocal enableDelayedExpansion
...
cmd /v:on /c "(echo ^!filename^!)" | findstr /i /b /c:"%name% (%year%)"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This part works well until there is an ampersand in the filename, in which case it crashes my script completely.

echo %filename% | findstr /i /b /c:"%name% (%year%)"

I can't just put the filename into quotation marks because I need to find the string at the beginning. So how can I do both?

Body:
Another option is to use delayed expansion, which requires an explicit cmd with the /v:on option.

cmd /v:on /c "(echo !filename!)" | findstr /i /b /c:"%name% (%year%)"

If your batch script already has enabled delayed expansion, then parentheses around the left side are needed to prevent the delayed expansion from occurring within the parent script (see Why does delayed expansion fail when inside a piped block of code?). The child process will still default to disabled delayed expansion, so the cmd /v:on /c ... is still needed.

@echo off
setlocal enableDelayedExpansion
...
(cmd /v:on /c "(echo !filename!)") | findstr /i /b /c:"%name% (%year%)"

Another way to delay the expansion until the sub-process is to escape the expansion

@echo off
setlocal enableDelayedExpansion
...
cmd /v:on /c "(echo ^!filename^!)" | findstr /i /b /c:"%name% (%year%)"


问:
Catch exception from guzzle
I'm using laravel and I have setup the abstract class method to get response from the various APIs I'm calling. But if the API url is unreachable then it throws an exception. I know I'm missing something. Any help would be great for me. </p>

```<code>$offers = [];
    try {
      $appUrl = parse_url($this->apiUrl);

      // Call Api using Guzzle
      $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

      if ($appUrl['scheme'] == 'https') //If https then disable ssl certificate
        $client->setDefaultOption('verify', false);

      $request = $client->get('?' . $appUrl['query']);
      $response = $request->send();
      if ($response->getStatusCode() == 200) {
        $offers = json_decode($response->getBody(), true);
      }
    } catch (ClientErrorResponseException $e) {
      Log::info("Client error :" . $e->getResponse()->getBody(true));
    } catch (ServerErrorResponseException $e) {
      Log::info("Server error" . $e->getResponse()->getBody(true));
    } catch (BadResponseException $e) {
      Log::info("BadResponse error" . $e->getResponse()->getBody(true));
    } catch (\Exception $e) {
      Log::info("Err" . $e->getMessage());
    }

    return $offers;
</code>```

答:
you should set the guzzehttp client with option 'http_errors' => false,
the example code should be like this, document:guzzlehttp client http-error option explain

Set to false to disable throwing exceptions on an HTTP protocol errors (i.e., 4xx and 5xx responses). Exceptions are thrown by default when HTTP protocol errors are encountered.

```<code>$client->request('GET', '/status/500');
// Throws a GuzzleHttp\Exception\ServerException

$res = $client->request('GET', '/status/500', ['http_errors' => false]);
echo $res->getStatusCode();
// 500

$this->client = new Client([
    'cookies' => true,
    'headers' => $header_params,
    'base_uri' => $this->base_url,
    'http_errors' => false
]);

$response = $this->client->request('GET', '/');
if ($code = $response->getStatusCode() == 200) {
   try {
       // do danger dom things in here
   }catch (/Exception $e){
      //catch
   }

}
</code>```

Title: Catch exception from guzzle

Body:
I'm using laravel and I have setup the abstract class method to get response from the various APIs I'm calling. But if the API url is unreachable then it throws an exception. I know I'm missing something. Any help would be great for me.

$offers = [];
    try {
      $appUrl = parse_url($this->apiUrl);

      // Call Api using Guzzle
      $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

      if ($appUrl['scheme'] == 'https') //If https then disable ssl certificate
        $client->setDefaultOption('verify', false);

      $request = $client->get('?' . $appUrl['query']);
      $response = $request->send();
      if ($response->getStatusCode() == 200) {
        $offers = json_decode($response->getBody(), true);
      }
    } catch (ClientErrorResponseException $e) {
      Log::info("Client error :" . $e->getResponse()->getBody(true));
    } catch (ServerErrorResponseException $e) {
      Log::info("Server error" . $e->getResponse()->getBody(true));
    } catch (BadResponseException $e) {
      Log::info("BadResponse error" . $e->getResponse()->getBody(true));
    } catch (\Exception $e) {
      Log::info("Err" . $e->getMessage());
    }

    return $offers;

Body:
you should set the guzzehttp client with option 'http_errors' => false,
the example code should be like this, document:guzzlehttp client http-error option explain

Set to false to disable throwing exceptions on an HTTP protocol errors (i.e., 4xx and 5xx responses). Exceptions are thrown by default when HTTP protocol errors are encountered.

$client->request('GET', '/status/500');
// Throws a GuzzleHttp\Exception\ServerException

$res = $client->request('GET', '/status/500', ['http_errors' => false]);
echo $res->getStatusCode();
// 500

$this->client = new Client([
    'cookies' => true,
    'headers' => $header_params,
    'base_uri' => $this->base_url,
    'http_errors' => false
]);

$response = $this->client->request('GET', '/');
if ($code = $response->getStatusCode() == 200) {
   try {
       // do danger dom things in here
   }catch (/Exception $e){
      //catch
   }

}


问:
Angular - Child routing not working
EDIT SOLUTION:

I ended up having to navigate by using something like this (which differs slightly from the code below)

```<code>  onSelect(menuItem: string): void {
    this.selectedMenuItem = menuItem;
    if (menuItem == 'Upload') {
      this.router.navigateByUrl('/adminhome/(adminhomeviewport:adminupload)');
    }
    else if (menuItem == "Download") {
      this.router.navigateByUrl('/adminhome/(adminhomeviewport:admindownload)');
    }
  }
</code>```

I'm not sure why it has to be done this way, or why if there is another way to do it, but this gives me the expected behavior.

I'm using Angular and I'm trying to have a named router-outlet in one of my views.  Unfortunately, nothing seems to be working at all.  My goal is to get the router-outlet named 'admin-viewport' found on the 'http://localhost:4200/adminhome' page to show the 'AdminUploadComponent' and it's related view.

As of now, the parent html, http://localhost:4200/adminhome, which I can successfully navigate to looks like this:

```<code><div class="home-root">
  <ul class="home-menu"  ng-controller="AdminHomeComponent">
    <li *ngFor="let menuString of menuStrings"
        [class.selected]="menuString === selectedMenuItem"
        (click)="onSelect(menuString)">
      <span class="badge">*</span>{{menuString}}
    </li>
  </ul>
  <router-outlet name="admin-viewport"></router-outlet>
</div>
</code>```

And the routes in my app.module.ts looks like this:

```<code>RouterModule.forRoot([
{
  path: 'adminlogin',
  component: AdminLoginComponent
},
{
  path: 'search',
  component: SearchQueryComponent
},
{
  path: 'adminhome',
  component: AdminHomeComponent,
  children : [
    {
      path: 'adminupload',
      component: AdminUploadComponent,
      outlet: 'admin-viewport'
    },
  ]
}
</code>```

],
  { enableTracing: true }
)

On a button click, I attempt to navigate my outlet using this code.:

```<code>  constructor( private router: Router,public route: ActivatedRoute) {
  }

  onSelect(menuItem: string): void {
    this.selectedMenuItem = menuItem;
    if( menuItem == 'Upload' )
    {
      this.router.navigate(['/adminhome/adminupload', {outlet : 'admin-viewport'}]);
    }
  }
</code>```

Which of course throws the following error:

```<code>error_handler.ts:1 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'adminhome/adminupload;outlet=admin-viewport'
Error: Cannot match any routes. URL Segment: 'adminhome/adminupload;outlet=admin-viewport'
</code>```

Any help on how to navigate my child router-outlet would be greatly appreciated.

EDIT: When I list my routes after implementing @Seejatheran's suggestion, it still doesn't work and I get this this when I list my paths.

答:
In your onSelect method try this :

```<code>this.router.navigate([{ outlets: { admin-viewport: ['adminupload'] } }]);
</code>```

Hope this helps

Title: Angular - Child routing not working

Body:
EDIT SOLUTION:

I ended up having to navigate by using something like this (which differs slightly from the code below)

  onSelect(menuItem: string): void {
    this.selectedMenuItem = menuItem;
    if (menuItem == 'Upload') {
      this.router.navigateByUrl('/adminhome/(adminhomeviewport:adminupload)');
    }
    else if (menuItem == "Download") {
      this.router.navigateByUrl('/adminhome/(adminhomeviewport:admindownload)');
    }
  }

I'm not sure why it has to be done this way, or why if there is another way to do it, but this gives me the expected behavior.

I'm using Angular and I'm trying to have a named router-outlet in one of my views.  Unfortunately, nothing seems to be working at all.  My goal is to get the router-outlet named 'admin-viewport' found on the 'http://localhost:4200/adminhome' page to show the 'AdminUploadComponent' and it's related view.

As of now, the parent html, http://localhost:4200/adminhome, which I can successfully navigate to looks like this:

      *{{menuString}}

  <router-outlet name="admin-viewport"></router-outlet>

And the routes in my app.module.ts looks like this:

RouterModule.forRoot([
{
  path: 'adminlogin',
  component: AdminLoginComponent
},
{
  path: 'search',
  component: SearchQueryComponent
},
{
  path: 'adminhome',
  component: AdminHomeComponent,
  children : [
    {
      path: 'adminupload',
      component: AdminUploadComponent,
      outlet: 'admin-viewport'
    },
  ]
}

],
  { enableTracing: true }
)

On a button click, I attempt to navigate my outlet using this code.:

  constructor( private router: Router,public route: ActivatedRoute) {
  }

  onSelect(menuItem: string): void {
    this.selectedMenuItem = menuItem;
    if( menuItem == 'Upload' )
    {
      this.router.navigate(['/adminhome/adminupload', {outlet : 'admin-viewport'}]);
    }
  }

Which of course throws the following error:

error_handler.ts:1 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'adminhome/adminupload;outlet=admin-viewport'
Error: Cannot match any routes. URL Segment: 'adminhome/adminupload;outlet=admin-viewport'

Any help on how to navigate my child router-outlet would be greatly appreciated.

EDIT: When I list my routes after implementing @Seejatheran's suggestion, it still doesn't work and I get this this when I list my paths.

Body:
In your onSelect method try this :

this.router.navigate([{ outlets: { admin-viewport: ['adminupload'] } }]);

Hope this helps


问:
Changing tab bar font in Swift
I have been trying to change the font for the tab bar items however I haven't been able to find any Swift examples. I know that this is how you change it in Objective-C:

```<code>[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, nil] forState:UIControlStateNormal];
</code>```

But how can I translate this into Swift?

答:
In addition @Mc.Lover 's answer, If you want to aplly this change to all of your tab bar Items in application, I recommand to add the code in application function of AppDelegate class:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    //Just add this line to get it done.
    UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "IranSansMobile", size: 15)!], for: UIControlState.normal)

    return true
}
</code>```

Title: Changing tab bar font in Swift

Body:
I have been trying to change the font for the tab bar items however I haven't been able to find any Swift examples. I know that this is how you change it in Objective-C:

[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, nil] forState:UIControlStateNormal];

But how can I translate this into Swift?

Body:
In addition @Mc.Lover 's answer, If you want to aplly this change to all of your tab bar Items in application, I recommand to add the code in application function of AppDelegate class:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    //Just add this line to get it done.
    UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "IranSansMobile", size: 15)!], for: UIControlState.normal)

    return true
}


问:
How to resolve 'could not initialize an instance of the type uikit.uiimage : The native initwith contentsofFile' errors in icons tabbed page
I am very struggle to fix this strange issue. In my application using tabbed page with icons but when try to build getting exception. From last three months it's working fine. last day on wards it's getting build issue. please suggest any idea to fix this. Thanks in advance.</p>

答:
1) Check that build action for icon is set to Bundle Resource

2) Check the file name. If it contains capital letters, remove the file from the project, rename to lowercase and then add again.


问:
Problems of using curl on windows compared to mac
i use xampp apache to run some of my php files.

In one of my php file i use curl to get data from external website, on my windows machine, everything works fine. However, on my mac machine, my browser just can not run those files.. it just takes very long to load, and in the end stop loading.

Attached is one of my php file:

```<code><?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
'http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);

print $contents;
?>
</code>```

I am really desprate on why mac machine can not run these files? is there another way to go about doing this on a mac machine? THanks all for your help!

EDIT: [SOLVED] Thanks all for your help. Manage to solve it, due, to because i am connecting to the net using a proxy server...thus my script need to handle that.

Code used:

```<code><?php
$aContext = array(
'http' => array(
'proxy' =>'tcp://xxxxx:xx',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);

$content = file_get_contents("http://www.example.com", False, $csContext);

print $content;
?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i use xampp apache to run some of my php files.

In one of my php file i use curl to get data from external website, on my windows machine, everything works fine. However, on my mac machine, my browser just can not run those files.. it just takes very long to load, and in the end stop loading.

Attached is one of my php file:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
'http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);

print $contents;
?>

I am really desprate on why mac machine can not run these files? is there another way to go about doing this on a mac machine? THanks all for your help!

EDIT: [SOLVED] Thanks all for your help. Manage to solve it, due, to because i am connecting to the net using a proxy server...thus my script need to handle that.

Code used:

<?php
$aContext = array(
'http' => array(
'proxy' =>'tcp://xxxxx:xx',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);

$content = file_get_contents("http://www.example.com", False, $csContext);

print $content;
?>

Body: use echo file_get_contents('http://www.example.com');


问:
I have json object in constructor in my component and how to use the object when using click function
I have given below is my object in constructor.

I am passing value from previous conmponent to below component. and i
  am getting the item json object. but i need to use below object when i
  am clicking.

```<code>constructor(public navCtrl: NavController, public navParams: NavParams) {
     this.item= navParams.get('item');
</code>```

}

How i will use the item json object when i am click the button?

答:
try

```<code><button (click)="itemUse()"></button>
</code>```

in your html

and

```<code>  item;  //if not defined yet
    itemUse(){
      console.log(this.item)
}
</code>```

in your component

Body:
I have given below is my object in constructor.

I am passing value from previous conmponent to below component. and i
  am getting the item json object. but i need to use below object when i
  am clicking.

constructor(public navCtrl: NavController, public navParams: NavParams) {
     this.item= navParams.get('item');

}

How i will use the item json object when i am click the button?

Body:
try

<button (click)="itemUse()"></button>

in your html

and

  item;  //if not defined yet
    itemUse(){
      console.log(this.item)
}

in your component


问:
Get value from numberpicker and putting it in a textview
// i  need to get newVal out of all these numberpickers methods separately , and i set them in  to  textviews , but  when  try to get value from the text view app crash.can you help me . how can i get numberpicker value outside it's onValuechange method?

```<code>  public class MainActivity extends AppCompatActivity {

ImageButton start,pause,reset;
TextView total,mintimer,sectimer,textView6,textView7,textView8;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    start=(ImageButton)findViewById(R.id.start);
    pause=(ImageButton)findViewById(R.id.pause);
    reset=(ImageButton)findViewById(R.id.reset);

    total=(TextView)findViewById(R.id.total);
    mintimer=(TextView)findViewById(R.id.mintimer);
    sectimer=(TextView)findViewById(R.id.sectimer);

     //this is how i tried to get textview value as a string. then the app
     crashes
    String a=textView6.getText().toString();

    NumberPicker min = (NumberPicker) findViewById(R.id.min);
    NumberPicker sec = (NumberPicker) findViewById(R.id.sec);
    NumberPicker brk = (NumberPicker) findViewById(R.id.brk);

    min.setMinValue(1);
    min.setMaxValue(20);
    min.setWrapSelectorWheel(true);
    min.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
           textView6=(TextView)findViewById(R.id.textView6);
           textView6.setText(" "+newVal);

        }
    });

    //beep sound breake
    sec.setMaxValue(60);
    sec.setMinValue(0);
    sec.setWrapSelectorWheel(true);
    sec.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

        @Override
        public void onValueChange(NumberPicker picker, int oldVa2, int newVal2) {
            textView7=(TextView)findViewById(R.id.textView7);
            textView7.setText(" "+newVal2);
        }
    });
    //Break

    brk.setMaxValue(5);
    brk.setMaxValue(60);
    brk.setWrapSelectorWheel(true);
    brk.setOnValueChangedListener(new NumberPicker.OnValueChangeListener(){
        @Override
        public void onValueChange(NumberPicker picker ,int oldVal3,int newVal3){
            textView8=(TextView)findViewById(R.id.textView8);

            textView8.setText(" "+newVal3);

        }

    });

}
</code>```

}

答: textview6 is a null object. It doesn't have instance of TextView.</p>

Body:
// i  need to get newVal out of all these numberpickers methods separately , and i set them in  to  textviews , but  when  try to get value from the text view app crash.can you help me . how can i get numberpicker value outside it's onValuechange method?

  public class MainActivity extends AppCompatActivity {

ImageButton start,pause,reset;
TextView total,mintimer,sectimer,textView6,textView7,textView8;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    start=(ImageButton)findViewById(R.id.start);
    pause=(ImageButton)findViewById(R.id.pause);
    reset=(ImageButton)findViewById(R.id.reset);

    total=(TextView)findViewById(R.id.total);
    mintimer=(TextView)findViewById(R.id.mintimer);
    sectimer=(TextView)findViewById(R.id.sectimer);

     //this is how i tried to get textview value as a string. then the app
     crashes
    String a=textView6.getText().toString();

    NumberPicker min = (NumberPicker) findViewById(R.id.min);
    NumberPicker sec = (NumberPicker) findViewById(R.id.sec);
    NumberPicker brk = (NumberPicker) findViewById(R.id.brk);

    min.setMinValue(1);
    min.setMaxValue(20);
    min.setWrapSelectorWheel(true);
    min.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
           textView6=(TextView)findViewById(R.id.textView6);
           textView6.setText(" "+newVal);

        }
    });

    //beep sound breake
    sec.setMaxValue(60);
    sec.setMinValue(0);
    sec.setWrapSelectorWheel(true);
    sec.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

        @Override
        public void onValueChange(NumberPicker picker, int oldVa2, int newVal2) {
            textView7=(TextView)findViewById(R.id.textView7);
            textView7.setText(" "+newVal2);
        }
    });
    //Break

    brk.setMaxValue(5);
    brk.setMaxValue(60);
    brk.setWrapSelectorWheel(true);
    brk.setOnValueChangedListener(new NumberPicker.OnValueChangeListener(){
        @Override
        public void onValueChange(NumberPicker picker ,int oldVal3,int newVal3){
            textView8=(TextView)findViewById(R.id.textView8);

            textView8.setText(" "+newVal3);

        }

    });

}

}


问:
How to insert Select Query Result into a PIVOT
I m using SQL SERVER 2012.

Query:1

```<code>SELECT *
FROM (
    SELECT Insurance, ChargeValue, CreatedDate
    FROM dailychargesummary
    WHERE MonthName='June 2017'
) m
PIVOT (
    SUM(ChargeValue)
    FOR CreatedDate IN ([06/22/2017], [06/23/2017],[06/30/2017])
) n
</code>```

Output of above query is looks like below:

Now I m hard coding all the dates of a month inside the Pivot Query such as 06/01/2017, 06/02/2017, etc., After searching in the Google, I got the following query to display all the dates of a given month number.

Query 2:

```<code>DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016

;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT datefromparts(@year,@month,N) date FROM tally
WHERE N <= day(EOMONTH(datefromparts(@year,@month,1)))
</code>```

Output looks like below:

Can anyone please guide me how to use the Query2 inside the pivot in Query1 to automate the dates.

答:
You need to use dynamic query, to get the pivot list dynamically

first assign the dates list to a variable.

```<code>Declare @pivot_list varchar(8000)= ''
DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016

;WITH N(N)     AS (SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
      tally(N) AS (SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
select @pivot_list = stuff((SELECT ','+quotename(convert(varchar(15),datefromparts(@year,@month,N),101))
                            FROM tally
                            WHERE N <= day(EOMONTH(datefromparts(@year,@month,1))) for xml path('')),1,1,'')

--Print @pivot_list
</code>```

Now use the @pivot_list variable in the pivot list

```<code>Declare @sql varchar(8000)
set @sql = '
SELECT *
FROM (
    SELECT Insurance, ChargeValue, CreatedDate
    FROM dailychargesummary
    WHERE MonthName='June 2017'
) m
PIVOT (
    SUM(ChargeValue)
    FOR CreatedDate IN ('+@pivot_list+')
) n'

--Print @sql

Exec @sql
</code>```

Body:
I m using SQL SERVER 2012.

Query:1

SELECT *
FROM (
    SELECT Insurance, ChargeValue, CreatedDate
    FROM dailychargesummary
    WHERE MonthName='June 2017'
) m
PIVOT (
    SUM(ChargeValue)
    FOR CreatedDate IN ([06/22/2017], [06/23/2017],[06/30/2017])
) n

Output of above query is looks like below:

Now I m hard coding all the dates of a month inside the Pivot Query such as 06/01/2017, 06/02/2017, etc., After searching in the Google, I got the following query to display all the dates of a given month number.

Query 2:

DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016

;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT datefromparts(@year,@month,N) date FROM tally
WHERE N <= day(EOMONTH(datefromparts(@year,@month,1)))

Output looks like below:

Can anyone please guide me how to use the Query2 inside the pivot in Query1 to automate the dates.

Body:
You need to use dynamic query, to get the pivot list dynamically

first assign the dates list to a variable.

Declare @pivot_list varchar(8000)= ''
DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016

;WITH N(N)     AS (SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
      tally(N) AS (SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
select @pivot_list = stuff((SELECT ','+quotename(convert(varchar(15),datefromparts(@year,@month,N),101))
                            FROM tally
                            WHERE N <= day(EOMONTH(datefromparts(@year,@month,1))) for xml path('')),1,1,'')

--Print @pivot_list

Now use the @pivot_list variable in the pivot list

Declare @sql varchar(8000)
set @sql = '
SELECT *
FROM (
    SELECT Insurance, ChargeValue, CreatedDate
    FROM dailychargesummary
    WHERE MonthName='June 2017'
) m
PIVOT (
    SUM(ChargeValue)
    FOR CreatedDate IN ('+@pivot_list+')
) n'

--Print @sql

Exec @sql


问:
Which is faster in mysql ? Multiple update queries in the same transaction, or a single query?
Which is faster? Multiple update queries in the same transaction, or a single query?

For example, in this case, which is faster?

```<code>UPDATE product p, productPrice pp
SET
p.name = newName,
pp.price = pp.price * 0.8
WHERE
p.productId = pp.productId
AND
p.productId = 1;
</code>```

Or this:

```<code>Update product set p.name = newName where productId = 1;
Update productPrice set price = price * 0.8 where productId = 1;
</code>```

Written in

```<code>a single transaction
</code>```

Should a lock be taken into consideration?

Any difference with their lock in mysql?

And

Any difference between the select queries and update queries situation ?

Thanks!

答:
The first one is faster because the record to be updated needs to be located only once.  Also, transactions don't make database operations faster, they just make sure they are either all executed or none, in case one fails.

Locks make no sense here and the same applies for select or update statements.

Body:
Which is faster? Multiple update queries in the same transaction, or a single query?

For example, in this case, which is faster?

UPDATE product p, productPrice pp
SET
p.name = newName,
pp.price = pp.price * 0.8
WHERE
p.productId = pp.productId
AND
p.productId = 1;

Or this:

Update product set p.name = newName where productId = 1;
Update productPrice set price = price * 0.8 where productId = 1;

Written in

a single transaction

Should a lock be taken into consideration?

Any difference with their lock in mysql?

And

Any difference between the select queries and update queries situation ?

Thanks!


问:
Providing alternative images if Adobe Flash isn't available
Are there any ways providing an alternate GIF/PNG image, in case the user has no Adobe Flash installed and/or deactivated.
I’ve found recommendations, like the following from W3C, which determine via JavaScript the existence of Adobe Flash on the client: W3C Providing alternative images

Honestly, I would prefer a non JS technique. I’m thinking of some XHTML tag, equivalent to . (like <noobject> if the object (in our case Flash) can’t be displayed/loaded).

The reason for needing this separation is the following:
The bank I’m working for will preferably display their banners in Flash format. In case it isn’t possible a simple image should be shown.
In the past it was solved very likely in the way mentioned before. We’re currently working on a design refresh and that’s where I stumbled upon this piece of code which makes me wonder if it’s really the most elegant and compatible way of doing so.

Another idea that strikes me: Is it actually possible to load Flash-objects in a JavaScript disabled environment?

答:
I don't know why you want to avoid javascript, it is the best solution when dealing with Flash.

using the SWFObjects Library (the best known so far for the matter) you can do this:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title> My Home Page </title>
 <meta name="viewport" content="width=780">
 <script type="text/javascript" src="swfobject.js"></script>
</head>
<body>
 <div id="splashintro">
   <a href="more.html"><img src="splash_noflash.png" /></a>
 </div>
 <script type="text/javascript">
   var so = new SWFObject("csplash.swf", "my_intro", "300", "240", "8", "#338899");
   so.write("splashintro");
 </script>
 </body>
</html>
</code>```

what the script does is replace the splashintro div with the flash file, if the browser does not support Flash, then does nothing and the splash_noflash.png will be shown.

P.S. With this technique you are ready for the iPhone, instead of showing the blue cube, it will show the image :)

OwnerDisplayName: Gerhard Dinhof

Body:
I don't know why you want to avoid javascript, it is the best solution when dealing with Flash.

using the SWFObjects Library (the best known so far for the matter) you can do this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title> My Home Page </title>
 <meta name="viewport" content="width=780">
 <script type="text/javascript" src="swfobject.js"></script>
</head>
<body>
 <div id="splashintro">
   <a href="more.html"><img src="splash_noflash.png" /></a>
 </div>
 <script type="text/javascript">
   var so = new SWFObject("csplash.swf", "my_intro", "300", "240", "8", "#338899");
   so.write("splashintro");
 </script>
 </body>
</html>

what the script does is replace the splashintro div with the flash file, if the browser does not support Flash, then does nothing and the splash_noflash.png will be shown.

P.S. With this technique you are ready for the iPhone, instead of showing the blue cube, it will show the image :)

OwnerDisplayName: balexandre


问:
Rejecting Incoming Calls Immediately Android
Can we block incoming phone calls in android before it reaches the phone application?
I have made an application to block incoming phone calls my problem is that even though the call is suspended immediately it pops up the calling screen for a second. Any suggestions how to avoid that inefficiency?
Also if there is a way to delete the phone call from the call history please let me know how to do it?

This is my main activity

```<code>    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_PHONE_STATE_GRANTED = 1;

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

    getPermission();

    }

    private void getPermission() {

      if (ContextCompat.checkSelfPermission(this,
      Manifest.permission.READ_PHONE_STATE) !=
      PackageManager.PERMISSION_GRANTED) {
          ActivityCompat.requestPermissions(this, new String[]
          {Manifest.permission.READ_PHONE_STATE},
        PERMISSION_REQUEST_PHONE_STATE_GRANTED);
      }
    }
</code>```

}

This is my CallReceiver class which extends BroadcastReceiver

```<code>    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.telephony.TelephonyManager;
    import com.android.internal.telephony.ITelephony;
    import java.lang.reflect.Method;

    public class CallReceiver extends BroadcastReceiver {

        private ITelephony telephonyService;

        @Override
        public void onReceive(Context context, Intent intent) {

            TelephonyManager telephony = (TelephonyManager)
                    context.getSystemService(Context.TELEPHONY_SERVICE);

            //make sure it's not an outgoing call
            if (telephony.getCallState() == 1) {
                try {
                    Class c = Class.forName(telephony.getClass().getName());
                    Method m = c.getDeclaredMethod("getITelephony");
                    m.setAccessible(true);
                    telephonyService = (ITelephony) m.invoke(telephony);
                    telephonyService.endCall();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
</code>```

This is my manifest file

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

        <uses-permission android:name="android.permission.CALL_PHONE" />
        <uses-permission
            android:name="android.permission.READ_PHONE_STATE"/>

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

            <receiver
                android:name=".CallReceiver"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action
                        android:name="android.intent.action.PHONE_STATE"/>
                </intent-filter>
            </receiver>

        </application>

    </manifest>
</code>```

And this is a picture of the popup screen (which pops up after the call is already suspended on the caller’s side)enter image description here

Ps
 I tried to add android priority but it didn’t help.

答: Relying on phone state to determine if there is an incoming call and then ending it via TelephonyManager is never going to be a reliable approach to implementing a call screening app of this nature.  The broadcasts for phone state are sent asynchronously while the system is busy doing all sorts of other things related to call setup.  So on some devices it might work, but on others there is a good chance it won't.</p>

Body:
Can we block incoming phone calls in android before it reaches the phone application?
I have made an application to block incoming phone calls my problem is that even though the call is suspended immediately it pops up the calling screen for a second. Any suggestions how to avoid that inefficiency?
Also if there is a way to delete the phone call from the call history please let me know how to do it?

This is my main activity

    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_PHONE_STATE_GRANTED = 1;

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

    getPermission();

    }

    private void getPermission() {

      if (ContextCompat.checkSelfPermission(this,
      Manifest.permission.READ_PHONE_STATE) !=
      PackageManager.PERMISSION_GRANTED) {
          ActivityCompat.requestPermissions(this, new String[]
          {Manifest.permission.READ_PHONE_STATE},
        PERMISSION_REQUEST_PHONE_STATE_GRANTED);
      }
    }

}

This is my CallReceiver class which extends BroadcastReceiver

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.telephony.TelephonyManager;
    import com.android.internal.telephony.ITelephony;
    import java.lang.reflect.Method;

    public class CallReceiver extends BroadcastReceiver {

        private ITelephony telephonyService;

        @Override
        public void onReceive(Context context, Intent intent) {

            TelephonyManager telephony = (TelephonyManager)
                    context.getSystemService(Context.TELEPHONY_SERVICE);

            //make sure it's not an outgoing call
            if (telephony.getCallState() == 1) {
                try {
                    Class c = Class.forName(telephony.getClass().getName());
                    Method m = c.getDeclaredMethod("getITelephony");
                    m.setAccessible(true);
                    telephonyService = (ITelephony) m.invoke(telephony);
                    telephonyService.endCall();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

This is my manifest file

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

        <uses-permission android:name="android.permission.CALL_PHONE" />
        <uses-permission
            android:name="android.permission.READ_PHONE_STATE"/>

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

            <receiver
                android:name=".CallReceiver"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action
                        android:name="android.intent.action.PHONE_STATE"/>
                </intent-filter>
            </receiver>

        </application>

    </manifest>

And this is a picture of the popup screen (which pops up after the call is already suspended on the caller’s side)enter image description here

Ps
 I tried to add android priority but it didn’t help.


问:
How do i reduce padding on codename one charts
How do i close the padding between chart title and the chart. See image attached

答: I would suggest placing the chart into a BoxLayout.Y_AXIS instead of what I assume is the center of a BorderLayout. The center of the BorderLayout stretches to take up available space and the chart aligns to the center. The box layout will give the chart the full width and its preferred height.


问:
I cannot move the items freely on layouts in Xamarin Android
I can drag and drop items but I cannot change the position of items on layouts in Xamarin</p>

答: If you use linear layout, items will be snapped to the grid. For a free moving, change the layout to a relative. </p>


问:
How retrieve current redux-form state field value in react class form component?
I have a react form component class containing two redux-form Fields. The form component is wrapped by reduxForm and a container component defining mapStateToProps, mapDispatchToProps functions. Each field is passed an onChange function defined in the form component.

I tried creating a selector on the form using formValueSelector, but the selected values don't update as the field values change.

How can I get the current state.form value of the other field in a onChange function?

I'm using:

"react": "^15.5.4",

"redux-form": "^6.8.0",

答:
Since redux-form questions tend to go unanswered at stackoverflow, I raised a redux-form issue: https://github.com/erikras/redux-form/issues/3110#issuecomment-312135987

This resulted in a couple of runnable examples of how to retrieve the current state.form value of a Field. Once you have that, you can pass it to an onChange function.


问:
Merging objects within an array and keeping the highest value for identical properties
I have this array and I would like to merge the objects within it.

```<code>[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]
</code>```

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }```

However, the properties are overwritten by other objects that have the same properties later in the parameters order

What I want is to keep the highest value available for the same property.

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.

答:
With vanilla javascript:

function getData(obj) {
    var d = {};
    for (var index in obj) {
        var item = obj[index];
        for (var k in item) {
            if (!d[k]) d[k] = item[k];
            else d[k] = Math.max(d[k], item[k]);
        }
    }
    console.log(d);
    return d;
}
getData([null, null, { "1": 1 }, { "2": 1 }, { "3": 1 }, { "2": 2 }, { "5": 1 }]);```

Body:
I have this array and I would like to merge the objects within it.

[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

However, the properties are overwritten by other objects that have the same properties later in the parameters order

What I want is to keep the highest value available for the same property.

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.


问:
Async task is stuck in a deadlock
I am trying to do an async task in xamarin studio ( c#) but i'm missing something about async/await. Here is my code. It never finishes this function.</p>

```<code>public static async Task<string> AsyncTask()
        {
            using (var client = new HttpClient())
            {
                var values = new Dictionary<string, string>
            {
                { "thing1", "this is the second time" },
                { "thing2", "world" }
            };

                var content =  new  FormUrlEncodedContent(values);

                var response = await client.PostAsync(DATA_SOURCE, content);

                var responseString = await response.Content.ReadAsStringAsync();
                System.Diagnostics.Debug.WriteLine("PART 2:" + responseString);
                _json = responseString;
                return _json;
            }

        }
</code>```

答:
It appears you may be calling this from a WPF or WinForms context. If I'm correct the following applies and is a common source of confusion:

When you await an async method call, by default it will continue on the captured context (the UI context if this is being called from UI code). In that case, the UI context is busy and is also captured and so a deadlock will occur.

What you should do is add .ConfigureAwait(false) to each awaited method call.

```<code>async MethodCall(...).ConfigureAwait(false);
</code>```

This will allow a different context to resume execution of the method after the async call completes, and thus will avoid the deadlock. Note: this is especially important for all library code to work in this manner so that it is safe to call from a UI context.

Many people wish this was the default behavior and that you would instead opt-in to force it to resume on the same context, but maintaining backward compatibility precluded that decision.

Title: Async task is stuck in a deadlock

Body:
I am trying to do an async task in xamarin studio ( c#) but i'm missing something about async/await. Here is my code. It never finishes this function.

public static async Task<string> AsyncTask()
        {
            using (var client = new HttpClient())
            {
                var values = new Dictionary<string, string>
            {
                { "thing1", "this is the second time" },
                { "thing2", "world" }
            };

                var content =  new  FormUrlEncodedContent(values);

                var response = await client.PostAsync(DATA_SOURCE, content);

                var responseString = await response.Content.ReadAsStringAsync();
                System.Diagnostics.Debug.WriteLine("PART 2:" + responseString);
                _json = responseString;
                return _json;
            }

        }

Body:
It appears you may be calling this from a WPF or WinForms context. If I'm correct the following applies and is a common source of confusion:

When you await an async method call, by default it will continue on the captured context (the UI context if this is being called from UI code). In that case, the UI context is busy and is also captured and so a deadlock will occur.

What you should do is add .ConfigureAwait(false) to each awaited method call.

async MethodCall(...).ConfigureAwait(false);

This will allow a different context to resume execution of the method after the async call completes, and thus will avoid the deadlock. Note: this is especially important for all library code to work in this manner so that it is safe to call from a UI context.

Many people wish this was the default behavior and that you would instead opt-in to force it to resume on the same context, but maintaining backward compatibility precluded that decision.


问:
Problems with pcolormesh in Cartopy
I'm trying to adapt the Cartopy example plot for circular South Polar Stereographic plots to the North Pole and add data to it. I have a couple questions.

First, in the example code, the land feature is added before the ocean feature. When I did that, I got a map with only ocean. I reversed the order of the call in the code below and get a map with land and ocean. Why did the other order work with the South Polar example?

Second, and more importantly, I can't figure out why my pcolormesh call isn't having any effect.

I'm using Python 2.7.7, matplotlib 1.5.1, and Cartopy 0.15.1.

```<code>import matplotlib.path as mpath
import matplotlib.pyplot as plt
import numpy as np

import cartopy.crs as ccrs
import cartopy.feature

lats = np.linspace(60,90,30)
lons = np.linspace(0,360,200)
X,Y = np.meshgrid(lons,lats)
Z = np.random.normal(size = X.shape)

def main():
    fig = plt.figure(figsize=[10, 5])
    ax = plt.subplot(1, 1, 1, projection=ccrs.NorthPolarStereo())
    fig.subplots_adjust(bottom=0.05, top=0.95,
                        left=0.04, right=0.95, wspace=0.02)

    # Limit the map to -60 degrees latitude and below.
    ax.set_extent([-180, 180, 60, 60], ccrs.PlateCarree())

    ax.gridlines()

    ax.add_feature(cartopy.feature.OCEAN)
    ax.add_feature(cartopy.feature.LAND)

    # Compute a circle in axes coordinates, which we can use as a boundary
    # for the map. We can pan/zoom as much as we like - the boundary will be
    # permanently circular.
    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)

    ax.set_boundary(circle, transform=ax.transAxes)
    ax.pcolormesh(X,Y,Z,transform=ccrs.PlateCarree())

    plt.show()

if __name__ == '__main__':
    main()
</code>```

答:
Your code leaves cartopy to dictate the order of feature plots on the map, as a result, some features can be hidden with no clues. It is possible to specify the order of plots explicitly.

The order of features plot is controlled by zorder, which can be specified with zorder=integer in most plotting statements. Here is a modified code that produces a better plot.

```<code># your data
lats = np.linspace(60, 90, 30)
lons = np.linspace(0, 360, 160)
X,Y = np.meshgrid(lons, lats)
Z = np.random.normal(size = X.shape)

# new data for pcolormesh plot
latz = np.linspace(75, 90, 15)
lonz = np.linspace(0, 360, 160)
X1,Y1 = np.meshgrid(lonz, latz)
Z1 = np.random.normal(size = X1.shape)

def main():
    fig = plt.figure(figsize=[10, 10])
    ax = plt.subplot(1, 1, 1, projection=ccrs.NorthPolarStereo())
    fig.subplots_adjust(bottom=0.05, top=0.95,
                        left=0.04, right=0.95, wspace=0.02)

    # Limit the map to -60 degrees latitude and below.
    ax.set_extent([-180, 180, 60, 60], ccrs.PlateCarree())

    ax.gridlines()

    # zorder can be used to arrange what is on top
    ax.add_feature(cartopy.feature.LAND, zorder=4)   # land is specified to plot above ...
    ax.add_feature(cartopy.feature.OCEAN, zorder=1)  # ... the ocean

    # Compute a circle in axes coordinates, which we can use as a boundary
    # for the map. We can pan/zoom as much as we like - the boundary will be
    # permanently circular.
    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)

    ax.set_boundary(circle, transform=ax.transAxes)
    # pcolormesh is specified to plot on top of the ocean but below land
    ax.pcolormesh(X1, Y1, Z1, transform=ccrs.PlateCarree(), zorder=3)

    plt.show()

if __name__ == '__main__':
    main()
</code>```

Title: Problems with pcolormesh in Cartopy

Body:
I'm trying to adapt the Cartopy example plot for circular South Polar Stereographic plots to the North Pole and add data to it. I have a couple questions.

First, in the example code, the land feature is added before the ocean feature. When I did that, I got a map with only ocean. I reversed the order of the call in the code below and get a map with land and ocean. Why did the other order work with the South Polar example?

Second, and more importantly, I can't figure out why my pcolormesh call isn't having any effect.

I'm using Python 2.7.7, matplotlib 1.5.1, and Cartopy 0.15.1.

import matplotlib.path as mpath
import matplotlib.pyplot as plt
import numpy as np

import cartopy.crs as ccrs
import cartopy.feature

lats = np.linspace(60,90,30)
lons = np.linspace(0,360,200)
X,Y = np.meshgrid(lons,lats)
Z = np.random.normal(size = X.shape)

def main():
    fig = plt.figure(figsize=[10, 5])
    ax = plt.subplot(1, 1, 1, projection=ccrs.NorthPolarStereo())
    fig.subplots_adjust(bottom=0.05, top=0.95,
                        left=0.04, right=0.95, wspace=0.02)

    # Limit the map to -60 degrees latitude and below.
    ax.set_extent([-180, 180, 60, 60], ccrs.PlateCarree())

    ax.gridlines()

    ax.add_feature(cartopy.feature.OCEAN)
    ax.add_feature(cartopy.feature.LAND)

    # Compute a circle in axes coordinates, which we can use as a boundary
    # for the map. We can pan/zoom as much as we like - the boundary will be
    # permanently circular.
    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)

    ax.set_boundary(circle, transform=ax.transAxes)
    ax.pcolormesh(X,Y,Z,transform=ccrs.PlateCarree())

    plt.show()

if __name__ == '__main__':
    main()

Body:
Your code leaves cartopy to dictate the order of feature plots on the map, as a result, some features can be hidden with no clues. It is possible to specify the order of plots explicitly.

The order of features plot is controlled by zorder, which can be specified with zorder=integer in most plotting statements. Here is a modified code that produces a better plot.

# your data
lats = np.linspace(60, 90, 30)
lons = np.linspace(0, 360, 160)
X,Y = np.meshgrid(lons, lats)
Z = np.random.normal(size = X.shape)

# new data for pcolormesh plot
latz = np.linspace(75, 90, 15)
lonz = np.linspace(0, 360, 160)
X1,Y1 = np.meshgrid(lonz, latz)
Z1 = np.random.normal(size = X1.shape)

def main():
    fig = plt.figure(figsize=[10, 10])
    ax = plt.subplot(1, 1, 1, projection=ccrs.NorthPolarStereo())
    fig.subplots_adjust(bottom=0.05, top=0.95,
                        left=0.04, right=0.95, wspace=0.02)

    # Limit the map to -60 degrees latitude and below.
    ax.set_extent([-180, 180, 60, 60], ccrs.PlateCarree())

    ax.gridlines()

    # zorder can be used to arrange what is on top
    ax.add_feature(cartopy.feature.LAND, zorder=4)   # land is specified to plot above ...
    ax.add_feature(cartopy.feature.OCEAN, zorder=1)  # ... the ocean

    # Compute a circle in axes coordinates, which we can use as a boundary
    # for the map. We can pan/zoom as much as we like - the boundary will be
    # permanently circular.
    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)

    ax.set_boundary(circle, transform=ax.transAxes)
    # pcolormesh is specified to plot on top of the ocean but below land
    ax.pcolormesh(X1, Y1, Z1, transform=ccrs.PlateCarree(), zorder=3)

    plt.show()

if __name__ == '__main__':
    main()


问:
Need faster method to replace colors in an image based on another color
I'm looking for a faster method of replacing colors in an image based on another color. For example, I have an image that is mostly black with shades of gray and I want to recolor it based on red. Right now I pass it into this function with black as my base color and red as my new color. Then I go pixel by pixel to determine its RGB and recalculate that to the new red shade. So pure black becomes pure red and grays become a lighter red and so on.

Is there a quicker way to do this? Possibly using a separate image manipulation library? I looked into ImageMagick but I can't find the exact functionality I'm looking for.

Here's my current function. It works but is slow.

```<code>Public Function doRecolorImage(ByRef inBMP As Bitmap, ByVal baseColor As Color, ByVal newColor As Color) As Bitmap
        Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)

            Using gIcons As Graphics = Graphics.FromImage(newimg)
                For x = 0 To inBMP.Width - 1
                    For y = 0 To inBMP.Height - 1
                        Dim ltrans As Byte = inBMP.GetPixel(x, y).A
                        Dim lR As Byte = inBMP.GetPixel(x, y).R
                        Dim lG As Byte = inBMP.GetPixel(x, y).G
                        Dim lB As Byte = inBMP.GetPixel(x, y).B

                        Dim newpixR As Integer = CInt(newColor.R) + (CInt(lR) - CInt(baseColor.R))

                        Dim newpixG As Integer = CInt(newColor.G) + (CInt(lG) - CInt(baseColor.G))

                        Dim newpixB As Integer = CInt(newColor.B) + (CInt(lB) - CInt(baseColor.B))

                        newimg.SetPixel(x, y, System.Drawing.Color.FromArgb(ltrans, newpixR, newpixG, newpixB))
                    Next
                Next
            End Using

        Return newimg

    End Function
</code>```

Here I tried using ColorMatrix but it didn't work, not sure why...maybe my understanding of how ColorMatrix works is wrong.

```<code>Public Function doNewRecolorImage(ByRef inBMP As Bitmap, ByVal baseColor As Color, ByVal newColor As Color) As Bitmap
        Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)

            Dim iaImageProps As New ImageAttributes

            Dim cmNewColors As ColorMatrix

            cmNewColors = New ColorMatrix(New Single()() _
                {New Single() {newColor.R / baseColor.R, 0, 0, 0, 0}, _
                 New Single() {0, newColor.G / baseColor.G, 0, 0, 0}, _
                 New Single() {0, 0, newColor.B / baseColor.B, 0, 0}, _
                 New Single() {0, 0, 0, 1, 0}, _
                 New Single() {0, 0, 0, 0, 1}})

            iaImageProps.SetColorMatrix(cmNewColors)

            Using g As Graphics = Graphics.FromImage(newimg)
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
                g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, iaImageProps)
            End Using

        Return newimg

    End Function
</code>```

UPDATE 1:

Here's my updated function based on Ryan's answer below. It runs but it isn't returning the expected recolored image. The image is one solid color...the base color. So I'm passing in the base color and the new color and getting the result. However, the result should be the new color (dark blue) because the image is a solid color so it should be an exact color swap.

```<code>Private Function calcColorSwap(_base As Byte, _new As Byte) As Single
    If _new > _base Then
        Return (CInt(_new) - CInt(_base)) / 255.0!
    Else
        Return (CInt(_base) - CInt(_new)) / 255.0!
    End If
End Function

Public Function doNewRecolorImage(inBMP As Bitmap, baseColor As Color, newColor As Color) As Bitmap
    Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)
    Dim transformation As New ColorMatrix(New Single()() {
          New Single() {1, 0, 0, 0, 0},
          New Single() {0, 1, 0, 0, 0},
          New Single() {0, 0, 1, 0, 0},
          New Single() {0, 0, 0, 1, 0},
          New Single() {calcColorSwap(baseColor.R, newColor.R), calcColorSwap(baseColor.G, newColor.G), calcColorSwap(baseColor.B, newColor.B), 0, 1}
      })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Using g As Graphics = Graphics.FromImage(newimg)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

Return newimg

End Function
</code>```

UPDATE 2 (SOLUTION):

Here's the solution: based on Ryan's answer below.

```<code>Private Function calcColorSwap(_base As Byte, _new As Byte) As Single
        Return (CInt(_new) - CInt(_base)) / 255.0!
End Function

Public Function doNewRecolorImage(inBMP As Bitmap, baseColor As Color, newColor As Color) As Bitmap
    Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)
    Dim transformation As New ColorMatrix(New Single()() {
          New Single() {1, 0, 0, 0, 0},
          New Single() {0, 1, 0, 0, 0},
          New Single() {0, 0, 1, 0, 0},
          New Single() {0, 0, 0, 1, 0},
          New Single() {calcColorSwap(baseColor.R, newColor.R), calcColorSwap(baseColor.G, newColor.G), calcColorSwap(baseColor.B, newColor.B), 0, 1}
      })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Using g As Graphics = Graphics.FromImage(newimg)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

Return newimg

End Function
</code>```

答:
In ImageMagick, you can do

```<code>convert gray.png \( -clone 0 -fill red -colorize 100 \) \( -clone 0 -negate \) -compose colorize -composite red.png
</code>```

I answered a similar question here (without the negate) Re-coloring image preserving luminance

Another approach in ImageMagick that is simpler and may be more what you want is:

```<code>convert gray.png +level-colors red,white red.png
</code>```

see http://www.imagemagick.org/Usage/color_mods/#level-colors

Body:
I'm looking for a faster method of replacing colors in an image based on another color. For example, I have an image that is mostly black with shades of gray and I want to recolor it based on red. Right now I pass it into this function with black as my base color and red as my new color. Then I go pixel by pixel to determine its RGB and recalculate that to the new red shade. So pure black becomes pure red and grays become a lighter red and so on.

Is there a quicker way to do this? Possibly using a separate image manipulation library? I looked into ImageMagick but I can't find the exact functionality I'm looking for.

Here's my current function. It works but is slow.

Public Function doRecolorImage(ByRef inBMP As Bitmap, ByVal baseColor As Color, ByVal newColor As Color) As Bitmap
        Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)

            Using gIcons As Graphics = Graphics.FromImage(newimg)
                For x = 0 To inBMP.Width - 1
                    For y = 0 To inBMP.Height - 1
                        Dim ltrans As Byte = inBMP.GetPixel(x, y).A
                        Dim lR As Byte = inBMP.GetPixel(x, y).R
                        Dim lG As Byte = inBMP.GetPixel(x, y).G
                        Dim lB As Byte = inBMP.GetPixel(x, y).B

                        Dim newpixR As Integer = CInt(newColor.R) + (CInt(lR) - CInt(baseColor.R))

                        Dim newpixG As Integer = CInt(newColor.G) + (CInt(lG) - CInt(baseColor.G))

                        Dim newpixB As Integer = CInt(newColor.B) + (CInt(lB) - CInt(baseColor.B))

                        newimg.SetPixel(x, y, System.Drawing.Color.FromArgb(ltrans, newpixR, newpixG, newpixB))
                    Next
                Next
            End Using

        Return newimg

    End Function

Here I tried using ColorMatrix but it didn't work, not sure why...maybe my understanding of how ColorMatrix works is wrong.

Public Function doNewRecolorImage(ByRef inBMP As Bitmap, ByVal baseColor As Color, ByVal newColor As Color) As Bitmap
        Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)

            Dim iaImageProps As New ImageAttributes

            Dim cmNewColors As ColorMatrix

            cmNewColors = New ColorMatrix(New Single()() _
                {New Single() {newColor.R / baseColor.R, 0, 0, 0, 0}, _
                 New Single() {0, newColor.G / baseColor.G, 0, 0, 0}, _
                 New Single() {0, 0, newColor.B / baseColor.B, 0, 0}, _
                 New Single() {0, 0, 0, 1, 0}, _
                 New Single() {0, 0, 0, 0, 1}})

            iaImageProps.SetColorMatrix(cmNewColors)

            Using g As Graphics = Graphics.FromImage(newimg)
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
                g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, iaImageProps)
            End Using

        Return newimg

    End Function

UPDATE 1:

Here's my updated function based on Ryan's answer below. It runs but it isn't returning the expected recolored image. The image is one solid color...the base color. So I'm passing in the base color and the new color and getting the result. However, the result should be the new color (dark blue) because the image is a solid color so it should be an exact color swap.

Private Function calcColorSwap(_base As Byte, _new As Byte) As Single
    If _new > _base Then
        Return (CInt(_new) - CInt(_base)) / 255.0!
    Else
        Return (CInt(_base) - CInt(_new)) / 255.0!
    End If
End Function

Public Function doNewRecolorImage(inBMP As Bitmap, baseColor As Color, newColor As Color) As Bitmap
    Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)
    Dim transformation As New ColorMatrix(New Single()() {
          New Single() {1, 0, 0, 0, 0},
          New Single() {0, 1, 0, 0, 0},
          New Single() {0, 0, 1, 0, 0},
          New Single() {0, 0, 0, 1, 0},
          New Single() {calcColorSwap(baseColor.R, newColor.R), calcColorSwap(baseColor.G, newColor.G), calcColorSwap(baseColor.B, newColor.B), 0, 1}
      })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Using g As Graphics = Graphics.FromImage(newimg)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

Return newimg

End Function

UPDATE 2 (SOLUTION):

Here's the solution: based on Ryan's answer below.

Private Function calcColorSwap(_base As Byte, _new As Byte) As Single
        Return (CInt(_new) - CInt(_base)) / 255.0!
End Function

Public Function doNewRecolorImage(inBMP As Bitmap, baseColor As Color, newColor As Color) As Bitmap
    Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)
    Dim transformation As New ColorMatrix(New Single()() {
          New Single() {1, 0, 0, 0, 0},
          New Single() {0, 1, 0, 0, 0},
          New Single() {0, 0, 1, 0, 0},
          New Single() {0, 0, 0, 1, 0},
          New Single() {calcColorSwap(baseColor.R, newColor.R), calcColorSwap(baseColor.G, newColor.G), calcColorSwap(baseColor.B, newColor.B), 0, 1}
      })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Using g As Graphics = Graphics.FromImage(newimg)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

Return newimg

End Function

Body:
In ImageMagick, you can do

convert gray.png \( -clone 0 -fill red -colorize 100 \) \( -clone 0 -negate \) -compose colorize -composite red.png

I answered a similar question here (without the negate) Re-coloring image preserving luminance

Another approach in ImageMagick that is simpler and may be more what you want is:

convert gray.png +level-colors red,white red.png

see http://www.imagemagick.org/Usage/color_mods/#level-colors


问:
How do you alter the size of a Pytorch Dataset?
Say I am loading MNIST from torchvision.datasets.MNIST, but I only want to load in 10000 images total, how would I slice the data to limit it to only some number of data points?  I understand that the DataLoader is a generator yielding data in the size of the specified batch size, but how do you slice datasets?

```<code>tr = datasets.MNIST('../data', train=True, download=True, transform=transform)
te = datasets.MNIST('../data', train=False, transform=transform)
train_loader = DataLoader(tr, batch_size=args.batch_size, shuffle=True, num_workers=4, **kwargs)
test_loader = DataLoader(te, batch_size=args.batch_size, shuffle=True, num_workers=4, **kwargs)
</code>```

答:
It is important to note that when you create the DataLoader object, it doesnt immediately load all of your data (its impractical for large datasets). It provides you an iterator that you can use to access each sample.

Unfortunately, DataLoader doesnt provide you with any way to control the number of samples you wish to extract. You will have to use the typical ways of slicing iterators.

Simplest thing to do (without any libraries) would be to stop after the required number of samples is reached.

```<code>nsamples = 10000
for i, image, label in enumerate(train_loader):
    if i > nsamples:
        break

    # Your training code here.
</code>```

Or, you could use itertools.islice to get the first 10k samples. Like so.

```<code>for image, label in itertools.islice(train_loader, stop=10000):

    # your training code here.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Say I am loading MNIST from torchvision.datasets.MNIST, but I only want to load in 10000 images total, how would I slice the data to limit it to only some number of data points?  I understand that the DataLoader is a generator yielding data in the size of the specified batch size, but how do you slice datasets?

tr = datasets.MNIST('../data', train=True, download=True, transform=transform)
te = datasets.MNIST('../data', train=False, transform=transform)
train_loader = DataLoader(tr, batch_size=args.batch_size, shuffle=True, num_workers=4, **kwargs)
test_loader = DataLoader(te, batch_size=args.batch_size, shuffle=True, num_workers=4, **kwargs)

Body:
It is important to note that when you create the DataLoader object, it doesnt immediately load all of your data (its impractical for large datasets). It provides you an iterator that you can use to access each sample.

Unfortunately, DataLoader doesnt provide you with any way to control the number of samples you wish to extract. You will have to use the typical ways of slicing iterators.

Simplest thing to do (without any libraries) would be to stop after the required number of samples is reached.

nsamples = 10000
for i, image, label in enumerate(train_loader):
    if i > nsamples:
        break

    # Your training code here.

Or, you could use itertools.islice to get the first 10k samples. Like so.

for image, label in itertools.islice(train_loader, stop=10000):

    # your training code here.


问:
how to use map function in a list using Javascript or Jquery
this is my HTMl,

   <select id="Select1" style="display:none" multiple="multiple" data-limit="7" wtx-context="5C3D486B-FBBF-4191-BDA3-C2F28323036B">
      <option></option>
      <option data-img-src="" value="728" data-img-label="10"></option>
      <option data-img-src="" data-img-label="11"></option>
      <option data-img-src="" value="730" data-img-label="12"></option>
   </select>

```
</div>
</div>
</p>

<p>has a <code>select</code> control that has a list associated to it. I want to map and get all image sources that has <code>thumbnail selected</code> class</p>

<p>I tried this but i get an empty array,</p>

```var list = $('.thumbnail').map(function () { return $(this).closest("img").attr("src"); }).get();

console.log(list.join(','))
```

答:
One of the simplest thing to do is put your criteria directly in jquery selector and select the image elements and process them. Here is the JS code.</p>

```<code>$('.thumbnail.selected > img').map(function() {return this.src;}).get().join(',');
</code>```

Body:
this is my HTMl,

   <select id="Select1" style="display:none" multiple="multiple" data-limit="7" wtx-context="5C3D486B-FBBF-4191-BDA3-C2F28323036B">
      <option></option>
      <option data-img-src="" value="728" data-img-label="10"></option>
      <option data-img-src="" data-img-label="11"></option>
      <option data-img-src="" value="730" data-img-label="12"></option>
   </select>

has a select control that has a list associated to it. I want to map and get all image sources that has thumbnail selected class

I tried this but i get an empty array,

var list = $('.thumbnail').map(function () { return $(this).closest("img").attr("src"); }).get();

console.log(list.join(','))

Body:
One of the simplest thing to do is put your criteria directly in jquery selector and select the image elements and process them. Here is the JS code.

$('.thumbnail.selected > img').map(function() {return this.src;}).get().join(',');


问:
Beautifyrc SCSS adding new white line after closing curly brace
Can anyone help me out on how to add a new white space after each CSS-block (after the closing curly brace) by adjusting the settings for the beautifyrc-file?

the SCSS-problem:

```<code>.return-btn {
 background-color: #ACE514 !important;
 border: 0;
 border-bottom: 3px solid #1F8619 !important;
 border-radius: 0;
 font-size: 18px;
 margin: 50px 0 50px 0;
}
.return-btn:hover {
 background-color: #ACE514 !important;
 border-bottom: 3px solid #1F8619 !important;
}
</code>```

I want a new white space after the closing bracket of ".return-btn" when I beautify my .scss.

My current settings in the default.jsbeautifyrc:

```<code>{
"js": {
    "eol": "\n",
    "preserve_newlines": true,
    "max_preserve_newlines": 10,
    "space_after_anon_function": true,
    "brace_style": "collapse",
    "keep_array_indentation": true,
    "keep_function_indentation": false,
    "space_before_conditional": true,
    "break_chained_methods": false,
    "eval_code": false,
    "unescape_strings": false,
    "wrap_line_length": 0,
    "wrap_attributes": "auto",
    "end_with_newline": true,
    "comma_first": false
},
"css": {
    "allowed_file_extensions": ["css", "scss", "sass", "less"],
    "eol": "\\n",
    "end_with_newline": true,
    "selector_separator_newline": true,
    "newline_between_rules": true,
    "smartIndent": false,
    "indent_char": " ",
    "indent_size": 2,
    "selector_separator": " "
},
"html": {
    "eol": "\n",
    "end_with_newline": true,
    "preserve_newlines": true,
    "max_preserve_newlines": 10,
    "indent_inner_html": false,
    "brace_style": "collapse",
    "indent_scripts": "normal",
    "wrap_line_length": 0,
    "wrap_attributes": "auto"
}
}
</code>```

When i format the outputted css-file itself, a newline is added after each closing curly brace but not in the scss-file.

答: Seems like this feature isn't available now and already requested, see newline_between_rules support for Sass (enhancement) for more info.</p>

Body:
Can anyone help me out on how to add a new white space after each CSS-block (after the closing curly brace) by adjusting the settings for the beautifyrc-file?

the SCSS-problem:

.return-btn {
 background-color: #ACE514 !important;
 border: 0;
 border-bottom: 3px solid #1F8619 !important;
 border-radius: 0;
 font-size: 18px;
 margin: 50px 0 50px 0;
}
.return-btn:hover {
 background-color: #ACE514 !important;
 border-bottom: 3px solid #1F8619 !important;
}

I want a new white space after the closing bracket of ".return-btn" when I beautify my .scss.

My current settings in the default.jsbeautifyrc:

{
"js": {
    "eol": "\n",
    "preserve_newlines": true,
    "max_preserve_newlines": 10,
    "space_after_anon_function": true,
    "brace_style": "collapse",
    "keep_array_indentation": true,
    "keep_function_indentation": false,
    "space_before_conditional": true,
    "break_chained_methods": false,
    "eval_code": false,
    "unescape_strings": false,
    "wrap_line_length": 0,
    "wrap_attributes": "auto",
    "end_with_newline": true,
    "comma_first": false
},
"css": {
    "allowed_file_extensions": ["css", "scss", "sass", "less"],
    "eol": "\\n",
    "end_with_newline": true,
    "selector_separator_newline": true,
    "newline_between_rules": true,
    "smartIndent": false,
    "indent_char": " ",
    "indent_size": 2,
    "selector_separator": " "
},
"html": {
    "eol": "\n",
    "end_with_newline": true,
    "preserve_newlines": true,
    "max_preserve_newlines": 10,
    "indent_inner_html": false,
    "brace_style": "collapse",
    "indent_scripts": "normal",
    "wrap_line_length": 0,
    "wrap_attributes": "auto"
}
}

When i format the outputted css-file itself, a newline is added after each closing curly brace but not in the scss-file.


问:
sort word in alphabet order in C
Below code is for a test sample given in https://www.testdome.com/for-developers/solve-question/9621

The question is:
Implement function sort_words that can sort an array of words which contain lowercase characters from english alphabet, in descending order.

For example, the array { "cherry", "orange", "apple" } should, after sorting, become { "orange", "cherry", "apple" }.

My code is:

```<code>#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void sort_words(char *words[], int count)
{
    char *x;

    for (int i = 0; i<count; i++)
    {
        for (int j = i + 1; j<count; j++)
        {
            if ((char)(*words[i]) < (char)(*words[j]))
            {
                x = words[j];
                words[j] = words[i];
                words[i] = x;
            }
        }

    }
}

#ifndef RunTests
int main()
{
    char *words[] = { "cherry", "orange", "apple" };

    sort_words(words, 3);

    for (int i = 0; i < 3; i++)
    {
        printf("%s ", words[i]);
    }
}
#endif
</code>```

Result is correct, but the system notices the fail information "Performance test on a dictionary: Time limit exceeded"

Why this error happens and how to solve this problem? Thanks!

答:
This is because the algorithm you are using is not efficient in terms of time complexity. The on eyou use is very trivial. It would no doubt sort the input, but would incur a lot of time when the input data set is huge. Try using some other sorting algorithm like - mergesort, quicksort, etc. These will do the same work in lesser time.
Refer how these algorithms work and try implementing them - https://www.tutorialspoint.com/data_structures_algorithms/sorting_algorithms.htm

Title: sort word in alphabet order in C

Body:
Below code is for a test sample given in https://www.testdome.com/for-developers/solve-question/9621

The question is:
Implement function sort_words that can sort an array of words which contain lowercase characters from english alphabet, in descending order.

For example, the array { "cherry", "orange", "apple" } should, after sorting, become { "orange", "cherry", "apple" }.

My code is:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void sort_words(char *words[], int count)
{
    char *x;

    for (int i = 0; i<count; i++)
    {
        for (int j = i + 1; j<count; j++)
        {
            if ((char)(*words[i]) < (char)(*words[j]))
            {
                x = words[j];
                words[j] = words[i];
                words[i] = x;
            }
        }

    }
}

#ifndef RunTests
int main()
{
    char *words[] = { "cherry", "orange", "apple" };

    sort_words(words, 3);

    for (int i = 0; i < 3; i++)
    {
        printf("%s ", words[i]);
    }
}
#endif

Result is correct, but the system notices the fail information "Performance test on a dictionary: Time limit exceeded"

Why this error happens and how to solve this problem? Thanks!


问:
how to print proper error message
I have following small shell script.

```<code>value='testdir/imp'
`mkdir -m 755 $value`
echo $
</code>```

the out put is

```<code>$ ./dir.sh
mkdir: Failed to make directory "testdir/imp"; Permission denied
2
</code>```

Here i want to print this error message to a text file
How i can do this

答:
In your case

```<code>$ ./dir.sh 2 > log.file
</code>```

should put you error message in the file log.file

Title: how to print proper error message

Body:
I have following small shell script.

value='testdir/imp'
`mkdir -m 755 $value`
echo $

the out put is

$ ./dir.sh
mkdir: Failed to make directory "testdir/imp"; Permission denied
2

Here i want to print this error message to a text file
How i can do this

Body:
In your case

$ ./dir.sh 2 > log.file

should put you error message in the file log.file


问:
show statusbar and change color
I am trying to get my activity to show my status bar.

without statusbar

The style of my activity is like this:

```<code><resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppBaseTheme" parent="Theme.AppCompat">
</style>

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/ActionBarTheme</item>
    <item name="android:actionMenuTextColor">@color/ifix_gray_dark</item>
    <item name="android:typeface">serif</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="colorControlActivated">@color/white</item>

    <item name="actionBarStyle">@style/ActionBarTheme</item>
    <item name="actionMenuTextColor">@color/ifix_gray_dark</item>
</style>

<style name="ActivityBar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="actionBarSize">35dp</item>
</style>

<style name="ActionBarTheme" parent="Widget.AppCompat.ActionBar">
    <item name="android:background">@drawable/actionbar_background</item>
    <item name="android:backgroundStacked">@drawable/actionbar_background</item>
    <item name="android:backgroundSplit">@drawable/actionbar_background</item>

    <item name="background">@drawable/actionbar_background</item>
    <item name="backgroundStacked">@drawable/actionbar_background</item>
    <item name="backgroundSplit">@drawable/actionbar_background</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="buttonTint">@color/rosa_iguana</item>
</style>
</resources>
</code>```

For Style v21 I have it:

```<code> <style name="ActivityBar" parent="Theme.AppTheme.NoActionBar">
    <item name="colorPrimaryDark">@color/black</item>
    <item name="android:statusBarColor">@color/black</item>
</style>
</code>```

I found this code to show my status bar but I painted it white

```<code>@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    hideSystemUI(hasFocus);
}

@TargetApi(Build.VERSION_CODES.KITKAT)
private void hideSystemUI(boolean hasFocus) {
    if (hasFocus) {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
    }
}
</code>```

example status bar white here

My Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.projextx">
    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />
    <!-- for card.io card scanning -->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- Added for MobileAppTracking -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true"
        android:xlargeScreens="true" />
    <application
        android:name=".Application"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@drawable/launcher_icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activities.SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.ActivitySelectCountry"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomeActivity"
            android:screenOrientation="portrait"
            android:theme="@style/ActivityBar"
            android:windowSoftInputMode="adjustPan"/>
        <activity
            android:name=".activities.ActivitySegment"
            android:screenOrientation="portrait"/>
        <activity
            android:name=".activities.ActivityProductDetail"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".activities.ActivityPagerPagoOption"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan" />
    </application>
</manifest>
</code>```

And I really would like some solution with in the styles because this I have to apply it to 2 more activities.

Thanks for the help.

答:
I solved this problem by including this same base them in values\styles and v21\styles like this.

```<code>  <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>
</code>```

Since theme used in your v21\style is different, change it to same base theme as like in values\styles. Hope this may Help you because I has solved this problem in the same way I described above.

Title: show statusbar and change color

Body:
I am trying to get my activity to show my status bar.

without statusbar

The style of my activity is like this:

<resources xmlns:android="http://schemas.android.com/apk/res/android">

</resources>

For Style v21 I have it:

I found this code to show my status bar but I painted it white

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    hideSystemUI(hasFocus);
}

@TargetApi(Build.VERSION_CODES.KITKAT)
private void hideSystemUI(boolean hasFocus) {
    if (hasFocus) {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
    }
}

example status bar white here

My Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.projextx">
    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true"
        android:xlargeScreens="true" />
    <application
        android:name=".Application"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@drawable/launcher_icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activities.SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.ActivitySelectCountry"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomeActivity"
            android:screenOrientation="portrait"
            android:theme="@style/ActivityBar"
            android:windowSoftInputMode="adjustPan"/>
        <activity
            android:name=".activities.ActivitySegment"
            android:screenOrientation="portrait"/>
        <activity
            android:name=".activities.ActivityProductDetail"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".activities.ActivityPagerPagoOption"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan" />
    </application>
</manifest>

And I really would like some solution with in the styles because this I have to apply it to 2 more activities.

Thanks for the help.

Body:
I solved this problem by including this same base them in values\styles and v21\styles like this.

  <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

Since theme used in your v21\style is different, change it to same base theme as like in values\styles. Hope this may Help you because I has solved this problem in the same way I described above.


问:
How to destroy session within 1 minute?
I try atmost but I failed to destroy session within in 1 minute. I am using PHP destroy code which is given below but it is not working.</p>

```<code><?php
    session_start();
    $_SESSION['start'] = "start session";
    if(isset($_POST['destroy'])){
        session_cache_expire(1);
    }
?>
</code>```

答:
```<code>session_start();

// 1 mins in seconds
$inactive = 60;

$session_life = time() - $_session['timeout'];

if($session_life > $inactive)
{  session_destroy(); header("Location: logoutpage.php");     }

S_session['timeout']=time();
</code>```

refer this link

or you can use

```<code>ini_set('session.gc_maxlifetime',1);
</code>```

Title: How to destroy session within 1 minute?

Body:
I try atmost but I failed to destroy session within in 1 minute. I am using PHP destroy code which is given below but it is not working.

<?php
    session_start();
    $_SESSION['start'] = "start session";
    if(isset($_POST['destroy'])){
        session_cache_expire(1);
    }
?>

Body:
session_start();

// 1 mins in seconds
$inactive = 60;

$session_life = time() - $_session['timeout'];

if($session_life > $inactive)
{  session_destroy(); header("Location: logoutpage.php");     }

S_session['timeout']=time();

refer this link

or you can use

ini_set('session.gc_maxlifetime',1);