问:
How should I create a URL such /api/resource/identifier/resource/identifier
I have a page with categories and page with goods for each category. How should I divide my api endpoints?

is that correct to use something like this:

'/api/categories'

'/api/categories/:categoryId'

'/api/categories/:categoryId/goods'

'/api/categories/:categoryId/goods/:itemId'

or should I use structure like:

'/api/categories'

'/api/categories/:categoryId'

'/api/goods'

'/api/goods/:itemId'

答:
Both answers are correct. There is usually no clear answer to questions like that. You can use one style of URLs, you can use the other style, or you can even use both with either the same resources available with two URL or with redirects.

The style of /api/categories/:categoryId/goods/:itemId has an advantage of nice hierarchy and more information in the URL itself.

But the style of /api/goods/:itemId has an advantage of being able to move goods between categories more easily, or even supporting multiple categories per item or adding tags in the future etc.

This is really something that you have to decide yourself, not only basing your decision on what URL seems better in itself but also considering your particular usage of the API that you're developing - like e.g. how likely it is to change categories, or how likely it is to access the goods without knowing the categories.

I recommend reading the tutorials about API design that were published by Stormpath. See:

https://stormpath.com/blog/fundamentals-rest-api-design

I particularly recommend watching the talks by Les Hazlewood that you can find on the Stormpath website, because he explains a lot of subtle topics like that.


来源: stackexchange

问:
how to use sumOf in cakephp by multiplying two column in cake php
I have a table that is look like below

I want to use sumOf on query by multiplying quantity and sub_total column
how to i solve this please help me

i am getting only sum of sub total by this

```<code>   $totalAmount = $this->OrderItems->find()->hydrate(false)->sumOf('sub_total');
</code>```

but i would like to multiply quantity and sub_total to making a virtual field for sumOf()

答:
There are several way. You can do it by creating a virtual field

Add those line in your model entity

```<code>// src/Model/Entity/OrderItems.php
protected $_virtual = ['gtotal'];

    protected function _getGtotal(){
        return $this->_properties['quantity'] * $this->_properties['sub_total'];
    }
</code>```

then you can call it from anywhere by using gtotal field

like

```<code>$totalAmount = $this->OrderItems->find()

foreach ($totalAmount as $key => $amount) {
    echo $amount->gtotal;
}
</code>```

For more check Creating Virtual Properties

ContentLicense: CC BY-SA 3.0

Body:
I have a table that is look like below

I want to use sumOf on query by multiplying quantity and sub_total column
how to i solve this please help me

i am getting only sum of sub total by this

   $totalAmount = $this->OrderItems->find()->hydrate(false)->sumOf('sub_total');

but i would like to multiply quantity and sub_total to making a virtual field for sumOf()

Body:
There are several way. You can do it by creating a virtual field

Add those line in your model entity

// src/Model/Entity/OrderItems.php
protected $_virtual = ['gtotal'];

    protected function _getGtotal(){
        return $this->_properties['quantity'] * $this->_properties['sub_total'];
    }

then you can call it from anywhere by using gtotal field

like

$totalAmount = $this->OrderItems->find()

foreach ($totalAmount as $key => $amount) {
    echo $amount->gtotal;
}

For more check Creating Virtual Properties


问:
How to add a icon inside a spinner
I'm able to do this if I'm able to freely modify the html, but the problem is I'm restricted to using a this one specific layout to make this spinner.

The spinner that I want to make is something like this,

There is the pink spinner which goes around and around the grey path and an icon in the middle which stays still.

The problem is I have to get the above spinner to work with just this html layout

Only a div

```<code><div class="spinner"></div>
</code>```

Div with an icon inside.

```<code><div class="spinner">
 <i class="mickey"></i>
</div>
</code>```

An icon font or an image can be used for the icon in the middle.

EDIT: Link to JSFiddle

答:
Here's my go

HTML

```<code><div class="loader-container">
    <span>icon</span>
    <div class="loader"></div>
</div>
</code>```

CSS

```<code> .loader {
    border: 16px solid #f3f3f3;
    /* Light grey */
    border-top: 16px solid #3498db;
    /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
 }

 .loader-container {
    position: relative;
    display: inline-block;
 }

 .loader-container span {
    position: absolute;
    top: 45%;
    left: 45%;
 }

 @keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
 }
</code>```

Codepen

Title: How to add a icon inside a spinner

Body:
I'm able to do this if I'm able to freely modify the html, but the problem is I'm restricted to using a this one specific layout to make this spinner.

The spinner that I want to make is something like this,

There is the pink spinner which goes around and around the grey path and an icon in the middle which stays still.

The problem is I have to get the above spinner to work with just this html layout

Only a div

Div with an icon inside.

An icon font or an image can be used for the icon in the middle.

EDIT: Link to JSFiddle

Body:
Here's my go

HTML

<div class="loader-container">
    <span>icon</span>
    <div class="loader"></div>
</div>

CSS

 .loader {
    border: 16px solid #f3f3f3;
    /* Light grey */
    border-top: 16px solid #3498db;
    /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
 }

 .loader-container {
    position: relative;
    display: inline-block;
 }

 .loader-container span {
    position: absolute;
    top: 45%;
    left: 45%;
 }

 @keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
 }

Codepen


问:
Inserting values into a Hash for YAML dump
I'm creating a hash that will eventually be dumped on disk in YAML, but I need to capture multiple values stored in a file on disk and insert them into a hash.  I can successfully create a variable with comma separated values, but I need to insert those values into a my "classes" key:

```<code>variable_values = "class1,class2,class3"
</code>```

Ultimately, I need to get them into my test hash so it simulates something like this:

```<code>test_hash = {'Classes' => ['class1', 'class2', 'class3']}
</code>```

Finally, I can output them to yaml so it looks like this:

```<code>---
classes:
- class1
- class2
- class3
</code>```

What's the best way to iterate through the values and insert them into the hash? Thanks for any help you can offer!

答:
You'd probably want something like:</p>

```<code>test_hash = {'Classes' => variable_values.split(',')}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm creating a hash that will eventually be dumped on disk in YAML, but I need to capture multiple values stored in a file on disk and insert them into a hash.  I can successfully create a variable with comma separated values, but I need to insert those values into a my "classes" key:

variable_values = "class1,class2,class3"

Ultimately, I need to get them into my test hash so it simulates something like this:

test_hash = {'Classes' => ['class1', 'class2', 'class3']}

Finally, I can output them to yaml so it looks like this:

---
classes:
- class1
- class2
- class3

What's the best way to iterate through the values and insert them into the hash? Thanks for any help you can offer!

Body:
You'd probably want something like:

test_hash = {'Classes' => variable_values.split(',')}


问:
Hide navigation when at the top
Hello how can i hide my navigation when not scrolling and show it when i scroll

i am using two menus at this link http://dev.thegabrielmethod.com/gabriel/

one on a white bg and the other on a blue bg

i would like to hide the navigation menu items on the white bg when not scrolling and then show them again when scrolling

This is what am trying which is not working

```<code><script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
        var headerTop = $('#header').offset().top;
        var headerBottom = headerTop + 120; // Sub-menu should appear after this distance from top.
        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop(); // Current vertical scroll position from the top
            if (scrollTop > headerBottom) { // Check to see if we have scrolled more than headerBottom
                if (($("#navigation-alongside").is(":visible") === false)) {
                    $('#navigation-alongside').fadeIn('slow');
                }
            } else {
                if ($("#navigation-alongside").is(":visible")) {
                    $('#navigation-alongside').hide();
                }
            }
        });
    });

</script>
</code>```

Please some one advice

答:
I hope this code will resolve your issue

jQuery(window).scroll(function (event) {
    var scroll = jQuery(window).scrollTop();
    console.log(scroll);
if(scroll==0){
 jQuery('.include-nav').hide();
  jQuery('.nav-bar-below.op-page-header').css('margin-top','0px');
}else{
  jQuery('.include-nav').show();
  jQuery('.nav-bar-below.op-page-header').css('margin-top','100px');
}
});```

Title: Hide navigation when at the top

Body:
Hello how can i hide my navigation when not scrolling and show it when i scroll

i am using two menus at this link http://dev.thegabrielmethod.com/gabriel/

one on a white bg and the other on a blue bg

i would like to hide the navigation menu items on the white bg when not scrolling and then show them again when scrolling

This is what am trying which is not working

Please some one advice


问:
How can I hide and show ion-tabs conditionally in ionic2?
I have 5 tabs

```<code><ion-tabs tabsPlacement="bottom" tabsLayout="icon-top" tabsHighlight="true" color="primary">
  <ion-tab [root]="myCardsTabRoot" tabTitle="My Cards" tabIcon="ios-photos"></ion-tab>
  <ion-tab [root]="calendarTabRoot" tabTitle="Calendar" tabIcon="calendar"></ion-tab>
  <ion-tab [root]="myProfileTabRoot" tabTitle="My Profile" tabIcon="ios-person"></ion-tab>
  <ion-tab [root]="searchTabRoot" tabTitle="Search" tabIcon="ios-search"></ion-tab>
  <ion-tab [root]="pendingRequestsTabRoot" tabTitle="Follow Req" tabIcon="notifications" tabBadge="{{pendingRequests}}" tabBadgeStyle="danger"></ion-tab>
</ion-tabs>
</code>```

I want to show last tab only if there is any pending requests, I tried below but still no chance and doesn't show/hide tab when pendingRequests value is changing,
value of pendingRequests is changed in ionViewDidEnter()

```<code>  <div *ngIf="pendingRequests > 0">
    <ion-tab [root]="pendingRequestsTabRoot" tabTitle="Follow Req" tabIcon="notifications" tabBadge="{{pendingRequests}}" tabBadgeStyle="danger"></ion-tab>
  </div>
</code>```

and

```<code><ion-tab *ngIf="pendingRequests > 0" [root]="pendingRequestsTabRoot" tabTitle="Follow Req" tabIcon="notifications" tabBadge="{{pendingRequests}}" tabBadgeStyle="danger"></ion-tab>
</code>```

If I restart app, tabs are displayed correctly based on the value of pendingRequests the only issue is that when the value is changed tabs doesn't hide/show correspondingly

here is the code for updating pendingRequests

```<code>  ionViewDidEnter() {
    this.refreshPrendingRequests();
  }

  refreshPrendingRequests() {
    this.contactsService.getContactRequestsCount(this.userInfoService.currentProfile.id)
      .subscribe(count => this.pendingRequests = count);
  }
</code>```

Update

Based on @Sampath suggestion, I create a plunker for it. The behavior is different than what I have it on my app, but also this one is not working too.

Clicking on top right toolbar button should show/hide tab
http://plnkr.co/edit/Cx6Pyr9AihvX66ASed0s?p=preview

答:
You can do that if you follow the below steps.The code is self-explanatory.If you need any help please comment below.

Note: This is just a working sample.Hope you can easily convert it to your use case.

You can play with this if you clone the Git Repo here.

I have used Ionic2 Event publish/subscribe pattern on this sample

Step 1: Create another tab page TabSet1Page

.ts

```<code>@Component({
  selector: 'page-tab-set1',
  templateUrl: 'tab-set1.html'
})
export class TabSet1Page {

  tab1Root: any = HomePage;
  tab2Root: any = AboutPage;

  constructor() { }

}
</code>```

.html

```<code><ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab>
</ion-tabs>
</code>```

Step 2:

app.component.ts

```<code>@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage: any = TabsPage;

  constructor(public events: Events) {

    this.subscribePendingRequests();//subscribe
    this.events.publish('pending-requests', 0);//publish
  }

  //subscribe
  subscribePendingRequests() {
    this.events.subscribe('pending-requests', (data) => {
      if (data > 0) {
        this.rootPage = TabSet1Page;
      }
      else {
        this.rootPage = TabsPage;
      }
    });
  }

}
</code>```

Step 3:

about.ts

```<code> @Component({
      selector: 'page-about',
      templateUrl: 'about.html'
    })
    export class AboutPage {

      constructor(public events: Events) { }

      //refresh
      refreshPendingRequests() {
        this.events.publish('pending-requests', 5);
      }
   }
</code>```

about.html

```<code><ion-header>
  <ion-navbar>
    <ion-title>
      About
    </ion-title>
     <ion-buttons end>
      <button ion-button icon-only (click)="refreshPendingRequests()">
        <ion-icon name="ios-funnel"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
</code>```

Body:
I have 5 tabs

<ion-tabs tabsPlacement="bottom" tabsLayout="icon-top" tabsHighlight="true" color="primary">
  <ion-tab [root]="myCardsTabRoot" tabTitle="My Cards" tabIcon="ios-photos"></ion-tab>
  <ion-tab [root]="calendarTabRoot" tabTitle="Calendar" tabIcon="calendar"></ion-tab>
  <ion-tab [root]="myProfileTabRoot" tabTitle="My Profile" tabIcon="ios-person"></ion-tab>
  <ion-tab [root]="searchTabRoot" tabTitle="Search" tabIcon="ios-search"></ion-tab>
  <ion-tab [root]="pendingRequestsTabRoot" tabTitle="Follow Req" tabIcon="notifications" tabBadge="{{pendingRequests}}" tabBadgeStyle="danger"></ion-tab>
</ion-tabs>

I want to show last tab only if there is any pending requests, I tried below but still no chance and doesn't show/hide tab when pendingRequests value is changing,
value of pendingRequests is changed in ionViewDidEnter()

 0">
    <ion-tab [root]="pendingRequestsTabRoot" tabTitle="Follow Req" tabIcon="notifications" tabBadge="{{pendingRequests}}" tabBadgeStyle="danger"></ion-tab>

and

<ion-tab *ngIf="pendingRequests > 0" [root]="pendingRequestsTabRoot" tabTitle="Follow Req" tabIcon="notifications" tabBadge="{{pendingRequests}}" tabBadgeStyle="danger"></ion-tab>

If I restart app, tabs are displayed correctly based on the value of pendingRequests the only issue is that when the value is changed tabs doesn't hide/show correspondingly

here is the code for updating pendingRequests

  ionViewDidEnter() {
    this.refreshPrendingRequests();
  }

  refreshPrendingRequests() {
    this.contactsService.getContactRequestsCount(this.userInfoService.currentProfile.id)
      .subscribe(count => this.pendingRequests = count);
  }

Update

Based on @Sampath suggestion, I create a plunker for it. The behavior is different than what I have it on my app, but also this one is not working too.

Clicking on top right toolbar button should show/hide tab
http://plnkr.co/edit/Cx6Pyr9AihvX66ASed0s?p=preview

Body:
You can do that if you follow the below steps.The code is self-explanatory.If you need any help please comment below.

Note: This is just a working sample.Hope you can easily convert it to your use case.

You can play with this if you clone the Git Repo here.

I have used Ionic2 Event publish/subscribe pattern on this sample

Step 1: Create another tab page TabSet1Page

.ts

@Component({
  selector: 'page-tab-set1',
  templateUrl: 'tab-set1.html'
})
export class TabSet1Page {

  tab1Root: any = HomePage;
  tab2Root: any = AboutPage;

  constructor() { }

}

.html

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab>
</ion-tabs>

Step 2:

app.component.ts

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage: any = TabsPage;

  constructor(public events: Events) {

    this.subscribePendingRequests();//subscribe
    this.events.publish('pending-requests', 0);//publish
  }

  //subscribe
  subscribePendingRequests() {
    this.events.subscribe('pending-requests', (data) => {
      if (data > 0) {
        this.rootPage = TabSet1Page;
      }
      else {
        this.rootPage = TabsPage;
      }
    });
  }

}

Step 3:

about.ts

 @Component({
      selector: 'page-about',
      templateUrl: 'about.html'
    })
    export class AboutPage {

      constructor(public events: Events) { }

      //refresh
      refreshPendingRequests() {
        this.events.publish('pending-requests', 5);
      }
   }

about.html

<ion-header>
  <ion-navbar>
    <ion-title>
      About
    </ion-title>
     <ion-buttons end>
      <button ion-button icon-only (click)="refreshPendingRequests()">
        <ion-icon name="ios-funnel"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>


问:
Using player's face from camera as a sprite in unity
Is there a way to get a picture of the player and then cropping the face for a sprite or something?
Like the apps that add your face to a body, but the face would be stored in some way.</p>

答:
Following this question answer, you can retrieve the picture from the Android Camera and save it as a texture. Then you use a Texture2D containing your mask (let's say a circle on the middle with alpha around it) to check which byte you want to save and which byte will be transparent. Don't forget to set this Texture2D import properties to Advanced and check Read/Write enabled. Finally you can load the newly created picture as a sprite using either Unity WWW class or System.IO.ReadAllBytes.

Here is a quick implementation of this:

```<code>[SerializeField]
private Texture2D maskTexture;

private WebCamTexture webCamTexture;

protected void Start()
{
    GetComponent<RawImage>().rectTransform.sizeDelta = new Vector2(maskTexture.width, maskTexture.height);

    webCamTexture = new WebCamTexture();
    GetComponent<Renderer>().material.mainTexture = webCamTexture;
    webCamTexture.Play();
}

public void SavePicture()
{
    StartCoroutine(SavePictureCoroutine());
}

private IEnumerator SavePictureCoroutine()
{
    yield return new WaitForEndOfFrame();

    RawImage rawImageToRead = GetComponent<RawImage>();

    //This is to save the current RenderTexture: RenderTexture.GetTemporary() and RenderTexture.ReleaseTemporary() can also be used
    RenderTexture previousRenderTexture = RenderTexture.active;
    RenderTexture.active = rawImageToRead.texture as RenderTexture;
    Texture2D renderedTexture = new Texture2D(maskTexture.width, maskTexture.height, TextureFormat.ARGB32, false);
    renderedTexture.ReadPixels(new Rect(Screen.width * 0.5f - maskTexture.width * 0.5f, Screen.height * 0.5f - maskTexture.height * 0.5f, renderedTexture.width, renderedTexture.height), 0, 0);
    renderedTexture.Apply();
    RenderTexture.active = previousRenderTexture;
    //----

    for(int i = 0; i < renderedTexture.width; i++)
    {
        for(int j = 0; j < renderedTexture.height; j++)
        {
            if(maskTexture.GetPixel(i, j).a > 0.5f)
            {
                renderedTexture.SetPixel(i, j, renderedTexture.GetPixel(i, j));
            }
            else
            {
                renderedTexture.SetPixel(i, j, new Color(0.0f, 0.0f, 0.0f, 0.0f));
            }
        }
    }
    renderedTexture.Apply();
    yield return renderedTexture;
    File.WriteAllBytes(Path.Combine(Application.dataPath, "YOUR_FILE_NAME"), renderedTexture.EncodeToPNG());
}
</code>```

(Warning: untested code)

Also keep in mind to try to provide what you already tried before asking questions: it helps other users understand what and how you want to achieve it.

Hope this helps,

Body:
Following this question answer, you can retrieve the picture from the Android Camera and save it as a texture. Then you use a Texture2D containing your mask (let's say a circle on the middle with alpha around it) to check which byte you want to save and which byte will be transparent. Don't forget to set this Texture2D import properties to Advanced and check Read/Write enabled. Finally you can load the newly created picture as a sprite using either Unity WWW class or System.IO.ReadAllBytes.

Here is a quick implementation of this:

[SerializeField]
private Texture2D maskTexture;

private WebCamTexture webCamTexture;

protected void Start()
{
    GetComponent<RawImage>().rectTransform.sizeDelta = new Vector2(maskTexture.width, maskTexture.height);

    webCamTexture = new WebCamTexture();
    GetComponent<Renderer>().material.mainTexture = webCamTexture;
    webCamTexture.Play();
}

public void SavePicture()
{
    StartCoroutine(SavePictureCoroutine());
}

private IEnumerator SavePictureCoroutine()
{
    yield return new WaitForEndOfFrame();

    RawImage rawImageToRead = GetComponent<RawImage>();

    //This is to save the current RenderTexture: RenderTexture.GetTemporary() and RenderTexture.ReleaseTemporary() can also be used
    RenderTexture previousRenderTexture = RenderTexture.active;
    RenderTexture.active = rawImageToRead.texture as RenderTexture;
    Texture2D renderedTexture = new Texture2D(maskTexture.width, maskTexture.height, TextureFormat.ARGB32, false);
    renderedTexture.ReadPixels(new Rect(Screen.width * 0.5f - maskTexture.width * 0.5f, Screen.height * 0.5f - maskTexture.height * 0.5f, renderedTexture.width, renderedTexture.height), 0, 0);
    renderedTexture.Apply();
    RenderTexture.active = previousRenderTexture;
    //----

    for(int i = 0; i < renderedTexture.width; i++)
    {
        for(int j = 0; j < renderedTexture.height; j++)
        {
            if(maskTexture.GetPixel(i, j).a > 0.5f)
            {
                renderedTexture.SetPixel(i, j, renderedTexture.GetPixel(i, j));
            }
            else
            {
                renderedTexture.SetPixel(i, j, new Color(0.0f, 0.0f, 0.0f, 0.0f));
            }
        }
    }
    renderedTexture.Apply();
    yield return renderedTexture;
    File.WriteAllBytes(Path.Combine(Application.dataPath, "YOUR_FILE_NAME"), renderedTexture.EncodeToPNG());
}

(Warning: untested code)

Also keep in mind to try to provide what you already tried before asking questions: it helps other users understand what and how you want to achieve it.

Hope this helps,


问:
Using Google OAuth 2 on embedded Android-based device
We have an application for embedded Android-based device, it uses WebView and inside it we use Google OAuth 2 to login to the app. Unfortunately Google will soon block OAuth 2 inside WebView, and we have lots of restrictions:

The device doesn't have Google Services installed, so probably no 'official' way of logging in would work (or maybe any of them would work without Google Services?)

We can't just invoke Android browser to do login, because it shows address bar, which would allow the user to surf the internet, which we can't allow

We don't fully control the software installed on the device: can't install Google Services, update Android version, install Google Chrome, etc..., we can just update our app.

What else could we do having those restrictions?

答:
Implementation through a browser:

1) Register custom URI scheme (How to implement my very own URI scheme on Android), for example, app-oauth2://

2) Make access request in user's browser

```<code>https://accounts.google.com/o/oauth2/v2/auth?
scope=...
access_type=offline&
include_granted_scopes=true&
state=state_parameter_passthrough_value&
redirect_uri=http://example.com/oauth2-handler&
response_type=code&
client_id=...
</code>```

3) If user accept or denied requested rights in the confirmation dialog, it will be redirected to redirect_uri (http://example.com/oauth2-handler) with some params

4) On the side of redirect_uri handler (http://example.com/oauth2-handler), mare a redirect to custom URI scheme with params:

Success: app-oauth2://?state=state_parameter_passthrough_value&code=...&scope=...#

Failure: app-oauth2://?error=access_denied&state=state_parameter_passthrough_value#

5) In your app you can parse URI scheme app-oauth2:// from option 4 and receive the code for future usage or error for displaying to the user.

Body:
Implementation through a browser:

1) Register custom URI scheme (How to implement my very own URI scheme on Android), for example, app-oauth2://

2) Make access request in user's browser

https://accounts.google.com/o/oauth2/v2/auth?
scope=...
access_type=offline&
include_granted_scopes=true&
state=state_parameter_passthrough_value&
redirect_uri=http://example.com/oauth2-handler&
response_type=code&
client_id=...

3) If user accept or denied requested rights in the confirmation dialog, it will be redirected to redirect_uri (http://example.com/oauth2-handler) with some params

4) On the side of redirect_uri handler (http://example.com/oauth2-handler), mare a redirect to custom URI scheme with params:

Success: app-oauth2://?state=state_parameter_passthrough_value&code=...&scope=...#

Failure: app-oauth2://?error=access_denied&state=state_parameter_passthrough_value#

5) In your app you can parse URI scheme app-oauth2:// from option 4 and receive the code for future usage or error for displaying to the user.


问:
jquery radio button check tick mark should be fired in the div
```<code>$(document).ready(function(){
  $('#gender').change(function(){
    var resultnill="";
    $("#stat5").html(resultnill);
    var result=$('input[type="radio"]:checked');
    if(result.length>0)
    {
      $("#stat5").append("<img src='tick.png'/>");
    }

  });
 });

<div class="form-group">
  <label for="gender" class="control-label col-xs-4">Gender:</label>
    <div class="col-xs-6">
    <label class="radio-inline"><input type="radio" name="gender" id="gender" value="M" required/>Male</label>
    <label class="radio-inline"><input type="radio" name="gender" id="gender" value="F" required/>Female</label>
    </div><div id="stat5"></div>
</div>
</code>```

when i check male radio button tick marks is appearing but if i check female tick box is not appearing.

答:
You have duplicate id gender, alternatively you can user a class or name on check box as:

HTML:

```<code><div class="form-group">
  <label for="gender" class="control-label col-xs-4">Gender:</label>
   <div class="col-xs-6">
    <label class="radio-inline"><input type="radio" name="gender" class="gender" value="M" required/>Male</label>
    <label class="radio-inline"><input type="radio" name="gender" class="gender" value="F" required/>Female</label>
   </div><div id="stat5"></div>
</div>
</code>```

JQUERY

```<code>$(document).ready(function(){
  $('.gender').change(function(){
   var resultnill="";
   $("#stat5").html(resultnill);
   var result=$('input[type=radio][name=gender]:checked');
   if(result.length>0)
   {
     //$("#stat5").append("<img src='tick.png'/>");
   }
 });
});
</code>```

DEMO HERE

Body:
$(document).ready(function(){
  $('#gender').change(function(){
    var resultnill="";
    $("#stat5").html(resultnill);
    var result=$('input[type="radio"]:checked');
    if(result.length>0)
    {
      $("#stat5").append("");
    }

  });
 });

  Gender:

    <input type="radio" name="gender" id="gender" value="M" required/>Male
    <input type="radio" name="gender" id="gender" value="F" required/>Female

when i check male radio button tick marks is appearing but if i check female tick box is not appearing.

Body:
You have duplicate id gender, alternatively you can user a class or name on check box as:

HTML:

<div class="form-group">
  <label for="gender" class="control-label col-xs-4">Gender:</label>
   <div class="col-xs-6">
    <label class="radio-inline"><input type="radio" name="gender" class="gender" value="M" required/>Male</label>
    <label class="radio-inline"><input type="radio" name="gender" class="gender" value="F" required/>Female</label>
   </div><div id="stat5"></div>
</div>

JQUERY

$(document).ready(function(){
  $('.gender').change(function(){
   var resultnill="";
   $("#stat5").html(resultnill);
   var result=$('input[type=radio][name=gender]:checked');
   if(result.length>0)
   {
     //$("#stat5").append("<img src='tick.png'/>");
   }
 });
});

DEMO HERE


问:
Find and tag a number between a range
I have two dfs as below

```<code>>codes1

Country       State                       City  Start No    End No
IN          Telangana                Hyderabad    100        200
IN        Maharashtra       Pune (Bund Garden)    300        400
IN            Haryana                  Gurgaon    500        600
IN        Maharashtra                     Pune    700        800
IN            Gujarat    Ahmedabad (Vastrapur)    900        1000
</code>```

Now i want to tag ip address from table 1

```<code>>codes2

ID     No
1      157
2      346
3      389
4      453
5      562
6      9874
7      98745
</code>```

Now i want to tag numbers in codes2 df as per the range given in codes1 df for No column , expected ouput is

```<code>ID     No    Country     State          City
1     157       IN      Telangana     Hyderabad
2     346       IN     Maharashtra   Pune(Bund Garden)
.
.
.
</code>```

Basically want to tag No column in codes 2 with codes1 according to the range (Start No and End No) that No observations falls in.

Also the order could be anything in codes 2 df .

答:
You could use the non-equi join capability of the data.table package for that:

```<code>library(data.table)
setDT(codes1)
setDT(codes2)

codes2[codes1, on = .(No > StartNo, No < EndNo),          ## (1)
       `:=`(cntry = Country, state = State, city = City)] ## (2)
</code>```

(1) obtains matching row indices in codes2 corresponding to each row in codes1, while matching on the condition provided to the on argument.

(2) updates codes2 values for those matching rows for the columns specified directly by reference (i.e., you don't have to assign the result back to another variable).

This gives:

```<code>codes2
#    ID    No  cntry       state               city
# 1:  1   157     IN   Telangana          Hyderabad
# 2:  2   346     IN Maharashtra Pune (Bund Garden)
# 3:  3   389     IN Maharashtra Pune (Bund Garden)
# 4:  4   453     NA          NA                 NA
# 5:  5   562     IN     Haryana            Gurgaon
# 6:  6  9874     NA          NA                 NA
# 7:  7 98745     NA          NA                 NA
</code>```

Title: Find and tag a number between a range

Body:
I have two dfs as below

>codes1

Country       State                       City  Start No    End No
IN          Telangana                Hyderabad    100        200
IN        Maharashtra       Pune (Bund Garden)    300        400
IN            Haryana                  Gurgaon    500        600
IN        Maharashtra                     Pune    700        800
IN            Gujarat    Ahmedabad (Vastrapur)    900        1000

Now i want to tag ip address from table 1

>codes2

ID     No
1      157
2      346
3      389
4      453
5      562
6      9874
7      98745

Now i want to tag numbers in codes2 df as per the range given in codes1 df for No column , expected ouput is

ID     No    Country     State          City
1     157       IN      Telangana     Hyderabad
2     346       IN     Maharashtra   Pune(Bund Garden)
.
.
.

Basically want to tag No column in codes 2 with codes1 according to the range (Start No and End No) that No observations falls in.

Also the order could be anything in codes 2 df .

Body:
You could use the non-equi join capability of the data.table package for that:

library(data.table)
setDT(codes1)
setDT(codes2)

codes2[codes1, on = .(No > StartNo, No < EndNo),          ## (1)
       `:=`(cntry = Country, state = State, city = City)] ## (2)

(1) obtains matching row indices in codes2 corresponding to each row in codes1, while matching on the condition provided to the on argument.

(2) updates codes2 values for those matching rows for the columns specified directly by reference (i.e., you don't have to assign the result back to another variable).

This gives:

codes2
#    ID    No  cntry       state               city
# 1:  1   157     IN   Telangana          Hyderabad
# 2:  2   346     IN Maharashtra Pune (Bund Garden)
# 3:  3   389     IN Maharashtra Pune (Bund Garden)
# 4:  4   453     NA          NA                 NA
# 5:  5   562     IN     Haryana            Gurgaon
# 6:  6  9874     NA          NA                 NA
# 7:  7 98745     NA          NA                 NA


问:
Why not a consolidated Copy constructor and Assignment operator available in C++?
I do understand the scenarios where the respective functions (Copy Constructor and Assignment operator) would be called. And both these functions are literally doing the same functionality - properly allocating memory for dynamic data members and copy the data from the passed argument object, so that both the object looks identical in data. Why not in that case, C++ provides a consolidated (one function) which would be called in both these scenarios instead of complicating things by providing two variants?</p>

答:
They are so not the same. They might be the same in special cases, but generally, no.

when you have something like this:

```<code>std::vector myVec = myOtherVec;
</code>```

It looks like assignment, but actually the copy constructor is being called.

The copy constructor starts an object from nothing.

This falls back to the basic question of what's the difference between malloc (the old C way to reserve memory) and new. The difference is: new calls the constructor of your object, which is very important in C++, otherwise we'd be talking about garbage memory that can't be initialzed unless it explicitly is.

For example, in the internal implementation of std::vector, there is a size variable that tracks the number of elements actively acknowledged by the user with push_back() or resize (we're not talking about reserve).

Now imagine how it's implemented:

```<code>template <typename T>
class vector
{
    int size;
    T* theArray;
    void reserveMyMemory(); //ignoring allocators for simplicity
}
</code>```

What's the difference between the copy constructor and assignment operator?

Assignment operator: Just copies size and the array content.

Copy-cosntructor: Must reserve memory and initialize variables, then copy.

Now imageine that memory reserving requires checking the size and whether theArray is nullptr. What's going to happen if internally it uses assignment operator? A catastrophe. Because the values are not initialized. So, you need a constructor to start.

In this case, the copy constructor is more general, because it should initialize variables, then copy the elements it has to copy. Of course, this whole example is just a demonstration. Don't take it literally for std::vector, the STL doesn't work that way.

Body:
They are so not the same. They might be the same in special cases, but generally, no.

when you have something like this:

std::vector myVec = myOtherVec;

It looks like assignment, but actually the copy constructor is being called.

The copy constructor starts an object from nothing.

This falls back to the basic question of what's the difference between malloc (the old C way to reserve memory) and new. The difference is: new calls the constructor of your object, which is very important in C++, otherwise we'd be talking about garbage memory that can't be initialzed unless it explicitly is.

For example, in the internal implementation of std::vector, there is a size variable that tracks the number of elements actively acknowledged by the user with push_back() or resize (we're not talking about reserve).

Now imagine how it's implemented:

template <typename T>
class vector
{
    int size;
    T* theArray;
    void reserveMyMemory(); //ignoring allocators for simplicity
}

What's the difference between the copy constructor and assignment operator?

Assignment operator: Just copies size and the array content.

Copy-cosntructor: Must reserve memory and initialize variables, then copy.

Now imageine that memory reserving requires checking the size and whether theArray is nullptr. What's going to happen if internally it uses assignment operator? A catastrophe. Because the values are not initialized. So, you need a constructor to start.

In this case, the copy constructor is more general, because it should initialize variables, then copy the elements it has to copy. Of course, this whole example is just a demonstration. Don't take it literally for std::vector, the STL doesn't work that way.


问:
How to solve a timeout error in Laravel 5
I have the following set up:

In routes I have:

Route::get('articles', 'ArticlesController@index');

The index method in the controller is simply:

```<code>public function index()
{
   $articles = Article::all();
   return View('articles.index', compact('articles'));
}
</code>```

and in the view:

```<code>@extends('../app')
@section('content')
<h1>Articles</h1>
<p>
    @foreach($articles as $article)
    <article>
        <h2><a href="{{action('ArticlesController@show', [$article->id])}}">{{$article->title}}</a></h2>
        <p>{{ $article->body }}</p>
    </article>
    @endforeach
</p>
@stop
</code>```

I attempted to replace the:

```<code>$articles = Article::all();
</code>```

with

```<code>$article = Article::latest()->get();
</code>```

such that I can actually show the articles latest first.
I got the error:

```<code>FatalErrorException in Str.php line 322:
Maximum execution time of 30 seconds exceeded
</code>```

and the call stack is:

```<code>in Str.php line 322
at FatalErrorException->__construct() in HandleExceptions.php line 131
at HandleExceptions->fatalExceptionFromError() in HandleExceptions.php line 116
at HandleExceptions->handleShutdown() in HandleExceptions.php line 0
at Str::snake() in helpers.php line 561
at snake_case() in ControllerInspector.php line 105
at ControllerInspector->getVerb() in ControllerInspector.php line 78
at ControllerInspector->getMethodData() in ControllerInspector.php line 39
at ControllerInspector->getRoutable() in Router.php line 251
at Router->controller() in Router.php line 226
at Router->controllers() in Facade.php line 210
at Facade::__callStatic() in routes.php line 21
at Route::controllers() in routes.php line 21
in RouteServiceProvider.php line 40
</code>```

... etc

I have restored the controller method to what it was, but the error persists.

Can you please tell me how I can solve this problem?

答:
Sometimes you just need to optimize your code or query, Setting more max_execution_time is not a solution.

It is not suggested to take more than 30 for loading a webpage if a task takes more time need to be a queue.

ContentLicense: CC BY-SA 4.0

Body:
I have the following set up:

In routes I have:

Route::get('articles', 'ArticlesController@index');

The index method in the controller is simply:

public function index()
{
   $articles = Article::all();
   return View('articles.index', compact('articles'));
}

and in the view:

@extends('../app')
@section('content')

Articles

    @foreach($articles as $article)

id])}}">{{$article->title}}

{{ $article->body }}

    @endforeach

@stop

I attempted to replace the:

$articles = Article::all();

with

$article = Article::latest()->get();

such that I can actually show the articles latest first.
I got the error:

FatalErrorException in Str.php line 322:
Maximum execution time of 30 seconds exceeded

and the call stack is:

in Str.php line 322
at FatalErrorException->__construct() in HandleExceptions.php line 131
at HandleExceptions->fatalExceptionFromError() in HandleExceptions.php line 116
at HandleExceptions->handleShutdown() in HandleExceptions.php line 0
at Str::snake() in helpers.php line 561
at snake_case() in ControllerInspector.php line 105
at ControllerInspector->getVerb() in ControllerInspector.php line 78
at ControllerInspector->getMethodData() in ControllerInspector.php line 39
at ControllerInspector->getRoutable() in Router.php line 251
at Router->controller() in Router.php line 226
at Router->controllers() in Facade.php line 210
at Facade::__callStatic() in routes.php line 21
at Route::controllers() in routes.php line 21
in RouteServiceProvider.php line 40

... etc

I have restored the controller method to what it was, but the error persists.

Can you please tell me how I can solve this problem?


问:
How to simultaneously create both 'web' and 'node' versions of a bundle with Webpack?
Is there a way to create both 'web' and 'node' versions of a bundle with one go by using Webpack or Browserify? The 'web' version of the bundle will be used on a client, and 'node' version of the same bundle will be used on the server for pre-rendering ("isomorphic" web application).</p>

答:
You can create multiple config objects in webpack.config.js file:

```<code>const config1 = {
  target: 'web',
  ...
}
const config2 = {
  target: 'node',
  ...
}

export default [config1, config2]
</code>```

Body:
You can create multiple config objects in webpack.config.js file:

const config1 = {
  target: 'web',
  ...
}
const config2 = {
  target: 'node',
  ...
}

export default [config1, config2]


问:
This rating option has been disabled by the Android Market team
I'm seeing this message

This rating option has been disabled
  by the Android Market team

next to the "All" rating option for my app.  This is showing up for my apps that need Internet access to serve up adMob ads.  I am not allowed to select the All option.  My app is suitable for little kids, and the ads don't show up on the main game screen.  Does anyone know of a way to get around this?

答: Should a child not be able to know where they are?</p>


问:
What is "2" in command, while redirecting both System.out , System.err Java messages to file
I just figured that, we can redirect both System.out and System.err messages to  a file, am not able to understand this command which does redirecting while running this below file using : java StandarProgram> output.log 2>error.log

What is 2? and if am not using 2, error messages are displayed on console and not redirected to file? am not able to get this at all.

```<code>public class StandardProgram{

    public static void main(String[] args){

       System.out.println("Hello");
       System.err.println("World");

    }
}
</code>```

答:
System.out is according to documentation Standard Output Stream - it is 1

System.err is according to documentation Standard Error Stream - it is 2

Body:
I just figured that, we can redirect both System.out and System.err messages to  a file, am not able to understand this command which does redirecting while running this below file using : java StandarProgram> output.log 2>error.log

What is 2? and if am not using 2, error messages are displayed on console and not redirected to file? am not able to get this at all.

public class StandardProgram{

    public static void main(String[] args){

       System.out.println("Hello");
       System.err.println("World");

    }
}


问:
Country state concept in codeigniter
This is My View Page

```<code> <select name="category" value="c_id" onChange="getsubcategorydetails(this.value)" style="display:">
                                                   <option value="" selected="selected" >Select Categories</option>
            <?php if(isset($categories)) : foreach($categories as $row) :?>
                <option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
                <?php endforeach;?>
                <?php else :
                endif;
                ?>
          </select>
                 </div>
               </div>
                 </div>
                </div>
                                <div class="row">
                                   <div class="input-field col s12">
                                   <tr>

                                            <td>

    <select name=" select id="subcategory">
 <option value="" selected="selected" >Select Sub Category</option>
 <?php foreach($sub_categories as $stt): ?>
  <option value="<?php echo $stt->s_c_id; ?>"><?php echo $stt->s_c_name; ?></option>
 <?php endforeach; ?>
 </select>
                                                </select></td>
                                                </tr>
</code>```

This is My Controller

```<code>    public function getsubcategorydetails($c_id)
    {

      $c_id = $this->uri->segment(3);
      //  echo  $c_id;
        $data['sub_categories'] = $this->m_category->getsubcategorydetails($c_id);
        //print_r($data['sub_category']);
       $this->load->view('my_admin/newpost_1',$data);
    }
</code>```

This is My Model

```<code>    function getsubcategorydetails($c_id='')
 {
    $this -> db -> select('*');
    $this -> db -> where('c_id', $c_id);
    $query = $this -> db -> get('subcategories');
    return $query->result();
 }
</code>```

When i Click Category Select Box The Values returned from Controller ... But It Not Displayed On View ... What's Wrong With That .... Thanks In Advance

答:
Here in my code,

iam posting categoryid through ajax in onchange event

and getting the subcategory for the categoryid from controller

and make the selection box in controller with the subcategory

and put the selection box in subcategory id.

Try this method.

View file

```<code><select name="category" onChange="getsubcategorydetails(this.value)" >
 <option value=""  >Select Categories</option>
            <?php if(isset($categories)) : foreach($categories as $row) :?>
                <option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
                <?php endforeach;?>
                <?php else :
                endif;
                ?>
</select>

<select name="subcategory" id="subcategory">
    <option value="" >Select Sub Category</option>
</select>
</code>```

Controller

```<code>public function getsubcategorydetails($c_id)
    {

       $c_id = $this->input->post('c_id');

       $sub_categories = $this->m_category->getsubcategorydetails($c_id);

       $subcategory='<option value="" >Select Sub Category</option>';

       foreach($sub_categories as $stt)
       {

       $subcategory.='<option value="'.$stt->s_c_id.'">'.$stt->s_c_name.'</option>';

       }

       echo $subcategory;
    }
</code>```

Model

```<code>function getsubcategorydetails($c_id='')
 {
    $this -> db -> select('*');
    $this -> db -> where('c_id', $c_id);
    $query = $this -> db -> get('subcategories');
    return $query->result();
 }
</code>```

Script

```<code>function getsubcategorydetails(c_id)
{
    $.ajax({
        type: 'POST',
        url: "<?php echo base_url(); ?>yourcontroller/yourfunction",
        data: {c_id:c_id},
        success: function(data) {
            $('#subcategory').html(data);
        }
    });
}
</code>```

Title: Country state concept in codeigniter

Body:
This is My View Page

 <select name="category" value="c_id" onChange="getsubcategorydetails(this.value)" style="display:">
                                                   <option value="" selected="selected" >Select Categories</option>
            <?php if(isset($categories)) : foreach($categories as $row) :?>
                <option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
                <?php endforeach;?>
                <?php else :
                endif;
                ?>
          </select>

    <select name=" select id="subcategory">
 <option value="" selected="selected" >Select Sub Category</option>
 <?php foreach($sub_categories as $stt): ?>
  <option value="<?php echo $stt->s_c_id; ?>"><?php echo $stt->s_c_name; ?></option>
 <?php endforeach; ?>
 </select>
                                                </select>

This is My Controller

    public function getsubcategorydetails($c_id)
    {

      $c_id = $this->uri->segment(3);
      //  echo  $c_id;
        $data['sub_categories'] = $this->m_category->getsubcategorydetails($c_id);
        //print_r($data['sub_category']);
       $this->load->view('my_admin/newpost_1',$data);
    }

This is My Model

    function getsubcategorydetails($c_id='')
 {
    $this -> db -> select('*');
    $this -> db -> where('c_id', $c_id);
    $query = $this -> db -> get('subcategories');
    return $query->result();
 }

When i Click Category Select Box The Values returned from Controller ... But It Not Displayed On View ... What's Wrong With That .... Thanks In Advance

Body:
Here in my code,

iam posting categoryid through ajax in onchange event

and getting the subcategory for the categoryid from controller

and make the selection box in controller with the subcategory

and put the selection box in subcategory id.

Try this method.

View file

<select name="category" onChange="getsubcategorydetails(this.value)" >
 <option value=""  >Select Categories</option>
            <?php if(isset($categories)) : foreach($categories as $row) :?>
                <option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
                <?php endforeach;?>
                <?php else :
                endif;
                ?>
</select>

<select name="subcategory" id="subcategory">
    <option value="" >Select Sub Category</option>
</select>

Controller

public function getsubcategorydetails($c_id)
    {

       $c_id = $this->input->post('c_id');

       $sub_categories = $this->m_category->getsubcategorydetails($c_id);

       $subcategory='<option value="" >Select Sub Category</option>';

       foreach($sub_categories as $stt)
       {

       $subcategory.='<option value="'.$stt->s_c_id.'">'.$stt->s_c_name.'</option>';

       }

       echo $subcategory;
    }

Model

function getsubcategorydetails($c_id='')
 {
    $this -> db -> select('*');
    $this -> db -> where('c_id', $c_id);
    $query = $this -> db -> get('subcategories');
    return $query->result();
 }

Script

function getsubcategorydetails(c_id)
{
    $.ajax({
        type: 'POST',
        url: "<?php echo base_url(); ?>yourcontroller/yourfunction",
        data: {c_id:c_id},
        success: function(data) {
            $('#subcategory').html(data);
        }
    });
}


问:
How to fetch class instance from class variable (from outside the class)?
Let's say I have this:

```<code>from PySide2 import QtWidgets

class MyClass(object):
    def __init__(self, parent=None):
        self.class_variable = QtWidgets.QWidget()

class_instance = MyClass()
variable = class_instance.class_variable
class_instance_returned = mystery_method(variable)  # How to make this return class_instance?
</code>```

How should I define mystery_method so that it would return the class_instance instance?

The real-world case I have is that I'm sending a QWidget which I'm using as a base instance for .ui file loading into a function. Inside this function I need to figure out which class instance it belongs to.

答:
Python 2.7

```<code>class MyClass(object):
    def foo():
        return 'bar'

instance = MyClass()

def mystery_method(method):
    return method.im_self.__class__

print mystery_method(instance.foo)
</code>```

Python 3

```<code>class MyClass(object):
    def foo():
        return 'bar'

instance = MyClass()

def mystery_method(method):
    return method.__self__.__class__

print mystery_method(instance.foo)
</code>```

EDIT

After the OP was edited:

```<code>class ParentClass():
    def foo():
        return 'bar'

class MyClass(object):
    def __init__(self, parent=None):
        self.instance_attribute = ParentClass()

def mystery_method(method):
    return method.__class__

class_instance = MyClass()
print mystery_method(class_instance.instance_attribute)
</code>```

Body:
Let's say I have this:

from PySide2 import QtWidgets

class MyClass(object):
    def __init__(self, parent=None):
        self.class_variable = QtWidgets.QWidget()

class_instance = MyClass()
variable = class_instance.class_variable
class_instance_returned = mystery_method(variable)  # How to make this return class_instance?

How should I define mystery_method so that it would return the class_instance instance?

The real-world case I have is that I'm sending a QWidget which I'm using as a base instance for .ui file loading into a function. Inside this function I need to figure out which class instance it belongs to.

Body:
Python 2.7

class MyClass(object):
    def foo():
        return 'bar'

instance = MyClass()

def mystery_method(method):
    return method.im_self.__class__

print mystery_method(instance.foo)

Python 3

class MyClass(object):
    def foo():
        return 'bar'

instance = MyClass()

def mystery_method(method):
    return method.__self__.__class__

print mystery_method(instance.foo)

EDIT

After the OP was edited:

class ParentClass():
    def foo():
        return 'bar'

class MyClass(object):
    def __init__(self, parent=None):
        self.instance_attribute = ParentClass()

def mystery_method(method):
    return method.__class__

class_instance = MyClass()
print mystery_method(class_instance.instance_attribute)


问:
How to acces a model attribute from another model
I newbie with Django Framework and I wish to know if is possible I access a attribute from the model X via model Y...In my case a have a model called "Evaluation" this model receive the scores of evaluations of the candidates..they have a ForeignKey that receive the Candidate(what is another model) and a PositiveIntegerField with receive a score what I want is access this PositiveIntegerField via Candidate model, it's possible?

My models.py:

```<code>from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator

class Criterion(models.Model):
    label = models.CharField(max_length=100)

    def  __str__(self):
        return self.label

class Candidate(models.Model):
    name = models.CharField(max_length=100)
    e_mail = models.EmailField(max_length=100, default = '')
    github = models.URLField(default = '')
    linkedin = models.URLField(max_length=100, default = '')
    cover_letter = models.TextField(default = '')
    higher_education = models.BooleanField(default = False)
    docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)

    def  __str__(self):
        return self.name

class Evaluation(models.Model):
    candidate = models.ForeignKey(Candidate)
    criterion = models.ForeignKey(Criterion, default='')
    score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
    appraiser = models.ForeignKey('auth.User')

    def  __str__(self):
        return str(self.candidate)

#model de teste
class Teste(models.Model):
    nome = models.CharField(max_length=10)

    def  __str__(self):
        return str(self.nome)
</code>```

答:
You have a two solution to access the Evaluation objects

Example 1

```<code>candidateObj = Candidate.objects.get(id=your_candidate_id)
evaluationObjs = Evaluation.objects.filter(candidate=candidateObj)
</code>```

Example 2

```<code>evaluationObjs = candidateObj.evaluation_set.all()
</code>```

If you create only one Evaluation object then you directly use

```<code>score = candidateObj.evaluation_set.get().score
</code>```

Hope this will help you

Body:
I newbie with Django Framework and I wish to know if is possible I access a attribute from the model X via model Y...In my case a have a model called "Evaluation" this model receive the scores of evaluations of the candidates..they have a ForeignKey that receive the Candidate(what is another model) and a PositiveIntegerField with receive a score what I want is access this PositiveIntegerField via Candidate model, it's possible?

My models.py:

from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator

class Criterion(models.Model):
    label = models.CharField(max_length=100)

    def  __str__(self):
        return self.label

class Candidate(models.Model):
    name = models.CharField(max_length=100)
    e_mail = models.EmailField(max_length=100, default = '')
    github = models.URLField(default = '')
    linkedin = models.URLField(max_length=100, default = '')
    cover_letter = models.TextField(default = '')
    higher_education = models.BooleanField(default = False)
    docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)

    def  __str__(self):
        return self.name

class Evaluation(models.Model):
    candidate = models.ForeignKey(Candidate)
    criterion = models.ForeignKey(Criterion, default='')
    score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
    appraiser = models.ForeignKey('auth.User')

    def  __str__(self):
        return str(self.candidate)

#model de teste
class Teste(models.Model):
    nome = models.CharField(max_length=10)

    def  __str__(self):
        return str(self.nome)

Body:
You have a two solution to access the Evaluation objects

Example 1

candidateObj = Candidate.objects.get(id=your_candidate_id)
evaluationObjs = Evaluation.objects.filter(candidate=candidateObj)

Example 2

evaluationObjs = candidateObj.evaluation_set.all()

If you create only one Evaluation object then you directly use

score = candidateObj.evaluation_set.get().score

Hope this will help you


问:
How to Find the 4 furthest points of this rectangle
I have plotted a list of corners I've obtained using Harris Corner detection.

Now I need to find the 4 furthers points that will represent the corners of the rectangle

I know I can get the two top and bottom diagonal corners using

```<code>  max(C);
  min(C);
</code>```

Where C is an n row matrix with a column for x and y like

```<code>  x y
  0 1
  2 3
  4 5
  6 6
</code>```

But how do I get the other two corners?

I thought I could rotate the matrix and use min and max again, but of course that just returns me a huge n column matrix (and I want a 2 column matrix)

I feel like the answer is obvious, but I'm blanking :(

答:
i don't know how limited is the following method but it worked for an example similar to yours:

```<code>% detect possible corners
points = detectHarrisFeatures(BW);
C = points.Location;
% compute par-wise distances between all points
D = pdist2(C,C);
p = zeros(1,4);
% compute maximum distance to find first pair
[m,idx1] = max(D,[],2);
[~,idx2] = max(m);
idx1 = idx1(idx2);
p(1:2) = [idx1, idx2];
% add first pair distance to distance matrix so the next pair will be
% distant from this pair as well, and compute max distance again
D = bsxfun(@plus,D,sum(D([idx1 idx2],:),1));
[m,idx1] = max(D,[],2);
[~,idx2] = max(m);
idx1 = idx1(idx2);
p(3:4) = [idx1, idx2];
% plot
imshow(BW);
hold on;
plot(C(:,1),C(:,2),'g.');
plot(C(p,1),C(p,2),'rx','LineWidth',2);
</code>```

another option is to use FEX functions like Polygon simplification and Decimate Polygon, and to set the number of desired vertexes to 4.

Body:
I have plotted a list of corners I've obtained using Harris Corner detection.

Now I need to find the 4 furthers points that will represent the corners of the rectangle

I know I can get the two top and bottom diagonal corners using

  max(C);
  min(C);

Where C is an n row matrix with a column for x and y like

  x y
  0 1
  2 3
  4 5
  6 6

But how do I get the other two corners?

I thought I could rotate the matrix and use min and max again, but of course that just returns me a huge n column matrix (and I want a 2 column matrix)

I feel like the answer is obvious, but I'm blanking :(

Body:
i don't know how limited is the following method but it worked for an example similar to yours:

% detect possible corners
points = detectHarrisFeatures(BW);
C = points.Location;
% compute par-wise distances between all points
D = pdist2(C,C);
p = zeros(1,4);
% compute maximum distance to find first pair
[m,idx1] = max(D,[],2);
[~,idx2] = max(m);
idx1 = idx1(idx2);
p(1:2) = [idx1, idx2];
% add first pair distance to distance matrix so the next pair will be
% distant from this pair as well, and compute max distance again
D = bsxfun(@plus,D,sum(D([idx1 idx2],:),1));
[m,idx1] = max(D,[],2);
[~,idx2] = max(m);
idx1 = idx1(idx2);
p(3:4) = [idx1, idx2];
% plot
imshow(BW);
hold on;
plot(C(:,1),C(:,2),'g.');
plot(C(p,1),C(p,2),'rx','LineWidth',2);

another option is to use FEX functions like Polygon simplification and Decimate Polygon, and to set the number of desired vertexes to 4.


问:
Android: Method is called twice if imeOptions is used
Layout:

```<code>    ....
    <EditText
        ....
        android:hint="@string/email"
        android:imeOptions="actionSend"/>
    <Button
        ...
        android:onClick="sendMessage"      <<<- both must call it
        android:text="@string/send" />
</code>```

Then binding in code:

```<code>( (EditText) findViewById(R.id.email) ).setOnEditorActionListener(new OnEditorActionListener()  {
            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                sendMessage(findViewById(android.R.id.content));
                return false;
            }
        });
</code>```

Where sendMessage is

```<code>public void sendMessage(View view)
{
    ....
    intent.putExtra("email", getEditContent(R.id.email));
    startActivityForResult(intent, 0);
}
</code>```

When I press button everything is fine. When I press "Done" in imeOption (keyboard) two Activities starts at the same time.

What am I doing wrong?

答:
```<code>public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (event.getAction() != KeyEvent.ACTION_DOWN)
        return false;

    // do your stuff

    return true;
}
</code>```

Body:
Layout:

    ....
    <EditText
        ....
        android:hint="@string/email"
        android:imeOptions="actionSend"/>
    <Button
        ...
        android:onClick="sendMessage"      <<<- both must call it
        android:text="@string/send" />

Then binding in code:

( (EditText) findViewById(R.id.email) ).setOnEditorActionListener(new OnEditorActionListener()  {
            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                sendMessage(findViewById(android.R.id.content));
                return false;
            }
        });

Where sendMessage is

public void sendMessage(View view)
{
    ....
    intent.putExtra("email", getEditContent(R.id.email));
    startActivityForResult(intent, 0);
}

When I press button everything is fine. When I press "Done" in imeOption (keyboard) two Activities starts at the same time.

What am I doing wrong?


问:
Is it possible to change the size of the text in an HTML input tag?
I have a client who wants bigger text in an <input> box.  I would prefer to not have to make custom graphic button for this as it's on a really resource-constrained embedded system.

答:
Simply specify the font-size you want for the element:

```<code>input {
    font-family: tahoma, verdana, sans-serif;
    font-size: 1.1em;
}
</code>```

I have used a relative size (em), so the ratio will keep if a user has a larger font size defined in the browser.

Body:
Simply specify the font-size you want for the element:

input {
    font-family: tahoma, verdana, sans-serif;
    font-size: 1.1em;
}

I have used a relative size (em), so the ratio will keep if a user has a larger font size defined in the browser.


问:
Solver time seems to be to high for a small energy model using oemof (solph) with CBC solver
I built an electricity energysystem with 6 busses with oemof. Every bus has an easy input. And bus 1 is connected to bus 2 in both direction (2 transformsers). Bus 2 is connected to bus 3 on the same way. …. bus 6 is connected to bus 1. So it is a ring structure. Every bus has a sink.
The bus 1 is also connected with a gas bus by an gas power plant. The gas bus has 1 input with energy.
Now I started to connect one demand on bus 1 with 8760 time steps (one year). I let the program solve the flow of every object in this energysystem. I got the solution after 40 seconds.
But my goal is to solve the problem with more demands in the system. So I integrated a second demand on bus 2. Now the calculation time was about 3 minutes. With an third demand on bus 3 the calculation time was 15 minutes. And with a demand at every bus, it takes more than 40min.

My processor is an i5 4670K 3.4 GHz.

My problem is: Why the CBC solver needs so much time to solve the problem with more demands in the energysystem? Is there any reason?

Do you now how the solver exactly works? I couldn’t find any answer

With one demand in the system:

```<code>128382 Obj 1.6384541e+013 Primal inf 6.0004356e+008 (5) Dual inf 2.5973983e-006 (1)
Primal infeasible - objective value 1.6384541e+013
PrimalInfeasible objective 1.638454066e+013 - 128382 iterations time 36.552
</code>```

With two demands in the system:

```<code>155933 Obj 1.1686988e+014 Primal inf 3.7517663e+010 (20494)
Primal infeasible - objective value 1.1686988e+014
PrimalInfeasible objective 1.16869879e+014 - 155933 iterations time 1728.062
</code>```

答:
I do agree that 40min seems to be too long for such a small system.

Normally the solver time increases significantly if the problem is infeasible. Therefore you should make sure that the problem is still solvable after you added additional demand objects. By the way, different units (or prefixes) are a typical source of error.

An easy way to make your problem solvable is to add unlimited excess and shortage objects to every bus (balance). Make sure that the shortage source is more expensive for the solver than all other objects, otherwise it might be used instead of your power plants.

For oemof.solph it looks like this (e.g. bus_1):

```<code>from oemof import solph

# shortage bus_1
solph.Source(label='shortage_1',
             outputs={bus_1: solph.Flow(variable_costs=50000)})

# excess bus_1
solph.Sink(label='excess_1', inputs={bus_1: solph.Flow()})
</code>```

If you add these objects to every bus your problem will be solvable. Afterwards you can check the results. If the sum of these sinks and sources is greater than zero the problem would be infeasible without them. Now you can analyse your results to find the problem.

Body:
I built an electricity energysystem with 6 busses with oemof. Every bus has an easy input. And bus 1 is connected to bus 2 in both direction (2 transformsers). Bus 2 is connected to bus 3 on the same way. …. bus 6 is connected to bus 1. So it is a ring structure. Every bus has a sink.
The bus 1 is also connected with a gas bus by an gas power plant. The gas bus has 1 input with energy.
Now I started to connect one demand on bus 1 with 8760 time steps (one year). I let the program solve the flow of every object in this energysystem. I got the solution after 40 seconds.
But my goal is to solve the problem with more demands in the system. So I integrated a second demand on bus 2. Now the calculation time was about 3 minutes. With an third demand on bus 3 the calculation time was 15 minutes. And with a demand at every bus, it takes more than 40min.

My processor is an i5 4670K 3.4 GHz.

My problem is: Why the CBC solver needs so much time to solve the problem with more demands in the energysystem? Is there any reason?

Do you now how the solver exactly works? I couldn’t find any answer

With one demand in the system:

128382 Obj 1.6384541e+013 Primal inf 6.0004356e+008 (5) Dual inf 2.5973983e-006 (1)
Primal infeasible - objective value 1.6384541e+013
PrimalInfeasible objective 1.638454066e+013 - 128382 iterations time 36.552

With two demands in the system:

155933 Obj 1.1686988e+014 Primal inf 3.7517663e+010 (20494)
Primal infeasible - objective value 1.1686988e+014
PrimalInfeasible objective 1.16869879e+014 - 155933 iterations time 1728.062

Body:
I do agree that 40min seems to be too long for such a small system.

Normally the solver time increases significantly if the problem is infeasible. Therefore you should make sure that the problem is still solvable after you added additional demand objects. By the way, different units (or prefixes) are a typical source of error.

An easy way to make your problem solvable is to add unlimited excess and shortage objects to every bus (balance). Make sure that the shortage source is more expensive for the solver than all other objects, otherwise it might be used instead of your power plants.

For oemof.solph it looks like this (e.g. bus_1):

from oemof import solph

# shortage bus_1
solph.Source(label='shortage_1',
             outputs={bus_1: solph.Flow(variable_costs=50000)})

# excess bus_1
solph.Sink(label='excess_1', inputs={bus_1: solph.Flow()})

If you add these objects to every bus your problem will be solvable. Afterwards you can check the results. If the sum of these sinks and sources is greater than zero the problem would be infeasible without them. Now you can analyse your results to find the problem.


问:
Staggering items in CSS with flexbox
I'm trying to create a staggered layout in CSS, where each row only has one item, but it will be offset from the items on the other rows.

I've made two working examples so far, but I'm wondering if there is a better way to achieve this.

Here's an example I made using spacer divs :
http://cdpn.io/e/EWrMgL

HTML :

```<code><div class="container">
    <div class="row">
        <div class="spacer">(spacer)</div>
        <div class="content col-2">content 2</div>
        <div class="spacer">(spacer)</div>
    </div>
    <div class="row">
        <div class="content col-1">content 1</div>
        <div class="spacer">(spacer)</div>
        <div class="spacer">(spacer)</div>
    </div>
    <div class="row">
        <div class="spacer">(spacer)</div>
        <div class="spacer">(spacer)</div>
        <div class="content col-3">content 3</div>
    </div>
    <div class="row">
        <div class="spacer">(spacer)</div>
        <div class="spacer">(spacer)</div>
        <div class="content col-3">content 3</div>
    </div>
</div>
</code>```

CSS :

```<code>.container, .spacer, .content, .row {
    display: flex;
}

.container {
    flex-flow: row wrap;
    font-family: sans-serif;
}

.row {
    width: 100%
}

.spacer {
    color: #2c3e50;
    flex: 1 1 0%;
}

.content {
    color: #ecf0f1;
    flex : 3 1 0%;
    flex-basis: 60%
}

.content, .spacer {
    justify-content: center;
    align-items: center;
    min-height: 5em;
    margin: 0.5em;
}

.col-1 {
    background-color: #96858F;
}

.col-2 {
     background-color:#9099A2;
}

.col-3 {
    background-color: #6d7993;
}
</code>```

I made another attempt at a cleaner version using margins instead of wrapping
each item in a row : http://cdpn.io/e/xqMBmB

HTML:

```<code><div class="container">
        <div class="content col-2">content 2</div>
        <div class="content col-1">content 1</div>
        <div class="content col-3">content 3</div>
        <div class="content col-3">content 3</div>
</div>
</code>```

CSS:

```<code>.container, .content{
    display: flex;
}

.container {
    flex-flow: row wrap;
    font-family: sans-serif;
}

.content {
    color: #ecf0f1;
    flex: 0 1 70%;

    justify-content: center;
    align-items: center;
    min-height: 5em;
    margin-bottom: 0.5em;
}

.col-1 {
    background-color: #96858F;
}

.col-2 {
    background-color:#9099A2;
    margin-left: 7.5%;
}

.col-3 {
    background-color: #6d7993;
    margin-left: 15%;
}
</code>```

Is there a cleaner way to do this than enclosing each row in a div or changing the margins? I'll want to add @media rules to make the rows 100% width below a certain screen size.

答:
Your second version of the code is fine, it's simple enough. What I would suggest though instead of using specific margins is to use auto margins, change the size of the items to 100% and then specify a max-width so that on smaller devices they will be full width and on larger screens they won't. Here's an example of the CSS for this:

```<code>.container, .content{
  display: flex;
}

.container {
  flex-flow: row wrap;
  font-family: sans-serif;
}

.content {
  color: #ecf0f1;
  flex: 0 1 100%; /* CHANGE */
  max-width: 800px; /* CHANGE */
  justify-content: center;
  align-items: center;
  min-height: 5em;
  margin-bottom: 0.5em;
}

.col-1 {
  background-color: #96858F;
}

.col-2 {
  background-color:#9099A2;
  margin-left: auto; /* CHANGE */
  margin-right: auto; /* CHANGE */
}

.col-3 {
  background-color: #6d7993;
  margin-left: auto;
}
</code>```

Maybe that is the result you're after? If not something along those lines should be fine. Using media queries as you suggested would also work, changing the flex size from 70% to 100% below a certain width. You could do that by adding something like the below to the end of your CSS:

```<code>@media screen and (max-width: 600px) {
  .content {
    flex: 0 1 100%;
  }
}
</code>```

Hopefully this will point you in the right direction.

Title: Staggering items in CSS with flexbox

Body:
I'm trying to create a staggered layout in CSS, where each row only has one item, but it will be offset from the items on the other rows.

I've made two working examples so far, but I'm wondering if there is a better way to achieve this.

Here's an example I made using spacer divs :
http://cdpn.io/e/EWrMgL

HTML :

(spacer)

content 2

(spacer)

content 1

(spacer)

(spacer)

(spacer)

(spacer)

content 3

(spacer)

(spacer)

content 3

CSS :

.container, .spacer, .content, .row {
    display: flex;
}

.container {
    flex-flow: row wrap;
    font-family: sans-serif;
}

.row {
    width: 100%
}

.spacer {
    color: #2c3e50;
    flex: 1 1 0%;
}

.content {
    color: #ecf0f1;
    flex : 3 1 0%;
    flex-basis: 60%
}

.content, .spacer {
    justify-content: center;
    align-items: center;
    min-height: 5em;
    margin: 0.5em;
}

.col-1 {
    background-color: #96858F;
}

.col-2 {
     background-color:#9099A2;
}

.col-3 {
    background-color: #6d7993;
}

I made another attempt at a cleaner version using margins instead of wrapping
each item in a row : http://cdpn.io/e/xqMBmB

HTML:

content 2

content 1

content 3

content 3

CSS:

.container, .content{
    display: flex;
}

.container {
    flex-flow: row wrap;
    font-family: sans-serif;
}

.content {
    color: #ecf0f1;
    flex: 0 1 70%;

    justify-content: center;
    align-items: center;
    min-height: 5em;
    margin-bottom: 0.5em;
}

.col-1 {
    background-color: #96858F;
}

.col-2 {
    background-color:#9099A2;
    margin-left: 7.5%;
}

.col-3 {
    background-color: #6d7993;
    margin-left: 15%;
}

Is there a cleaner way to do this than enclosing each row in a div or changing the margins? I'll want to add @media rules to make the rows 100% width below a certain screen size.

Body:
Your second version of the code is fine, it's simple enough. What I would suggest though instead of using specific margins is to use auto margins, change the size of the items to 100% and then specify a max-width so that on smaller devices they will be full width and on larger screens they won't. Here's an example of the CSS for this:

.container, .content{
  display: flex;
}

.container {
  flex-flow: row wrap;
  font-family: sans-serif;
}

.content {
  color: #ecf0f1;
  flex: 0 1 100%; /* CHANGE */
  max-width: 800px; /* CHANGE */
  justify-content: center;
  align-items: center;
  min-height: 5em;
  margin-bottom: 0.5em;
}

.col-1 {
  background-color: #96858F;
}

.col-2 {
  background-color:#9099A2;
  margin-left: auto; /* CHANGE */
  margin-right: auto; /* CHANGE */
}

.col-3 {
  background-color: #6d7993;
  margin-left: auto;
}

Maybe that is the result you're after? If not something along those lines should be fine. Using media queries as you suggested would also work, changing the flex size from 70% to 100% below a certain width. You could do that by adding something like the below to the end of your CSS:

@media screen and (max-width: 600px) {
  .content {
    flex: 0 1 100%;
  }
}

Hopefully this will point you in the right direction.


问:
How search feature works in AEM
 From AEM documents I can figure it out how to write queries for Aem content search, but How search feature works in AEM? Which bundle or framework does the magic of searching the content and present back. How internally content is being traversed when I use search queries ? </p>

答:
AEM uses OAK indexes to implement the search engine. AEM repository is a database and like every other database, it needs indexes to perform speedy searches. You can read more on: https://docs.adobe.com/docs/en/aem/6-2/deploy/platform/queries-and-indexing.html

In general, you define indexes (in case OOTB indexes are not enough) under /oak:indexes node. These indexes, in a broad sense, contain list of properties and nature (async, full text, property, lexical rules) of index and the path to be indexed (or excluded from index).

AEM generates a lot of lucene index data in your repository and data store and that is used to quickly lookup the nodes for your queries. Whenever, a query is fired the AEM instance loops through the indexes and finds the index which will provide the results with least traversal cost. If no such index is found it will resort to node traversal which is normally bad for performance but has some limited edge case uses.

You can integrated Solr and ElasticSearch with your AEM instance to use other advanced features but that is simply an extension to the built-in engine.

Search and promote (which is more of an external search) is not related to internal index and is more like a site crawler.

Queries and searches is a very broad topic so I suggest you read this reply as a summary and more details can be found from the link above.

Title: How search feature works in AEM


问:
Outlook save only pdf attachments
Hi I have found this code and been using it for a while now but I am looking to add a rule to only save the PDF attachments and count how many PDF files have been saved.

I have got it saving all files and it loops the duplicated files but I just want it to save pdf files.

can someone assist please?

thanks

```<code>' ######################################################
'  Returns the number of attachements in the selection.
' ######################################################
Public Function SaveAttachmentsFromSelection() As Long
    Dim objFSO              As Object       ' Computer's file system object.
    Dim objShell            As Object       ' Windows Shell application object.
    Dim objFolder           As Object       ' The selected folder object from Browse for Folder dialog box.
    Dim objItem             As Object       ' A specific member of a Collection object either by position or by key.
    Dim selItems            As Selection    ' A collection of Outlook item objects in a folder.
    Dim Atmt                As Attachment   ' A document or link to a document contained in an Outlook item.
    Dim strAtmtPath         As String       ' The full saving path of the attachment.
    Dim strAtmtFullName     As String       ' The full name of an attachment.
    Dim strAtmtName(1)      As String       ' strAtmtName(0): to save the name; strAtmtName(1): to save the file extension. They are separated by dot of an attachment file name.
    Dim strAtmtNameTemp     As String       ' To save a temporary attachment file name.
    Dim intDotPosition      As Integer      ' The dot position in an attachment name.
    Dim atmts               As Attachments  ' A set of Attachment objects that represent the attachments in an Outlook item.
    Dim lCountEachItem      As Long         ' The number of attachments in each Outlook item.
    Dim lCountAllItems      As Long         ' The number of attachments in all Outlook items.
    Dim strFolderpath       As String       ' The selected folder path.
    Dim blnIsEnd            As Boolean      ' End all code execution.
    Dim blnIsSave           As Boolean      ' Consider if it is need to save.
    Dim oItem               As Object
    Dim iAttachments        As Integer

    blnIsEnd = False
    blnIsSave = False
    lCountAllItems = 0

    On Error Resume Next

    Set selItems = ActiveExplorer.Selection

    If Err.Number = 0 Then

        ' Get the handle of Outlook window.
        lHwnd = FindWindow(olAppCLSN, vbNullString)

        If lHwnd <> 0 Then

            ' /* Create a Shell application object to pop-up BrowseForFolder dialog box. */
            Set objShell = CreateObject("Shell.Application")
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objShell.BrowseForFolder(lHwnd, "Select folder to save attachments:", _
                                                     BIF_RETURNONLYFSDIRS + BIF_DONTGOBELOWDOMAIN, CSIDL_DESKTOP)

            ' /* Failed to create the Shell application. */
            If Err.Number <> 0 Then
                MsgBox "Run-time error '" & CStr(Err.Number) & " (0x" & CStr(Hex(Err.Number)) & ")':" & vbNewLine & _
                       Err.Description & ".", vbCritical, "Error from Attachment Saver"
                blnIsEnd = True
                GoTo PROC_EXIT
            End If

            If objFolder Is Nothing Then
                strFolderpath = ""
                blnIsEnd = True
                GoTo PROC_EXIT
            Else
                strFolderpath = CGPath(objFolder.Self.Path)

                ' /* Go through each item in the selection. */
                For Each objItem In selItems
                    lCountEachItem = objItem.Attachments.Count

                    ' /* If the current item contains attachments. */
                    If lCountEachItem > 0 Then
                        Set atmts = objItem.Attachments

                        ' /* Go through each attachment in the current item. */
                        For Each Atmt In atmts

                            ' Get the full name of the current attachment.
                            strAtmtFullName = Atmt.FileName

                            ' Find the dot postion in atmtFullName.
                            intDotPosition = InStrRev(strAtmtFullName, ".")

                            ' Get the name.
                            strAtmtName(0) = Left$(strAtmtFullName, intDotPosition - 1)
                            ' Get the file extension.
                            strAtmtName(1) = Right$(strAtmtFullName, Len(strAtmtFullName) - intDotPosition)
                            ' Get the full saving path of the current attachment.
                            strAtmtPath = strFolderpath & Atmt.FileName

                            ' /* If the length of the saving path is not larger than 260 characters.*/
                            If Len(strAtmtPath) <= MAX_PATH Then
                                ' True: This attachment can be saved.
                                blnIsSave = True

                                ' /* Loop until getting the file name which does not exist in the folder. */
                                Do While objFSO.FileExists(strAtmtPath)
                                    strAtmtNameTemp = strAtmtName(0) & _
                                                      Format(Now, "_mmddhhmmss") & _
                                                      Format(Timer * 1000 Mod 1000, "000")
                                    strAtmtPath = strFolderpath & strAtmtNameTemp & "." & strAtmtName(1)

                                    ' /* If the length of the saving path is over 260 characters.*/
                                    If Len(strAtmtPath) > MAX_PATH Then
                                        lCountEachItem = lCountEachItem - 1
                                        ' False: This attachment cannot be saved.
                                        blnIsSave = False
                                        Exit Do
                                    End If
                                Loop

                                ' /* Save the current attachment if it is a valid file name. */
                                If blnIsSave Then Atmt.SaveAsFile strAtmtPath
                            Else
                                lCountEachItem = lCountEachItem - 1
                            End If
                        Next
                    End If

                    ' Count the number of attachments in all Outlook items.
                    lCountAllItems = lCountAllItems + lCountEachItem
                Next
            End If
        Else
            MsgBox "Failed to get the handle of Outlook window!", vbCritical, "Error from Attachment Saver"
            blnIsEnd = True
            GoTo PROC_EXIT
        End If

    ' /* For run-time error:
    '    The Explorer has been closed and cannot be used for further operations.
    '    Review your code and restart Outlook. */
    Else
        MsgBox "Please select an Outlook item at least.", vbExclamation, "Message from Attachment Saver"
        blnIsEnd = True
    End If

PROC_EXIT:
    SaveAttachmentsFromSelection = lCountAllItems

    ' /* Release memory. */
    If Not (objFSO Is Nothing) Then Set objFSO = Nothing
    If Not (objItem Is Nothing) Then Set objItem = Nothing
    If Not (selItems Is Nothing) Then Set selItems = Nothing
    If Not (Atmt Is Nothing) Then Set Atmt = Nothing
    If Not (atmts Is Nothing) Then Set atmts = Nothing

    ' /* End all code execution if the value of blnIsEnd is True. */
    If blnIsEnd Then End
End Function

' #####################
' Convert general path.
' #####################
Public Function CGPath(ByVal Path As String) As String
    If Right(Path, 1) <> "\" Then Path = Path & "\"
    CGPath = Path
End Function

' ######################################
' Run this macro for saving attachments.
' ######################################
Public Sub ExecuteSaving()
    Dim oItem As Object
    Dim iAttachments As Integer

    For Each oItem In ActiveExplorer.Selection
    iAttachments = oItem.Attachments.Count + iAttachments
    Next
    MsgBox "Selected " & ActiveExplorer.Selection.Count & " messages with " & iAttachments & " attachements"
End Sub
</code>```

答:
Simply use  Select Case Statement faster to execute and easier to understand.. and more flexible to add additional file types

After

```<code>' /* Go through each attachment in the current item. */
For Each Atmt In atmts
</code>```

Simply add

```<code>Dim sFileType As String
' Last 4 Characters in a Filename
sFileType = LCase$(Right$(Atmt.FileName, 4))
Debug.Print sFileType

Select Case sFileType
    ' Add additional file types below ".doc", "docx", ".xls"
    Case ".pdf"
</code>```

and before    Next

Add

```<code>  End Select
</code>```

Title: Outlook save only pdf attachments

Body:
Hi I have found this code and been using it for a while now but I am looking to add a rule to only save the PDF attachments and count how many PDF files have been saved.

I have got it saving all files and it loops the duplicated files but I just want it to save pdf files.

can someone assist please?

thanks

' ######################################################
'  Returns the number of attachements in the selection.
' ######################################################
Public Function SaveAttachmentsFromSelection() As Long
    Dim objFSO              As Object       ' Computer's file system object.
    Dim objShell            As Object       ' Windows Shell application object.
    Dim objFolder           As Object       ' The selected folder object from Browse for Folder dialog box.
    Dim objItem             As Object       ' A specific member of a Collection object either by position or by key.
    Dim selItems            As Selection    ' A collection of Outlook item objects in a folder.
    Dim Atmt                As Attachment   ' A document or link to a document contained in an Outlook item.
    Dim strAtmtPath         As String       ' The full saving path of the attachment.
    Dim strAtmtFullName     As String       ' The full name of an attachment.
    Dim strAtmtName(1)      As String       ' strAtmtName(0): to save the name; strAtmtName(1): to save the file extension. They are separated by dot of an attachment file name.
    Dim strAtmtNameTemp     As String       ' To save a temporary attachment file name.
    Dim intDotPosition      As Integer      ' The dot position in an attachment name.
    Dim atmts               As Attachments  ' A set of Attachment objects that represent the attachments in an Outlook item.
    Dim lCountEachItem      As Long         ' The number of attachments in each Outlook item.
    Dim lCountAllItems      As Long         ' The number of attachments in all Outlook items.
    Dim strFolderpath       As String       ' The selected folder path.
    Dim blnIsEnd            As Boolean      ' End all code execution.
    Dim blnIsSave           As Boolean      ' Consider if it is need to save.
    Dim oItem               As Object
    Dim iAttachments        As Integer

    blnIsEnd = False
    blnIsSave = False
    lCountAllItems = 0

    On Error Resume Next

    Set selItems = ActiveExplorer.Selection

    If Err.Number = 0 Then

        ' Get the handle of Outlook window.
        lHwnd = FindWindow(olAppCLSN, vbNullString)

        If lHwnd <> 0 Then

            ' /* Create a Shell application object to pop-up BrowseForFolder dialog box. */
            Set objShell = CreateObject("Shell.Application")
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objShell.BrowseForFolder(lHwnd, "Select folder to save attachments:", _
                                                     BIF_RETURNONLYFSDIRS + BIF_DONTGOBELOWDOMAIN, CSIDL_DESKTOP)

            ' /* Failed to create the Shell application. */
            If Err.Number <> 0 Then
                MsgBox "Run-time error '" & CStr(Err.Number) & " (0x" & CStr(Hex(Err.Number)) & ")':" & vbNewLine & _
                       Err.Description & ".", vbCritical, "Error from Attachment Saver"
                blnIsEnd = True
                GoTo PROC_EXIT
            End If

            If objFolder Is Nothing Then
                strFolderpath = ""
                blnIsEnd = True
                GoTo PROC_EXIT
            Else
                strFolderpath = CGPath(objFolder.Self.Path)

                ' /* Go through each item in the selection. */
                For Each objItem In selItems
                    lCountEachItem = objItem.Attachments.Count

                    ' /* If the current item contains attachments. */
                    If lCountEachItem > 0 Then
                        Set atmts = objItem.Attachments

                        ' /* Go through each attachment in the current item. */
                        For Each Atmt In atmts

                            ' Get the full name of the current attachment.
                            strAtmtFullName = Atmt.FileName

                            ' Find the dot postion in atmtFullName.
                            intDotPosition = InStrRev(strAtmtFullName, ".")

                            ' Get the name.
                            strAtmtName(0) = Left$(strAtmtFullName, intDotPosition - 1)
                            ' Get the file extension.
                            strAtmtName(1) = Right$(strAtmtFullName, Len(strAtmtFullName) - intDotPosition)
                            ' Get the full saving path of the current attachment.
                            strAtmtPath = strFolderpath & Atmt.FileName

                            ' /* If the length of the saving path is not larger than 260 characters.*/
                            If Len(strAtmtPath) <= MAX_PATH Then
                                ' True: This attachment can be saved.
                                blnIsSave = True

                                ' /* Loop until getting the file name which does not exist in the folder. */
                                Do While objFSO.FileExists(strAtmtPath)
                                    strAtmtNameTemp = strAtmtName(0) & _
                                                      Format(Now, "_mmddhhmmss") & _
                                                      Format(Timer * 1000 Mod 1000, "000")
                                    strAtmtPath = strFolderpath & strAtmtNameTemp & "." & strAtmtName(1)

                                    ' /* If the length of the saving path is over 260 characters.*/
                                    If Len(strAtmtPath) > MAX_PATH Then
                                        lCountEachItem = lCountEachItem - 1
                                        ' False: This attachment cannot be saved.
                                        blnIsSave = False
                                        Exit Do
                                    End If
                                Loop

                                ' /* Save the current attachment if it is a valid file name. */
                                If blnIsSave Then Atmt.SaveAsFile strAtmtPath
                            Else
                                lCountEachItem = lCountEachItem - 1
                            End If
                        Next
                    End If

                    ' Count the number of attachments in all Outlook items.
                    lCountAllItems = lCountAllItems + lCountEachItem
                Next
            End If
        Else
            MsgBox "Failed to get the handle of Outlook window!", vbCritical, "Error from Attachment Saver"
            blnIsEnd = True
            GoTo PROC_EXIT
        End If

    ' /* For run-time error:
    '    The Explorer has been closed and cannot be used for further operations.
    '    Review your code and restart Outlook. */
    Else
        MsgBox "Please select an Outlook item at least.", vbExclamation, "Message from Attachment Saver"
        blnIsEnd = True
    End If

PROC_EXIT:
    SaveAttachmentsFromSelection = lCountAllItems

    ' /* Release memory. */
    If Not (objFSO Is Nothing) Then Set objFSO = Nothing
    If Not (objItem Is Nothing) Then Set objItem = Nothing
    If Not (selItems Is Nothing) Then Set selItems = Nothing
    If Not (Atmt Is Nothing) Then Set Atmt = Nothing
    If Not (atmts Is Nothing) Then Set atmts = Nothing

    ' /* End all code execution if the value of blnIsEnd is True. */
    If blnIsEnd Then End
End Function

' #####################
' Convert general path.
' #####################
Public Function CGPath(ByVal Path As String) As String
    If Right(Path, 1) <> "\" Then Path = Path & "\"
    CGPath = Path
End Function

' ######################################
' Run this macro for saving attachments.
' ######################################
Public Sub ExecuteSaving()
    Dim oItem As Object
    Dim iAttachments As Integer

    For Each oItem In ActiveExplorer.Selection
    iAttachments = oItem.Attachments.Count + iAttachments
    Next
    MsgBox "Selected " & ActiveExplorer.Selection.Count & " messages with " & iAttachments & " attachements"
End Sub

Body:
Simply use  Select Case Statement faster to execute and easier to understand.. and more flexible to add additional file types

After

' /* Go through each attachment in the current item. */
For Each Atmt In atmts

Simply add

Dim sFileType As String
' Last 4 Characters in a Filename
sFileType = LCase$(Right$(Atmt.FileName, 4))
Debug.Print sFileType

Select Case sFileType
    ' Add additional file types below ".doc", "docx", ".xls"
    Case ".pdf"

and before    Next

Add

  End Select


问:
What type of application that allowed to auto-start in iPhone?
i wonder what type of application that are allowed to be started in the background/foreground when the iPhone boot , and are they limited to iOS 4 ? </p>

答:
I think voip applications. That's what Apple documentation states anyway and yes, they are limited to iOS 4.0. You should declare your application as voip and make according changes in the code. See the link:
Background Execution</p>


问:
Does Entity Framework Core support MariaDB?
Does Entity Framework Core support MariaDB?

I see it's not among the list of supported providers, but MySQL is. Maybe the MySQL provider would work against MariaDB?

答: I'm using the Pomelo MySql provider with Maria DB. It works great. MariaDB is just a fork of MySql,</p>


答:
2 is a standard error file descriptor.

File descriptor 1 is the standard output (stdout).
File descriptor 2 is the standard error (stderr).

```<code>2>error.log
</code>```

is used to redirect the standard error logs to a file named error.log

Title: What is "2" in command, while redirecting both System.out , System.err Java messages to file

Body:
I just figured that, we can redirect both System.out and System.err messages to  a file, am not able to understand this command which does redirecting while running this below file using : java StandarProgram> output.log 2>error.log

What is 2? and if am not using 2, error messages are displayed on console and not redirected to file? am not able to get this at all.

public class StandardProgram{

    public static void main(String[] args){

       System.out.println("Hello");
       System.err.println("World");

    }
}

Body:
2 is a standard error file descriptor.

File descriptor 1 is the standard output (stdout).
File descriptor 2 is the standard error (stderr).

2>error.log

is used to redirect the standard error logs to a file named error.log