问:
From input pass value to array and on replacing value in particular position in input replace at same place in array - JQuery/Javascript
In input box i am typing for example 123 . it should store in array as 123 on keypress . If i replace instead of 2 by 5. So input box will have value 153 and same value must be passed to array that is 135. How can i achieve this ?</p>

答:
```<code><input type="text" id="FirstValue" value="127" />
</code>```

Js part:

```<code>/* we create empty array for us to manipulate */
var collection = [];
/* find the input box, wait for changes and we do the logic */
/* if list is empty, insert the value of that input box and if it already has on, */
/* then we pop that element and insert that value */
var text = $('#FirstValue').on('change', function(this.value){
  if(collection.length == 0) {
    collection.push(this.value);
  } else if(collection.length == 1){
    collection.pop();
    collection.push(this.value);
  }
}
</code>```

You should go and search a bit about jquery click change keyup events. Quick articles would be good enough.

Body:
<input type="text" id="FirstValue" value="127" />

Js part:

/* we create empty array for us to manipulate */
var collection = [];
/* find the input box, wait for changes and we do the logic */
/* if list is empty, insert the value of that input box and if it already has on, */
/* then we pop that element and insert that value */
var text = $('#FirstValue').on('change', function(this.value){
  if(collection.length == 0) {
    collection.push(this.value);
  } else if(collection.length == 1){
    collection.pop();
    collection.push(this.value);
  }
}

You should go and search a bit about jquery click change keyup events. Quick articles would be good enough.


来源: stackexchange

问:
InternalError: current transaction is aborted, commands ignored until end of transaction block ,on UNIQUE constraint

I tried to get executed with my except: statement... while attempt to oppose the functionality of UNIQUE constraint..But ended with exceptional error..
The Postgresql database table already contains the row that I have used in

db.insert("The News","AparnaKumar",1995,234569654)

but it works well on inserting unrepeated rows..

```<code>import psycopg2
class database:

    def __init__(self):

        self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
        self.cur=self.con.cursor()
        self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
        self.con.commit()

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          print("already exists..")

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title=None,author=None,year=None,isbn=None):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.fetchall()
        print(row)

db=database()
db.insert("The News","AparnaKumar",1995,234569654)
db.view()
db.search(year=1995)
</code>```

答:
Use a SAVEPOINT.

See the second question in the psycopg FAQ list.

ContentLicense: CC BY-SA 3.0

Body:
I tried to get executed with my except: statement... while attempt to oppose the functionality of UNIQUE constraint..But ended with exceptional error..
The Postgresql database table already contains the row that I have used in

db.insert("The News","AparnaKumar",1995,234569654)

but it works well on inserting unrepeated rows..

import psycopg2
class database:

    def __init__(self):

        self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
        self.cur=self.con.cursor()
        self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
        self.con.commit()

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          print("already exists..")

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title=None,author=None,year=None,isbn=None):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.fetchall()
        print(row)

db=database()
db.insert("The News","AparnaKumar",1995,234569654)
db.view()
db.search(year=1995)


问:
How to give a .tf file as input in Terraform Apply command?
I'm a beginner in Terraform.

I have a directory which contains 2 .tf files.

Now I want to run Terraform Apply on a selected .tf file & neglect the other one.

Can I do that? If yes, how? If no, why & what is the best practice?

答:
You can't selectively apply one file and then the other. Two ways of (maybe) achieving what you're going for:

Use the -target flag to target resource(s) in one file and then the other.

Put each file (or more broadly, group of resources, which might be multiple files) in separate "modules" (folders). You can then apply them separately.

ContentLicense: CC BY-SA 4.0


问:
should the push server support https for apns?
A stupid question, as I have a bad head for HTTPS and SSLs.

The question is simple. As I've read at Apple APNS guide, there is required a SSL certificate. Should this certificate be linked only with my App ID or it should somehow represent my server to the WEB?

In other words: is it possible to set up the push-server over the HTTP, or it should be HTTPS only?

答:
SSL certificate is needed to verify/identify the sender and the app where push will be send to.

From article Certificate-Based Provider-to-APNs Trust

A certificate-based provider connection is valid for delivery to one specific app, identified by the topic (the app bundle ID) specified in the provider certificate (which you must have previously created, as explained in “Generate a universal APNs client SSL certificate” in Xcode Help)

To answer on your question:

Should this certificate be linked only with my App ID or it should somehow represent my server to the WEB?
    It have to be linked with your app id. And it is used to setup secure connection between your server(PN provider) and Apple Push Notifications server (for sending request from server to APNS)


问:
Constant dynamic image loading with Node js
Our team is developing a small web/native android application with Sails.js as our server framework.

One functionality requires sending a not-fixed number (between 10-100) of images, think of a comic reader.

I know we can do a single page view and request each image separately, but this seems to create a bottleneck with DB access and authorization of the user.

Is there a way to keep a constant stream of the images loading with the client?

Should I compress/optimize the images for each client?

Any advice is appreciated.

答:
We could help a lot better if you showed actual client and server code.  Authorizing a user on each incoming request should NOT be an expensive operation.  If it is, then you have a problem with that code.

If you're literally trying to down load 100 images from the server as separate images, that's just going to take 100 requests and you just need to make your server really efficient at serving those 100 requests (caching, really efficient DB, etc...).  You can parallelize the requests in the client so perhaps 10 at a time can be downloading.

In some cases, you can configure things for a client use a sprite where many separate images are combined in one file and the client is smart about displaying pieces of the main image to appear to show lots of separate images.  This is most effective when the groupings of images are known in advantage and can be pre-computed on the server and ready to serve.  If the client is requesting an arbitrary set of images, then a sprite probably won't be practical.

I know we can do a single page view and request each image separately, but this seems to create a bottleneck with DB access and authorization of the user.

That's how you do it.  You need to make your DB access and authorization very efficient to serve the large number of download queries.

Is there a way to keep a constant stream of the images loading with the client?

You can code the client to keep 10 requests in flight at any given time so you have some paralellism in your client downloading, but without overloading the server by sending all 100 requests at once.

Should I compress/optimize the images for each client?

Images should already be compressed.  If they are JPEG or PNG, they will already be compressed.  You can experiment with compression levels to optimize your compression.  Different subject matters can be optimized differently, sometimes achieving very high compression without unduly compromising the image quality (depends entirely upon the image subject matter).

You should certainly make sure your images are sized optimally so you aren't download a higher resolution than your client wants to display.  Downloading a 4k image when you only really need to display a 1k image is obviously a huge waste of bandwidth and download time.


问:
User of square brackets [ ] when appending link to head in JavaScript
I have been going through some code and converting all the jQuery to vanilla JS. Below is some code I converted successfully (commented out is the jQuery). I was having some trouble appending it to the head until I added [0] at the end.I know square brackets are used when accessing an array, but I'm not exactly sure why they were needed in this instance. Could someone explain?</p>

```<code>var head = document.getElementsByTagName('head')[0];
    var linkScript = document.createElement('link');
    linkScript.type = 'text/css';
    linkScript.rel = 'stylesheet';
    linkScript.href = purecommHostFiles + 'style.css';
    head.appendChild(linkScript);

    // $('<link>')
    //  .appendTo('head')
    //  .attr({
    //      type: 'text/css',
    //      rel: 'stylesheet',
    //      href: purecommHostFiles + 'style.css'
    //  });
</code>```

答: getElementsByTagName always returns an array-like HTMLCollection of elements, so you need to take the first element to access your  element.

Body:
I have been going through some code and converting all the jQuery to vanilla JS. Below is some code I converted successfully (commented out is the jQuery). I was having some trouble appending it to the head until I added [0] at the end.I know square brackets are used when accessing an array, but I'm not exactly sure why they were needed in this instance. Could someone explain?

var head = document.getElementsByTagName('head')[0];
    var linkScript = document.createElement('link');
    linkScript.type = 'text/css';
    linkScript.rel = 'stylesheet';
    linkScript.href = purecommHostFiles + 'style.css';
    head.appendChild(linkScript);

    // $('<link>')
    //  .appendTo('head')
    //  .attr({
    //      type: 'text/css',
    //      rel: 'stylesheet',
    //      href: purecommHostFiles + 'style.css'
    //  });

Body: getElementsByTagName always returns an array-like HTMLCollection of elements, so you need to take the first element to access your <head> element.


问:
How to implement Tags
I'm developing an application where i need to show the tags for every discussion and every comment as shown in image below. I'm getting the tags from service something like this.

```<code>tags =             (
                Registration,
                Apps,
                PublicSpeaking,
                Marketing,
                Sales
            );
</code>```

I want these tags to display under "tag" part of the given image.

this is how i was trying to implement, any kind of tutorial or link will be very helpful.

```<code>for (int i=0; i< [self.menuListArray count]; i++) {
    NSString *tag_string = [self.menuListArray objectAtIndex:i];
    CGSize tagSize = [tag_string sizeWithFont:[UIFont fontWithName:@"Roboto-Light" size:13.0]
                         constrainedToSize:CGSizeMake(230, FLT_MAX)
                             lineBreakMode:UILineBreakModeTailTruncation];
    UIImageView *tag_bgimage = [[UIImageView alloc]init];
    [tag_bgimage setFrame:CGRectMake(i*tagSize.width+5, stringSize.height+5, tagSize.width+4, 25)];
    [tag_bgimage setBackgroundColor:[UIColor grayColor]];
    [tag_bgimage setUserInteractionEnabled:NO];

    UILabel *tagLabel = [[UILabel alloc]init];
    [tagLabel setFrame:CGRectMake(0, 0, tagSize.width, 25)];
    [tagLabel setBackgroundColor:[UIColor clearColor]];
    [tagLabel setText:tag_string];
    [tagLabel setFont:[UIFont fontWithName:@"Roboto-Light" size:12.0]];
    [tagLabel setTextAlignment:NSTextAlignmentCenter];

    [tag_bgimage addSubview:tagLabel];
    [cell addSubview:tag_bgimage];
</code>```

}

答:
Instead of using addition framework, I recommend UICollectionView to implement Tags. It's less code, less overhead and easy to implement.

Follow this link for implementing:

https://codentrick.com/create-a-tag-flow-layout-with-uicollectionview/

This is how it looks like. Please note it is flexible too.

Hope this will help you

Title: How to implement Tags

Body:
I'm developing an application where i need to show the tags for every discussion and every comment as shown in image below. I'm getting the tags from service something like this.

tags =             (
                Registration,
                Apps,
                PublicSpeaking,
                Marketing,
                Sales
            );

I want these tags to display under "tag" part of the given image.

this is how i was trying to implement, any kind of tutorial or link will be very helpful.

for (int i=0; i< [self.menuListArray count]; i++) {
    NSString *tag_string = [self.menuListArray objectAtIndex:i];
    CGSize tagSize = [tag_string sizeWithFont:[UIFont fontWithName:@"Roboto-Light" size:13.0]
                         constrainedToSize:CGSizeMake(230, FLT_MAX)
                             lineBreakMode:UILineBreakModeTailTruncation];
    UIImageView *tag_bgimage = [[UIImageView alloc]init];
    [tag_bgimage setFrame:CGRectMake(i*tagSize.width+5, stringSize.height+5, tagSize.width+4, 25)];
    [tag_bgimage setBackgroundColor:[UIColor grayColor]];
    [tag_bgimage setUserInteractionEnabled:NO];

    UILabel *tagLabel = [[UILabel alloc]init];
    [tagLabel setFrame:CGRectMake(0, 0, tagSize.width, 25)];
    [tagLabel setBackgroundColor:[UIColor clearColor]];
    [tagLabel setText:tag_string];
    [tagLabel setFont:[UIFont fontWithName:@"Roboto-Light" size:12.0]];
    [tagLabel setTextAlignment:NSTextAlignmentCenter];

    [tag_bgimage addSubview:tagLabel];
    [cell addSubview:tag_bgimage];

}


问:
Form Builder GUI for PHP
I'm looking around for an open source form building package for PHP, and figured the hive-mob-mind of StackOverflow might be able to tilt me in the right direction.

Specifically, I'm looking for a form/survey builder application.  I want something that lets an end user use a web based GUI to create and configure/surveys and web-based forms.

What are the de-facto standard tools/packages that people use for this kind of thing these days.  I'm interested in software packages, not in hosted services.

答:
I think you want something with a GUI that your users can use to make forms...

Try this..

http://blog.sonuku.com/2009/04/11/php-formbuilder/

-FT

ContentLicense: CC BY-SA 2.5

Title: Form Builder GUI for PHP


问:
How to identify a word with a dollar sign $
I am trying to extract information based on if a string starts with a dollar sign.

I have a string "I bought $BTC"

I am trying to get if word in string starts with dollar sign, get me the word. So I am trying to get in this case "BTC". I tried, string.replace methods and findall, however cannot extract this information. I further read that dollar sign is used as interpolation in Python, I am assuming this is causing the issue.

Are there any ideas that can help me with this?

答:
Following code blocks works for me - returns "BTC". Regex in question is "\$(\w+)"

```<code>import re

test = "I bought $BTC today"
result = re.search("\$(\w+)", test)
print result.group(1)
</code>```

Group(1) specifies that you're after the characters within the brackets.

Body:
Following code blocks works for me - returns "BTC". Regex in question is "\$(\w+)"

import re

test = "I bought $BTC today"
result = re.search("\$(\w+)", test)
print result.group(1)

Group(1) specifies that you're after the characters within the brackets.


问:
Quicksort Algorithm in a doubly linked list
I want to sort a list by last names with the algorithm of Quicksort but when exchanging the elements it does not work, it leaves them as they were

In this part the values of the chains are exchanged

```<code>void swap(string* a, string* b){

cout<<"A and B are "<<*a<<" - "<<*b<<endl;

string t = *a;
*a = *b;
cout<<" A is ->"<<*a<<endl;

*b= t;
cout<<"B is ->"<<*b<<endl;

}
</code>```

This is where the partition is made. I have noticed that when * i and * j take values they are exactly the same names and therefore can not be compared later. It seems strange to me that this list works if it is a number but when it is strings this error occurs.

```<code>User *i = lower;
</code>```

But this did not work at the end because the program crashed, but if you change the value of the string

```<code>User* partition(User *lower, User *high){

cout<<"Lower ->  "<<lower->lastname<<endl;
cout<<"High ->  "<<high->lastname<<endl;
string  pivot = high->lastname;
User *i = bajo->prev;
 for (User *j = lower; j != high; j = j->next)
{
    if (j->lastname.compare(pivot)< 0)
    {
        i = (i == NULL)? lower : i->next;
        cout<<"Atention J e I valen ->"<<i->lastname<<" - "<<j->lastname<<endl;
        swap(&(i->lastname), &(j->lastname));
    }
}
i = (i == NULL)? lower : i->lastname; // Similar to i++
swap(&(i->lastname), &(alto->lastname));
return i;
}
</code>```

What am I failing? How can I make it really take the desired value.

EDITED:

This is the source code

```<code>#include <iostream>
#include<iomanip>
#include <string>
#include<cstdlib>

using namespace std;

class User
{

public :
    string lastname;
    User *next;
    User *prev;
    User()
    {
        lastname= "";
        next=NULL;
        prev=NULL;

    }
    int empty(User *listt)
    {

        if(listt ==  NULL)
        {

            return 1;
        }
        else
        {

            return 0;
        }

    }

    User *Insert(User *listt, string lastName)
    {

        User *temp = new User();

        if(empty(listt))
        {

            temp->lastname=lastName;
            listt = temp;

        }
        else
        {

            temp->lastname=lastName;
            listt->prev=temp;
            temp->next=listt;
            listt=temp;

        }
        return listt;
    }
    void swap(string* a, string* b)
    {

        string t = *a;
        *a = *b;

        *b= t;

    }
    User* partition(User* lower, User* high)
    {

        cout<<"Lower ->  "<<lower->lastname<<endl;
        cout<<"High ->  "<<high->lastname<<endl;
        string  pivot = high->lastname;
        User *i = lower->prev;
        for (User *j = lower; j != high; j = j->next)
        {
            if (j->lastname.compare(pivot)< 0)
            {
                i = (i == NULL)? lower : i->next;
                swap(&(i->lastname), &(j->lastname));
            }
        }
        i = (i == NULL)? lower : i->next; // Similar to i++
        swap(&(i->lastname), &(high->lastname));
        return i;
    }
    User *Last(User *listt)
    {
        User *temp = listt;

        while(temp && temp ->next)
            temp=temp->next;
        return temp;

    }
    void _quickSort( User* lower, User* high)
    {

        if(high != NULL && lower != high&&lower!= high->next)
        {
            User *p = partition(lower,high);
            _quickSort(lower,p->next); //I change this part
            _quickSort(p->next,high);

        }

    }
    void quickSort(User *listt)
    {
        User *h = Last(listt);

        _quickSort(listt, h);

    }
    User *Display(User *listt)
    {

        if(empty(listt))
        {

            cout<<"List empty"<<endl;

        }
        else
        {

            User *temp = new User();
            temp = listt;
            while(temp!= NULL)
            {

                cout<<"The last name is -> "<<temp->lastname<<endl;
                temp=temp->next;
            }

        }
        return listt;

    }
};

int main()
{

    User *listt = NULL;
    User y;
    bool exit = false;
    int opc;
    string lastName;
    while(!exit)
    {

        cout<<"1.-Insert an element"<<endl;
        cout<<"2.-Sort element-(Quicksort)"<<endl;
        cout<<"3.-Show elements"<<endl;
        cout<<"4.-Exitt"<<endl;
        cin>>opc;
        switch(opc)
        {
        case 1:
            cout<<"Inser your last name"<<endl;
            cin>>lastName;
            listt=y.Insert(listt,lastName);
            system("pause");
            system("cls");
            break;
        case 2:
            cout<<"Sorting...."<<endl;
            y.quickSort(listt);
            system("pause");
            system("cls");
            break;
        case 3:
            cout<<"Display..."<<endl;
            y.Display(listt);
            system("pause");
            system("cls");
            break;
        case 4:
            exit = true;
            break;

        }

    }

}
</code>```

答:
```<code>_quickSort(lower,p->next); //I change this part
</code>```

This should be p->prev. The correct function:

```<code>void _quickSort(User* lower, User* high)
{
    if(high != NULL && lower != high&&lower != high->next)
    {
        User *p = partition(lower, high);
        _quickSort(lower, p->prev); //change it back!
        _quickSort(p->next, high);
    }
}
</code>```

Additionally there is resource leak in Display. Don't allocate new items in display function:

```<code>User *Display(User *listt)
{
    if(empty(listt))
    {
        cout<<"List empty"<<endl;
    }
    else
    {
        //User *temp = new User(); <== don't allocate new item here
        User *temp = listt;
        while(temp!= NULL)
        {
            cout<<"The last name is -> "<<temp->lastname<<endl;
            temp=temp->next;
        }

    }
    return listt;
}
</code>```

Testing with a 1000 items:

```<code>class User
{
public:
    class Node
    {
    public:
        string lastname;
        Node *next;
        Node *prev;
        Node()
        {
            prev = next = nullptr;
        }
    };

    Node *head;
    User()
    {
        head = nullptr;
    }

    void Insert(string val)
    {
        Node *temp = new Node;
        temp->lastname = val;
        if (head)
        {
            head->prev = temp;
            temp->next = head;
        }
        head = temp;
    }

    void swap(string &a, string &b)
    {
        string t = a;
        a = b;
        b = t;
    }

    Node *Tail()
    {
        Node *temp = head;
        while(temp && temp->next)
            temp = temp->next;
        return temp;
    }

    Node* partition(Node* left, Node* right)
    {
        string pivot = right->lastname;
        Node *i = left->prev;
        for(Node *j = left; j != right; j = j->next)
        {
            if(j->lastname < pivot)
            {
                i = (i == nullptr) ? left : i->next;
                swap(i->lastname, j->lastname);
            }
        }
        i = (i == nullptr) ? left : i->next; // Similar to i++
        swap(i->lastname, right->lastname);
        return i;
    }

    void quickSort(Node* left, Node* right)
    {
        if(!left || !right || left == right || left == right->next)
            return;
        Node *p = partition(left, right);
        quickSort(left, p->prev);
        quickSort(p->next, right);
    }

    void quickSort()
    {
        quickSort(head, Tail());
    }

    void Display()
    {
        string last;
        for (Node *n = head; n; n = n->next)
        {
            if(n->lastname < last)
            {
                cout << "error ***\n";
                break;
            }
            last = n->lastname;
            cout << n->lastname << endl;
        }
    }
};

int main()
{
    User list;

    list.Insert("z");
    list.Insert("c");
    list.Insert("a");
    list.Insert("g");

    for(int i = 0; i < 1000; i++)
    {
        string str;
        for (int j = 0; j < 3; j++)
            str.push_back('a' + rand() % 26);
        list.Insert(str);
    }

    list.quickSort();
    list.Display();

    return 0;
}
</code>```

Body:
I want to sort a list by last names with the algorithm of Quicksort but when exchanging the elements it does not work, it leaves them as they were

In this part the values of the chains are exchanged

void swap(string* a, string* b){

cout<<"A and B are "<<*a<<" - "<<*b<<endl;

string t = *a;
*a = *b;
cout<<" A is ->"<<*a<<endl;

*b= t;
cout<<"B is ->"<<*b<<endl;

}

This is where the partition is made. I have noticed that when * i and * j take values they are exactly the same names and therefore can not be compared later. It seems strange to me that this list works if it is a number but when it is strings this error occurs.

User *i = lower;

But this did not work at the end because the program crashed, but if you change the value of the string

User* partition(User *lower, User *high){

cout<<"Lower ->  "<<lower->lastname<<endl;
cout<<"High ->  "<<high->lastname<<endl;
string  pivot = high->lastname;
User *i = bajo->prev;
 for (User *j = lower; j != high; j = j->next)
{
    if (j->lastname.compare(pivot)< 0)
    {
        i = (i == NULL)? lower : i->next;
        cout<<"Atention J e I valen ->"<lastname<<" - "<<j->lastname<<endl;
        swap(&(i->lastname), &(j->lastname));
    }
}
i = (i == NULL)? lower : i->lastname; // Similar to i++
swap(&(i->lastname), &(alto->lastname));
return i;
}

What am I failing? How can I make it really take the desired value.

EDITED:

This is the source code

#include <iostream>
#include<iomanip>
#include <string>
#include<cstdlib>

using namespace std;

class User
{

public :
    string lastname;
    User *next;
    User *prev;
    User()
    {
        lastname= "";
        next=NULL;
        prev=NULL;

    }
    int empty(User *listt)
    {

        if(listt ==  NULL)
        {

            return 1;
        }
        else
        {

            return 0;
        }

    }

    User *Insert(User *listt, string lastName)
    {

        User *temp = new User();

        if(empty(listt))
        {

            temp->lastname=lastName;
            listt = temp;

        }
        else
        {

            temp->lastname=lastName;
            listt->prev=temp;
            temp->next=listt;
            listt=temp;

        }
        return listt;
    }
    void swap(string* a, string* b)
    {

        string t = *a;
        *a = *b;

        *b= t;

    }
    User* partition(User* lower, User* high)
    {

        cout<<"Lower ->  "<<lower->lastname<<endl;
        cout<<"High ->  "<<high->lastname<<endl;
        string  pivot = high->lastname;
        User *i = lower->prev;
        for (User *j = lower; j != high; j = j->next)
        {
            if (j->lastname.compare(pivot)< 0)
            {
                i = (i == NULL)? lower : i->next;
                swap(&(i->lastname), &(j->lastname));
            }
        }
        i = (i == NULL)? lower : i->next; // Similar to i++
        swap(&(i->lastname), &(high->lastname));
        return i;
    }
    User *Last(User *listt)
    {
        User *temp = listt;

        while(temp && temp ->next)
            temp=temp->next;
        return temp;

    }
    void _quickSort( User* lower, User* high)
    {

        if(high != NULL && lower != high&&lower!= high->next)
        {
            User *p = partition(lower,high);
            _quickSort(lower,p->next); //I change this part
            _quickSort(p->next,high);

        }

    }
    void quickSort(User *listt)
    {
        User *h = Last(listt);

        _quickSort(listt, h);

    }
    User *Display(User *listt)
    {

        if(empty(listt))
        {

            cout<<"List empty"<<endl;

        }
        else
        {

            User *temp = new User();
            temp = listt;
            while(temp!= NULL)
            {

                cout<<"The last name is -> "<<temp->lastname<<endl;
                temp=temp->next;
            }

        }
        return listt;

    }
};

int main()
{

    User *listt = NULL;
    User y;
    bool exit = false;
    int opc;
    string lastName;
    while(!exit)
    {

        cout<<"1.-Insert an element"<<endl;
        cout<<"2.-Sort element-(Quicksort)"<<endl;
        cout<<"3.-Show elements"<<endl;
        cout<<"4.-Exitt"<<endl;
        cin>>opc;
        switch(opc)
        {
        case 1:
            cout<<"Inser your last name"<<endl;
            cin>>lastName;
            listt=y.Insert(listt,lastName);
            system("pause");
            system("cls");
            break;
        case 2:
            cout<<"Sorting...."<<endl;
            y.quickSort(listt);
            system("pause");
            system("cls");
            break;
        case 3:
            cout<<"Display..."<<endl;
            y.Display(listt);
            system("pause");
            system("cls");
            break;
        case 4:
            exit = true;
            break;

        }

    }

}

Body:
_quickSort(lower,p->next); //I change this part

This should be p->prev. The correct function:

void _quickSort(User* lower, User* high)
{
    if(high != NULL && lower != high&&lower != high->next)
    {
        User *p = partition(lower, high);
        _quickSort(lower, p->prev); //change it back!
        _quickSort(p->next, high);
    }
}

Additionally there is resource leak in Display. Don't allocate new items in display function:

User *Display(User *listt)
{
    if(empty(listt))
    {
        cout<<"List empty"<<endl;
    }
    else
    {
        //User *temp = new User(); <== don't allocate new item here
        User *temp = listt;
        while(temp!= NULL)
        {
            cout<<"The last name is -> "<<temp->lastname<<endl;
            temp=temp->next;
        }

    }
    return listt;
}

Testing with a 1000 items:

class User
{
public:
    class Node
    {
    public:
        string lastname;
        Node *next;
        Node *prev;
        Node()
        {
            prev = next = nullptr;
        }
    };

    Node *head;
    User()
    {
        head = nullptr;
    }

    void Insert(string val)
    {
        Node *temp = new Node;
        temp->lastname = val;
        if (head)
        {
            head->prev = temp;
            temp->next = head;
        }
        head = temp;
    }

    void swap(string &a, string &b)
    {
        string t = a;
        a = b;
        b = t;
    }

    Node *Tail()
    {
        Node *temp = head;
        while(temp && temp->next)
            temp = temp->next;
        return temp;
    }

    Node* partition(Node* left, Node* right)
    {
        string pivot = right->lastname;
        Node *i = left->prev;
        for(Node *j = left; j != right; j = j->next)
        {
            if(j->lastname < pivot)
            {
                i = (i == nullptr) ? left : i->next;
                swap(i->lastname, j->lastname);
            }
        }
        i = (i == nullptr) ? left : i->next; // Similar to i++
        swap(i->lastname, right->lastname);
        return i;
    }

    void quickSort(Node* left, Node* right)
    {
        if(!left || !right || left == right || left == right->next)
            return;
        Node *p = partition(left, right);
        quickSort(left, p->prev);
        quickSort(p->next, right);
    }

    void quickSort()
    {
        quickSort(head, Tail());
    }

    void Display()
    {
        string last;
        for (Node *n = head; n; n = n->next)
        {
            if(n->lastname < last)
            {
                cout << "error ***\n";
                break;
            }
            last = n->lastname;
            cout << n->lastname << endl;
        }
    }
};

int main()
{
    User list;

    list.Insert("z");
    list.Insert("c");
    list.Insert("a");
    list.Insert("g");

    for(int i = 0; i < 1000; i++)
    {
        string str;
        for (int j = 0; j < 3; j++)
            str.push_back('a' + rand() % 26);
        list.Insert(str);
    }

    list.quickSort();
    list.Display();

    return 0;
}


问:
Comparing rotated images
I'm looking for a way to compare images that are almost identical (95%+ similarity) but that could be rotated around a central axis.

I'm new to the whole computer graphics/vision field, and not really sure if there is a ready built tool or system for it, or even if this is the right stack exchange to ask on.

Currently, I'm investigating using C# to generate a bitmap histogram, then running it through Panda for analysis and to ideally group the images based on the similarity of histograms, though I've heard something like OpenCv + tesseract may be a viable alternative.

答:
You can compare image similarity using feature point extraction and matching using rotation and scale invariant algorithms.

Already rotation invariant feature matching algorithms are available in OpenCV -  SIFT
,SURF but these are patented so you have to pay if you want to use them commercially.

Fortunately an efficient alternative to SIFT or SURF is available namely ORB (Oriented FAST and Rotated BRIEF)

These algorithms work fine in most of the images except a few like document images.

PS: As mentioned in the question (OpenCV + tesseract) alternatively can be used for document images by extracting the text contents in the image using Tesseract library(Opensource OCR engine)

Title: Comparing rotated images


问:
Profile is not an "iOS App Store" profile
Using Xcode 9.

Working on app store build validation.

Created an app with app store profile.

Archived successfully

Trying to validate build in
Organizer, I am getting the following error on selecting the
profile.

This is the same profile used to archive and it is an app store profile.

2 Queries

How to identify a profile if it is ad-hoc or app store

Why did this happen?Pretty sure this is an appstore profile.

答:
I think you are selected Ad Hoc option to get .ipa file. Select App Store option to get the .ipa file, then use Application loader to submit .ipa file.

In my case i'm getting email like this...

```<code>Missing beta entitlement - Your app does not include the beta-reports-active entitlement. If you intend to distribute this build via TestFlight for beta testing, please re-build this app with an App Store Distribution provisioning profile. Do not use ad-hoc profiles.

After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.

Regards,
The App Store team
</code>```

Then i changed the option from Ad Hoc to App Store...
enter image description here

Body:
I think you are selected Ad Hoc option to get .ipa file. Select App Store option to get the .ipa file, then use Application loader to submit .ipa file.

In my case i'm getting email like this...

Missing beta entitlement - Your app does not include the beta-reports-active entitlement. If you intend to distribute this build via TestFlight for beta testing, please re-build this app with an App Store Distribution provisioning profile. Do not use ad-hoc profiles.

After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.

Regards,
The App Store team

Then i changed the option from Ad Hoc to App Store...
enter image description here


问:
How can I add a footer to the bottom of each page of a postscript or pdf file in linux?
So I'd like to add a "footer" (an attribution) to the bottom of every page of a pdf file I am generating via postscript with groff in linux. I am converting the file from ps to pdf myself, with the ps2pdf tool, so I have access to both formats.

These two posts have been somewhat helpful:

How to add page numbers to Postscript/PDF

How can I make a program overlay text on a postscript file?

I'm not against using the first method, but I don't have access to the pdflatex utility mentioned in the first script, nor do I have the option to install it on the machine that needs to do the work.

It looks like the second method could possibly work, but I have version 8.15 of ghostscript installed and I didn't see many of the flags listed on the man page ( http://unix.browserdebug.com/man/gs/ ). I think I have access to the "-c" flag to insert some postscript code, even though it is not listed. Anyhow, here are two commands I tried unsuccessfully:

```
gs -o output.pdf -sDEVICE=pdfwrite -g5030x5320 \
-c "/Helvetica-Italic findfont 15 scalefont setfont 453 482 moveto (test-string) show" \
-f input.ps
```

that gives me this:

```
Unknown switch -o - ignoring
ESP Ghostscript 815.02 (2006-04-19)
Copyright (C) 2004 artofcode LLC, Benicia, CA.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
ERROR: /undefinedfilename in (output.pdf)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
   --dict:1117/1686(ro)(G)--   --dict:0/20(G)--   --dict:102/200(L)--
Current allocation mode is local
Last OS error: 2
ESP Ghostscript 815.02: Unrecoverable error, exit code 1
```

So obviously the -o flag has a problem and so I did some research and tried this syntax:

```

gs -sOUTPUTFILE=output.pdf -sDEVICE=pdfwrite -g5030x5320 \
-c "/Helvetica-Italic findfont 15 scalefont setfont 453 482 moveto (test-string) show" \
-f input.ps

```

which outputs this and makes me hit return 4 times (maybe there are 4 pages in input.ps)

```

ESP Ghostscript 815.02 (2006-04-19)
Copyright (C) 2004 artofcode LLC, Benicia, CA.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Can't find (or can't open) font file /usr/share/ghostscript/8.15/Resource/Font/Helvetica-Italic.
Can't find (or can't open) font file Helvetica-Italic.
Querying operating system for font files...
Didn't find this font on the system!
Substituting font Helvetica-Oblique for Helvetica-Italic.
Loading NimbusSanL-ReguItal font from /usr/share/fonts/default/Type1/n019023l.pfb... 3742416 2168114 2083056 759694 1 done.
Loading NimbusRomNo9L-ReguItal font from /usr/share/fonts/default/Type1/n021023l.pfb... 3781760 2362033 2365632 1015713 1 done.
Loading NimbusRomNo9L-Medi font from /usr/share/fonts/default/Type1/n021004l.pfb... 3865136 2547267 2365632 1029818 1 done.
Loading NimbusRomNo9L-Regu font from /usr/share/fonts/default/Type1/n021003l.pfb... 4089592 2759001 2365632 1032885 1 done.
Using NimbusRomanNo9L-Regu font for NimbusRomNo9L-Regu.
>>showpage, press <return> to continue<<

>>showpage, press <return> to continue<<

>>showpage, press <return> to continue<<

>>showpage, press <return> to continue<<

```

So it seems like it would be simple enough to use gs to simply insert something in a ps file, but it is proving to be quite complicated...

答:
ESP Ghostscript is O-o-o-o-old. Don't use it any more unless you absolutely, absolutely cannot avoid it. It was a fork of the original Ghostscript which used by CUPS for a while. (And after some problems between developers where resolved, more recent versions of CUPS now also use the GPL Ghostscript again...)

Newer GPL Ghostscript versions are here: http://www.ghostscript.com/releases/

Also, -o out.pdf is only a shorthand for -dBATCH -dNOPAUSE -sOutputFile=out.pdf. So you should try this. (The -dNOPAUSE part relieves you from hitting <return> for every page advance....).

Lastly, don't expect the full range of documentation being provided by a third party man gs page. Rather refer to the original Ghostscript documentation for the version you use, the most important parts being:

current development branch: Readme.htm + Use.htm + Ps2pdf.htm

9.00 release: Readme.htm + Use.htm + Ps2pdf.htm

8.71 release: Readme.htm + Use.htm + Ps2pdf.htm

Update: Ghostscript has moved to Git (instead of Subversion) for their source code repository. Therefor the following links have changed, repeatedly:

current development branch: Readme.htm + Use.htm + Ps2pdf.htm

current development branch: Readme.htm + Use.htm + Ps2pdf.htm

Body:
So I'd like to add a "footer" (an attribution) to the bottom of every page of a pdf file I am generating via postscript with groff in linux. I am converting the file from ps to pdf myself, with the ps2pdf tool, so I have access to both formats.

These two posts have been somewhat helpful:

How to add page numbers to Postscript/PDF

How can I make a program overlay text on a postscript file?

I'm not against using the first method, but I don't have access to the pdflatex utility mentioned in the first script, nor do I have the option to install it on the machine that needs to do the work.

It looks like the second method could possibly work, but I have version 8.15 of ghostscript installed and I didn't see many of the flags listed on the man page ( http://unix.browserdebug.com/man/gs/ ). I think I have access to the "-c" flag to insert some postscript code, even though it is not listed. Anyhow, here are two commands I tried unsuccessfully:

gs -o output.pdf -sDEVICE=pdfwrite -g5030x5320 \
-c "/Helvetica-Italic findfont 15 scalefont setfont 453 482 moveto (test-string) show" \
-f input.ps

that gives me this:

Unknown switch -o - ignoring
ESP Ghostscript 815.02 (2006-04-19)
Copyright (C) 2004 artofcode LLC, Benicia, CA.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
ERROR: /undefinedfilename in (output.pdf)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
   --dict:1117/1686(ro)(G)--   --dict:0/20(G)--   --dict:102/200(L)--
Current allocation mode is local
Last OS error: 2
ESP Ghostscript 815.02: Unrecoverable error, exit code 1

So obviously the -o flag has a problem and so I did some research and tried this syntax:

gs -sOUTPUTFILE=output.pdf -sDEVICE=pdfwrite -g5030x5320 \
-c "/Helvetica-Italic findfont 15 scalefont setfont 453 482 moveto (test-string) show" \
-f input.ps

which outputs this and makes me hit return 4 times (maybe there are 4 pages in input.ps)

ESP Ghostscript 815.02 (2006-04-19)
Copyright (C) 2004 artofcode LLC, Benicia, CA.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Can't find (or can't open) font file /usr/share/ghostscript/8.15/Resource/Font/Helvetica-Italic.
Can't find (or can't open) font file Helvetica-Italic.
Querying operating system for font files...
Didn't find this font on the system!
Substituting font Helvetica-Oblique for Helvetica-Italic.
Loading NimbusSanL-ReguItal font from /usr/share/fonts/default/Type1/n019023l.pfb... 3742416 2168114 2083056 759694 1 done.
Loading NimbusRomNo9L-ReguItal font from /usr/share/fonts/default/Type1/n021023l.pfb... 3781760 2362033 2365632 1015713 1 done.
Loading NimbusRomNo9L-Medi font from /usr/share/fonts/default/Type1/n021004l.pfb... 3865136 2547267 2365632 1029818 1 done.
Loading NimbusRomNo9L-Regu font from /usr/share/fonts/default/Type1/n021003l.pfb... 4089592 2759001 2365632 1032885 1 done.
Using NimbusRomanNo9L-Regu font for NimbusRomNo9L-Regu.
>>showpage, press <return> to continue<<

>>showpage, press <return> to continue<<

>>showpage, press <return> to continue<<

>>showpage, press <return> to continue<<

So it seems like it would be simple enough to use gs to simply insert something in a ps file, but it is proving to be quite complicated...


问:
AWS Bucket Policy Error: Policy has invalid action
I have a very basic goal: to share all content of my bucket to a list of specific users, read only. This used to work with a tool called s3cmd. All I need to do was to add a user (identified by email) to the Access Control List with Read Permission, and they could list or download data smoothly.

But recently, this suddenly did not work anymore. The system just denies any attempt to access my bucket.

I then started thinking of editing the bucket policy. Here is the draft of my policy, generated by the Policy Generator (sensitive information is anonymized):

    {
      "Id": "Policy123456789",
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "Stmt1512705836469",
          "Action": [
            "s3:GetObject",
            "s3:ListBucket",
            "s3:ListObjects"
          ],
          "Effect": "Allow",
          "Resource": "arn:aws:s3:::mybucketname",
          "Principal": {
            "AWS": [
              "arn:aws:iam::anotheruserid:user/admin"
            ]
          }
        }
      ]
    }
```
<p>When I click <code>save</code>, I get a "<strong>Policy has invalid action</strong>" error. I then tried to remove "<em>ListObjects</em>" so the policy becomes</p>
<pre class="lang-json prettyprint-override"><code>    {
      "Id": "Policy123456789",
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "Stmt1512705836469",
          "Action": [
            "s3:GetObject",
            "s3:ListBucket"
          ],
          "Effect": "Allow",
          "Resource": "arn:aws:s3:::mybucketname",
          "Principal": {
            "AWS": [
              "arn:aws:iam::anotheruserid:user/admin"
            ]
          }
        }
      ]
    }
</code>```

and got another error message "Action does not apply to any resource(s) in statement".

These two errors do not make sense to me. Please correct me if I am wrong. If I am not in the right direction, please help me.

BTW: I tried to follow the tutorial at
http://docs.aws.amazon.com/AmazonS3/latest/dev/example-walkthroughs-managing-access-example2.html
but wasn't successful. By using the following bucket policy:

    {
       "Version": "2012-10-17",
       "Statement": [
          {
             "Sid": "Example permissions",
             "Effect": "Allow",
             "Principal": {
                "AWS": "arn:aws:iam::AccountB-ID:root"
             },
             "Action": [
                "s3:GetBucketLocation",
                "s3:ListBucket"
             ],
             "Resource": [
                "arn:aws:s3:::examplebucket"
             ]
          }
       ]
    }
```

I got an error message when using awscli of AccountB to execute "aws s3 ls s3://examplebucket".

The error message was "An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied".

This confuses me. If I add ListObjects, I got an "invalid" error.

If I remove the "ListObjects", another user could not read my bucket content.

What should I do?

答:
I suspect that the Policy Editor has become smarter when it comes to operations that operate on buckets as opposed to within buckets.

Also, ListObjects seems to be upsetting it, so leave it out.

This policy allows the contents of a bucket to be listed and objects retrieved:

```<code>{
    "Id": "Policy1",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ],
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:user/user-name"
            }
        }
    ]
}
</code>```

ListBucket operates on the Bucket.

GetObject operates on the contents of a bucket.

It could be written as two separate statements within the policy (one on the bucket, one on the contents of the bucket), but it's often easier to write it as above.

Body:
I have a very basic goal: to share all content of my bucket to a list of specific users, read only. This used to work with a tool called s3cmd. All I need to do was to add a user (identified by email) to the Access Control List with Read Permission, and they could list or download data smoothly.

But recently, this suddenly did not work anymore. The system just denies any attempt to access my bucket.

I then started thinking of editing the bucket policy. Here is the draft of my policy, generated by the Policy Generator (sensitive information is anonymized):

    {
      "Id": "Policy123456789",
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "Stmt1512705836469",
          "Action": [
            "s3:GetObject",
            "s3:ListBucket",
            "s3:ListObjects"
          ],
          "Effect": "Allow",
          "Resource": "arn:aws:s3:::mybucketname",
          "Principal": {
            "AWS": [
              "arn:aws:iam::anotheruserid:user/admin"
            ]
          }
        }
      ]
    }

When I click save, I get a "Policy has invalid action" error. I then tried to remove "ListObjects" so the policy becomes

    {
      "Id": "Policy123456789",
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "Stmt1512705836469",
          "Action": [
            "s3:GetObject",
            "s3:ListBucket"
          ],
          "Effect": "Allow",
          "Resource": "arn:aws:s3:::mybucketname",
          "Principal": {
            "AWS": [
              "arn:aws:iam::anotheruserid:user/admin"
            ]
          }
        }
      ]
    }

and got another error message "Action does not apply to any resource(s) in statement".

These two errors do not make sense to me. Please correct me if I am wrong. If I am not in the right direction, please help me.

BTW: I tried to follow the tutorial at
http://docs.aws.amazon.com/AmazonS3/latest/dev/example-walkthroughs-managing-access-example2.html
but wasn't successful. By using the following bucket policy:

    {
       "Version": "2012-10-17",
       "Statement": [
          {
             "Sid": "Example permissions",
             "Effect": "Allow",
             "Principal": {
                "AWS": "arn:aws:iam::AccountB-ID:root"
             },
             "Action": [
                "s3:GetBucketLocation",
                "s3:ListBucket"
             ],
             "Resource": [
                "arn:aws:s3:::examplebucket"
             ]
          }
       ]
    }

I got an error message when using awscli of AccountB to execute "aws s3 ls s3://examplebucket".

The error message was "An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied".

This confuses me. If I add ListObjects, I got an "invalid" error.

If I remove the "ListObjects", another user could not read my bucket content.

What should I do?

Body:
I suspect that the Policy Editor has become smarter when it comes to operations that operate on buckets as opposed to within buckets.

Also, ListObjects seems to be upsetting it, so leave it out.

This policy allows the contents of a bucket to be listed and objects retrieved:

{
    "Id": "Policy1",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ],
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:user/user-name"
            }
        }
    ]
}

ListBucket operates on the Bucket.

GetObject operates on the contents of a bucket.

It could be written as two separate statements within the policy (one on the bucket, one on the contents of the bucket), but it's often easier to write it as above.


问:
Google Assistant sdk GRPC authentication error : io.grpc.StatusRuntimeException: UNAUTHENTICATED:
I successfully created EmbeddedAssistantStub using the below code.

```<code>EmbeddedAssistantGrpc.EmbeddedAssistantStub mAssistantService = EmbeddedAssistantGrpc.newStub(channel)
                                  .withCallCredentials(MoreCallCredentials.from(
                                            Credentials.fromResource(mClientId,mRefreshToken,mAccessToken)
                                   ));
</code>```

After this i passed audio data to StreamObserver, At that time below exxception was occured.

```<code>Line 3378: 12-07 12:59:25.099  1917  4286 E  GASample: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Line 3378: 12-07 12:59:25.099  1917  4286 E  GASample: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Line 3379: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.Status.asRuntimeException(Status.java:540)
Line 3380: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:392)
Line 3381: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:428)
Line 3382: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:76)
Line 3383: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:514)
Line 3384: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$700(ClientCallImpl.java:431)
Line 3385: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:546)
Line 3386: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
Line 3387: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.SerializingExecutor$TaskRunner.run(SerializingExecutor.java:152)
Line 3388: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
Line 3389: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
Line 3390: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.lang.Thread.run(Thread.java:764)
</code>```

After this no response from response observer.

Kindly help me to solve this issue.

答:
They fixed this issue at back-end.</p>

<p>@JHorseman : Thanks for the support. </p>

Body:
I successfully created EmbeddedAssistantStub using the below code.

EmbeddedAssistantGrpc.EmbeddedAssistantStub mAssistantService = EmbeddedAssistantGrpc.newStub(channel)
                                  .withCallCredentials(MoreCallCredentials.from(
                                            Credentials.fromResource(mClientId,mRefreshToken,mAccessToken)
                                   ));

After this i passed audio data to StreamObserver, At that time below exxception was occured.

Line 3378: 12-07 12:59:25.099  1917  4286 E  GASample: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Line 3378: 12-07 12:59:25.099  1917  4286 E  GASample: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Line 3379: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.Status.asRuntimeException(Status.java:540)
Line 3380: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:392)
Line 3381: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:428)
Line 3382: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:76)
Line 3383: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:514)
Line 3384: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$700(ClientCallImpl.java:431)
Line 3385: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:546)
Line 3386: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
Line 3387: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.SerializingExecutor$TaskRunner.run(SerializingExecutor.java:152)
Line 3388: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
Line 3389: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
Line 3390: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.lang.Thread.run(Thread.java:764)

After this no response from response observer.

Kindly help me to solve this issue.

Body:
They fixed this issue at back-end.

@JHorseman : Thanks for the support.


问:
Facebook ShareDialog Limitations
Am facing one problem -> Sharing photos on facebook using Facebook Share Dialog (Facebook SDK) and that thing don't require publish action permission.

And everything works perfect until i share more then 6 photos. Its not working for more photos. So i want to know that is there any limitations from facebook side or from SDK that i can share 6 photos programatically (Bulk)

Here is the code Sample that am following :

```<code>for (int index = 0; index < mArryLstPhotos.size(); index++) {

                String pathofBmp = saveImageToExternalStorage(mArryLstPhotos.get(index), mImagesPath.get(index));
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeFile(pathofBmp.contains("file:///") ?
                        pathofBmp.replace("file://", "")
                        : pathofBmp);

                if (bitmap != null && photos.size() < 6)
                    photos.add(new SharePhoto.Builder()
                            .setBitmap(bitmap)
                            .build());
            }
</code>```

And then showing it using  :

```<code>if (shareDialog.canShow(content)) {
 shareDialog.show(content, ShareDialog.Mode.AUTOMATIC);}
</code>```

答:
https://developers.facebook.com/docs/sharing/android

-> People can share a combination of photos and videos from your app to Facebook with the Share Dialog. Note the following:

People need the native Facebook for Android app installed, version 71 or higher.
Photos must be less than 12MB in size.
Videos must be less than 12MB in size.
People can share a maximum of 6 photos and videos at a time.

Title: Facebook ShareDialog Limitations

Body:
Am facing one problem -> Sharing photos on facebook using Facebook Share Dialog (Facebook SDK) and that thing don't require publish action permission.

And everything works perfect until i share more then 6 photos. Its not working for more photos. So i want to know that is there any limitations from facebook side or from SDK that i can share 6 photos programatically (Bulk)

Here is the code Sample that am following :

for (int index = 0; index < mArryLstPhotos.size(); index++) {

                String pathofBmp = saveImageToExternalStorage(mArryLstPhotos.get(index), mImagesPath.get(index));
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeFile(pathofBmp.contains("file:///") ?
                        pathofBmp.replace("file://", "")
                        : pathofBmp);

                if (bitmap != null && photos.size() < 6)
                    photos.add(new SharePhoto.Builder()
                            .setBitmap(bitmap)
                            .build());
            }

And then showing it using  :

if (shareDialog.canShow(content)) {
 shareDialog.show(content, ShareDialog.Mode.AUTOMATIC);}


问:
Why i'm getting error?com.android.volley.timeouterror
Hello guys can someone help me with this class? I am getting an error and I am only new to the android studio and mobile development. I'm in the process of learning and acquiring knowledge. Please help me. </p>

```<code>RequestQueue requestQueue = Volley.newRequestQueue(this);

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Toast.makeText(Register.this, response, Toast.LENGTH_LONG).show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(Register.this, error.toString(), Toast.LENGTH_LONG).show();

    }
}) {

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {

        Map<String, String> params = new HashMap<String, String>();
        params.put(NAME, pangaran);
        params.put(SURNAME, apelyido);
        params.put(ADDRESS, lugar);
        params.put(CONTACTNO, kontak);
        params.put(USERNAME, username1);
        params.put(PASSWORD, password1);
        return params;

    }
};

requestQueue.add(stringRequest);
</code>```

答:
see this link, hope it will help you to set the time for the volley.

and if it doesn't help just let me know.

UPDATED

At the end i have inserted the code to change the default time set by volley, you can set time by your self and it should be in milliseconds.

```<code>RequestQueue requestQueue = Volley.newRequestQueue(this);

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
    Toast.makeText(Register.this, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
    Toast.makeText(Register.this, error.toString(), Toast.LENGTH_LONG).show();

}
}) {

@Override
protected Map<String, String> getParams() throws AuthFailureError {

    Map<String, String> params = new HashMap<String, String>();
    params.put(NAME, pangaran);
    params.put(SURNAME, apelyido);
    params.put(ADDRESS, lugar);
    params.put(CONTACTNO, kontak);
    params.put(USERNAME, username1);
    params.put(PASSWORD, password1);
    return params;

}
};

//10000 is the time in milliseconds adn is equal to 10 sec
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            10000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

requestQueue.add(stringRequest);
</code>```

Body:
Hello guys can someone help me with this class? I am getting an error and I am only new to the android studio and mobile development. I'm in the process of learning and acquiring knowledge. Please help me.

RequestQueue requestQueue = Volley.newRequestQueue(this);

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Toast.makeText(Register.this, response, Toast.LENGTH_LONG).show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(Register.this, error.toString(), Toast.LENGTH_LONG).show();

    }
}) {

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {

        Map<String, String> params = new HashMap<String, String>();
        params.put(NAME, pangaran);
        params.put(SURNAME, apelyido);
        params.put(ADDRESS, lugar);
        params.put(CONTACTNO, kontak);
        params.put(USERNAME, username1);
        params.put(PASSWORD, password1);
        return params;

    }
};

requestQueue.add(stringRequest);

Body:
see this link, hope it will help you to set the time for the volley.

and if it doesn't help just let me know.

UPDATED

At the end i have inserted the code to change the default time set by volley, you can set time by your self and it should be in milliseconds.

RequestQueue requestQueue = Volley.newRequestQueue(this);

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
    Toast.makeText(Register.this, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
    Toast.makeText(Register.this, error.toString(), Toast.LENGTH_LONG).show();

}
}) {

@Override
protected Map<String, String> getParams() throws AuthFailureError {

    Map<String, String> params = new HashMap<String, String>();
    params.put(NAME, pangaran);
    params.put(SURNAME, apelyido);
    params.put(ADDRESS, lugar);
    params.put(CONTACTNO, kontak);
    params.put(USERNAME, username1);
    params.put(PASSWORD, password1);
    return params;

}
};

//10000 is the time in milliseconds adn is equal to 10 sec
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            10000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

requestQueue.add(stringRequest);


问:
How to remove fragment on Button Click?
I have an expandable ListView in my MainActivity. When certain item on the child ListView is selected some buttons (install, detail, cancel) are shown in fragment.

```<code>lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

                FragmentManager fragmentManager = getSupportFragmentManager();
                final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                if(!status){
                    final Options op = new Options();
                    fragmentTransaction.replace(R.id.main,op);
                    fragmentTransaction.commit();

                }
</code>```

Here Options is my fragment's name. Pressing the cancel button in the Options class i want to remove this fragment and display only the MainActivity.

```<code>Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
      btnCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           //REMOVE THIS FRAGMENT

        }
    });
</code>```

Can anybody please tried help me?

答:
To Remove all Fragments

```<code>public void clearAllFragments() {

    try {
        FragmentManager aFragmentManager = Context
            .getSupportFragmentManager();

        aFragmentManager.popBackStack(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    } catch (Exception e) {

        e.printStackTrace();
    }
}
</code>```

To Remove a single Fragment

```<code>public void removeFragment(int aCount) {

    FragmentManager aFragmentManager = Context
            .getSupportFragmentManager();

    for (int i = 0; i < aCount; i++) {

        aFragmentManager.popBackStack();
    }
}
</code>```

Title: How to remove fragment on Button Click?

Body:
I have an expandable ListView in my MainActivity. When certain item on the child ListView is selected some buttons (install, detail, cancel) are shown in fragment.

lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

                FragmentManager fragmentManager = getSupportFragmentManager();
                final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                if(!status){
                    final Options op = new Options();
                    fragmentTransaction.replace(R.id.main,op);
                    fragmentTransaction.commit();

                }

Here Options is my fragment's name. Pressing the cancel button in the Options class i want to remove this fragment and display only the MainActivity.

Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
      btnCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           //REMOVE THIS FRAGMENT

        }
    });

Can anybody please tried help me?

Body:
To Remove all Fragments

public void clearAllFragments() {

    try {
        FragmentManager aFragmentManager = Context
            .getSupportFragmentManager();

        aFragmentManager.popBackStack(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    } catch (Exception e) {

        e.printStackTrace();
    }
}

To Remove a single Fragment

public void removeFragment(int aCount) {

    FragmentManager aFragmentManager = Context
            .getSupportFragmentManager();

    for (int i = 0; i < aCount; i++) {

        aFragmentManager.popBackStack();
    }
}


问:
Ionic 3 - ios - displaying selected image on screen
I set up the camera plugin to select an image from the photo library and upload it to the server with the following code:

```<code>getImage() {
  //By default the camera retrieves the image as a JPEG file.
  const options: CameraOptions = {
    quality: 100,
    destinationType: this.camera.DestinationType.FILE_URI,
    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    targetWidth:1080,
    targetHeight:1080,
    correctOrientation: true,
    mediaType: this.camera.MediaType.PICTURE,
    encodingType: this.camera.EncodingType.JPEG

  }

  this.camera.getPicture(options).then((fileUri) => {

    if (this.platform.is('ios')) {
        return this.crop.crop(fileUri, {quality: 100});
      } else if (this.platform.is('android')) {
        // Modify fileUri format, may not always be necessary
        fileUri = 'file://' + fileUri;

        /* Using cordova-plugin-crop starts here */
        return this.crop.crop(fileUri, { quality: 100 });
      }
  }, (err) => {
    console.log(err);

  }).then((path) => {
    // path looks like 'file:///storage/emulated/0/Android/data/com.foo.bar/cache/1477008080626-cropped.jpg?1477008106566'
    console.log('Cropped Image Path!: ' + path);
    this.imagePath = path;
    return path;
  });
}
</code>```

I then display my image preview on the screen like so:

```<code><img [src]="imagePath"  />
</code>```

The selecting image, cropping and uploading work perfectly fine on both iOS and Android. However, on iOS the displaying of the image does not work. (Nothing shows up)

My console log shows the following:

2017-12-07 15:06:52.559614-0500 fd-app[2537:1186586] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
  2017-12-07 15:06:52.560425-0500 fd-app[2537:1186586] [MC] Reading from public effective user settings.
  2017-12-07 15:06:55.754175-0500 fd-app[2537:1186662] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
  2017-12-07 15:07:04.589982-0500 fd-app[2537:1186586] Cropped Image Path!: file:///var/mobile/Containers/Data/Application/8B2CD0E8-F6AC-4530-BF02-D2F7A188EAC2/tmp/cdv_photo_004.jpg

I tried adding Photo Library Usage property to the Info.plist file but that didn't help. Any suggestions what to try next?

UPDATE: Not sure if this has anything to do with it but I am using Xcode 9.2 beta because my iPhone is on 11.2

Also, everything I'm googling is pointing to the fact that this is a permissions problem, however, after selecting the image, the image appears in the cropper... this makes me suspect something odd is going on here? How can the cropper show the image but not the HTML page?

答:
If you are using WKWebview which is the default webview in IOS 11 as per the official blog post, you need to rewrite the file:// url before using in your HTML.

If you’re working with local files (text files, images, videos), you’ll need to make sure that the path of file does not have file:// in front of it.

```<code>import { normalizeURL } from 'ionic-angular';
</code>```

And in your function,

```<code> this.imagePath = normalizeURL(path);
    return path;
</code>```

Further check troubleshooting section which says the same.

Body:
I set up the camera plugin to select an image from the photo library and upload it to the server with the following code:

getImage() {
  //By default the camera retrieves the image as a JPEG file.
  const options: CameraOptions = {
    quality: 100,
    destinationType: this.camera.DestinationType.FILE_URI,
    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    targetWidth:1080,
    targetHeight:1080,
    correctOrientation: true,
    mediaType: this.camera.MediaType.PICTURE,
    encodingType: this.camera.EncodingType.JPEG

  }

  this.camera.getPicture(options).then((fileUri) => {

    if (this.platform.is('ios')) {
        return this.crop.crop(fileUri, {quality: 100});
      } else if (this.platform.is('android')) {
        // Modify fileUri format, may not always be necessary
        fileUri = 'file://' + fileUri;

        /* Using cordova-plugin-crop starts here */
        return this.crop.crop(fileUri, { quality: 100 });
      }
  }, (err) => {
    console.log(err);

  }).then((path) => {
    // path looks like 'file:///storage/emulated/0/Android/data/com.foo.bar/cache/1477008080626-cropped.jpg?1477008106566'
    console.log('Cropped Image Path!: ' + path);
    this.imagePath = path;
    return path;
  });
}

I then display my image preview on the screen like so:

The selecting image, cropping and uploading work perfectly fine on both iOS and Android. However, on iOS the displaying of the image does not work. (Nothing shows up)

My console log shows the following:

2017-12-07 15:06:52.559614-0500 fd-app[2537:1186586] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
  2017-12-07 15:06:52.560425-0500 fd-app[2537:1186586] [MC] Reading from public effective user settings.
  2017-12-07 15:06:55.754175-0500 fd-app[2537:1186662] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
  2017-12-07 15:07:04.589982-0500 fd-app[2537:1186586] Cropped Image Path!: file:///var/mobile/Containers/Data/Application/8B2CD0E8-F6AC-4530-BF02-D2F7A188EAC2/tmp/cdv_photo_004.jpg

I tried adding Photo Library Usage property to the Info.plist file but that didn't help. Any suggestions what to try next?

UPDATE: Not sure if this has anything to do with it but I am using Xcode 9.2 beta because my iPhone is on 11.2

Also, everything I'm googling is pointing to the fact that this is a permissions problem, however, after selecting the image, the image appears in the cropper... this makes me suspect something odd is going on here? How can the cropper show the image but not the HTML page?

Body:
If you are using WKWebview which is the default webview in IOS 11 as per the official blog post, you need to rewrite the file:// url before using in your HTML.

If you’re working with local files (text files, images, videos), you’ll need to make sure that the path of file does not have file:// in front of it.

import { normalizeURL } from 'ionic-angular';

And in your function,

 this.imagePath = normalizeURL(path);
    return path;

Further check troubleshooting section which says the same.


问:
Bluetooth LE device cannot disconnect in Win 10 IoT UWP application
I am trying to control the Bluetooth LE devices connect/disconnect in my Win 10 IoT UWP C# application, running on Raspberry Pi 3 SBC. The Win 10 IoT is Windows Insiders Preview build 10.0.17035.1000. When I start my application, it recognizes the advertising BLE device, successfully connects and communicates with it . Then I try to disconnect this device by applying the recommended procedure:

device.Dispose();

device = null;

GC.Collect();

and even stop and start again the BluetoothLEAdvertisementWatcher. But when this device starts advertising again, it is not recognized. Of my understanding the reason is that the device was not actually disconnected (despite that it shows disconnected status) or some connection information is still pending, which prevents it to be recognized on a new advertisement.

Even if I don't apply the above procedure, a new device advertisement (from the same or other BLE device) is not recognized and in both cases the only resort is to restart the Win 10 IoT and restart the application in order a new advertisement from the same device to be recognized. After the communication with the device completes, an advertisement from different device of the same type can be recognized. But when the second device completes to communicate, no new advertisement from it or the first device can be recognized again. No exceptions or other problems were reported in debug mode. This is really inacceptable in an application production version.

Please advise me how to solve this problem. Thanks.

答:
This issue may be caused by the active session of GattDeviceService not been closed.

When you connected a BLE device and access its services and characteristics, there is an active session for your operations. You dispose of the device but the session is still open.

To solve this problem you need do a little more work when disconnecting the device like this:

If you opened a service(GattDeviceService) you need call service?.Dispose().

If you opened a characteristic(GattCharacteristic) you need to call characteristic?.Service?.Dispose().

For checking the session status you can call service?.Session.SessionStatus or
characteristic?.Service?.Session.SessionStatus

Update:
There maybe serval characteristics belong to one service. So you may run into exception when do the dispose from the characteristic level because you may duplicate to close a closed service.
To solve this problem you can do the dispose work at the service level. The following code piece based on BluetoothLE sample. You can edit ClearBluetoothLEDeviceAsync() like this:

```<code>        private async Task<bool> ClearBluetoothLEDeviceAsync()
        {
            ...

            foreach (var ser in ServiceCollection)
            {
                ser.service?.Dispose();
            }

            bluetoothLeDevice?.Dispose();
            bluetoothLeDevice = null;
            return true;
        }
</code>```

Body:
This issue may be caused by the active session of GattDeviceService not been closed.

When you connected a BLE device and access its services and characteristics, there is an active session for your operations. You dispose of the device but the session is still open.

To solve this problem you need do a little more work when disconnecting the device like this:

If you opened a service(GattDeviceService) you need call service?.Dispose().

If you opened a characteristic(GattCharacteristic) you need to call characteristic?.Service?.Dispose().

For checking the session status you can call service?.Session.SessionStatus or
characteristic?.Service?.Session.SessionStatus

Update:
There maybe serval characteristics belong to one service. So you may run into exception when do the dispose from the characteristic level because you may duplicate to close a closed service.
To solve this problem you can do the dispose work at the service level. The following code piece based on BluetoothLE sample. You can edit ClearBluetoothLEDeviceAsync() like this:

        private async Task<bool> ClearBluetoothLEDeviceAsync()
        {
            ...

            foreach (var ser in ServiceCollection)
            {
                ser.service?.Dispose();
            }

            bluetoothLeDevice?.Dispose();
            bluetoothLeDevice = null;
            return true;
        }


问:
How to compress multiple files in to zip file in angular 2
I have multiple files and I want to compress them as a zip file with  Angular 2 framework. I installed JSZIP library as well, but unfortunately it's not working.

Here is my code:

```<code>    var zip = new JSZip();
    var count = 0;
    var zipFilename = "zipFilename.zip";
    var urls = [
    'http://image-url-1',
    'http://image-url-2',
    'http://image-url-3'
     ];

    urls.forEach(function(url){
    var filename = "filename";
   // loading a file and add it in a zip file
   JSZipUtils.getBinaryContent(url, function (err, data) {
     if(err) {
        throw err; // or handle the error
     }
     zip.file(filename, data, {binary:true});
     count++;
     if (count == urls.length) {
       var zipFile = zip.generate({type: "blob"});
       saveAs(zipFile, zipFilename);
     }
  });
});
</code>```

答:
Probably your using the latest version (V3) of JSZip: If so you can make a slight change to the If statement like this and try

```<code>   if (count == urls.length) {
       zip.generateAsync({type:'blob'}).then(function(content) {
          saveAs(content, zipFilename);
       });
    }
</code>```

Source : https://gist.github.com/noelvo/4502eea719f83270c8e9

Body:
I have multiple files and I want to compress them as a zip file with  Angular 2 framework. I installed JSZIP library as well, but unfortunately it's not working.

Here is my code:

    var zip = new JSZip();
    var count = 0;
    var zipFilename = "zipFilename.zip";
    var urls = [
    'http://image-url-1',
    'http://image-url-2',
    'http://image-url-3'
     ];

    urls.forEach(function(url){
    var filename = "filename";
   // loading a file and add it in a zip file
   JSZipUtils.getBinaryContent(url, function (err, data) {
     if(err) {
        throw err; // or handle the error
     }
     zip.file(filename, data, {binary:true});
     count++;
     if (count == urls.length) {
       var zipFile = zip.generate({type: "blob"});
       saveAs(zipFile, zipFilename);
     }
  });
});

Body:
Probably your using the latest version (V3) of JSZip: If so you can make a slight change to the If statement like this and try

   if (count == urls.length) {
       zip.generateAsync({type:'blob'}).then(function(content) {
          saveAs(content, zipFilename);
       });
    }

Source : https://gist.github.com/noelvo/4502eea719f83270c8e9


问:
User authentication with CodeIgniter
I am writing a web application using PHP. I want to use the MVC pattern for this, and decided to go with CodeIgniter. My application will have some pages which will require authentication, and some pages won't. I want to design this in a very generic way, so that there should be no code duplication. Can any one point to some good "design/class structure" for this?</p>

答: I was looking into the same thing recently, and I found a CodeIgniter fork called Kohana that includes a nice authentication module. If you are set on CI, maybe adapting Kohana's auth module backwards to CI would save you some time? If you have just started out on your project and PHP5 is OK to use, consider switching over; they are very similar frameworks.</p>

OwnerDisplayName: Sabya

Title: User authentication with CodeIgniter

LastEditorDisplayName: Sabya

OwnerDisplayName: Barnabas Kendall


问:
htaccess replacing PHP file.php?id=dynamic_id with file/id
I am wanting to use htaccess to make a url such as http://example.com/news/news_post.php?id=dynamic_id with a URL that looks like http://example.com/news/news_post/dynamic_id. So basically remove the .php file extension, as well as make ?id=dynamic_id to /dynamic_id for my news_post.php page.

I have searched around at other examples to find something that may help, but I haven't been able to find anything that helps.

If someone can help me with this, it would be much appreciated!

答:
You Can add this code to your .htaccess file:

.htaccess

```<code>RewriteEngine on
RewriteCond %{QUERY_STRING} (^|&)id=dynamic_id($|&)
RewriteRule ^news/news_post\.php$ /news/news_post/dynamic_id?&%{QUERY_STRING}
</code>```

Body:
You Can add this code to your .htaccess file:

.htaccess

RewriteEngine on
RewriteCond %{QUERY_STRING} (^|&)id=dynamic_id($|&)
RewriteRule ^news/news_post\.php$ /news/news_post/dynamic_id?&%{QUERY_STRING}


问:
conditional attribute using knockout.js
I want to conditionally add a ID attribute to the div tag

I tried something like this

```<code> <div class="row" data-bind="attr: { id:'selectedReplyMessage': $component.selectedReplyMessageID() == _id }"></div>
</code>```

But it didnt work

Although this code

```<code><div class="row" data-bind=" css:{selectedReplyMessage: $component.selectedReplyMessageID() == _id }">
</code>```

is working completely fine.But i want to associate ID with the component.

答:
As mentioned by Adigo

```<code> <div class="row" data-bind="attr: { id: $component.selectedReplyMessageID() == _id ? 'selectedReplyMessage' : null }"></div>
</code>```

Doing like this way you can acheive you desired output.Using ternary operator and putting the values.

Title: conditional attribute using knockout.js

Body:
I want to conditionally add a ID attribute to the div tag

I tried something like this

But it didnt work

Although this code

is working completely fine.But i want to associate ID with the component.

Body:
As mentioned by Adigo

 <div class="row" data-bind="attr: { id: $component.selectedReplyMessageID() == _id ? 'selectedReplyMessage' : null }"></div>

Doing like this way you can acheive you desired output.Using ternary operator and putting the values.


问:
computing function of neighbors efficiently on lattice
I'm studying the Ising model, and I'm trying to efficiently compute a function H(σ) where σ is the current state of an LxL lattice (that is, σ_ij ∈ {+1, -1} for i,j ∈ {1,2,...,L}). To compute H for a particular σ, I need to perform the following calculation:

where ⟨i j⟩ indicates that sites σ_i and σ_j are nearest neighbors and (suppose) J is a constant.

A couple of questions:

Should I store my state σ as an LxL matrix or as an L2 list? Is one better than the other for memory accessing in RAM (which I guess depends on the way I'm accessing elements...)?

In either case, how can I best compute H?

Really I think this boils down to how can I access (and manipulate) the neighbors of every state most efficiently.

Some thoughts:

I see that if I loop through each element in the list or matrix that I'll be double counting, so is there a "best" way to return the unique neighbors?

Is there a better data structure that I'm not thinking of?

答:
I encountered this problem during one of my school assignments and I think the solution depends on which programming language you are using.

In terms of efficiency, there is no better way than to write a for loop to sum neighbours(which are actually the set of 4 points{ (i+/-1,j+/-1)} for a given (i,j). However, when simd(sse etc) functions are available, you can re-express this as a convolution with a 2d  kernel {0 1 0;1 0 1;0 1 0}. so if you use a numerical library which exploits simd functions you can obtain significant performance increase. You can see the example implementation of this here(https://github.com/zawlin/cs5340/blob/master/a1_code/denoiseIsingGibbs.py) .
Note that in this case, the performance improvement is huge because to evaluate it in python I need to write an expensive for loop.

In terms of work, there is in fact some waste as the unecessary multiplications and sum with zeros at corners and centers. So whether you can experience performance improvement depends quite a bit on your programming environment( if you are already in c/c++, it can be difficult and you need to use mkl etc to obtain good improvement)


问:
Should I show two validation messages for email id in web application?
I have an email address field on my web application.I have 2 cases for this

a) email should not be empty

b) email should be in proper format .

Whether user keep it empty or put improper email address in the email address
I show only one message "Please enter valid emailid".

My manager says that we should use two validation messages. but I am insisting that this one message is suffiecient.

Please suggest what should be approach for this.

UPDATED : -

Here is what I found for Yahoo.com login screen

答: I think it is always good to inform the user of what is happening.If the email is required as per your requirement then you should prompt the user to alert them they cannot leave the email field empty, and also by standards you should accept correct email formats (myemail@something.com). These are both different requirements and should be treated differently for a better user experience. I use Parsley.js for my front end form validations to validate empty text fields and incorrect input formats.</p>


问:
express.js server running on nodemon working differently than one on node
my server.js looks like this:

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

var ingredients = [
    {
        id:"i1",
        text:'eggs'
    },
    {
        id:'i2',
        text:'milk'
    },
    {
        id:'i3',
        text:'bacon'
    },
    {
        id:'i4',
        text:'frog legs'
    }
];
app.get('/',function (request,response){
    response.send(ingredients);
});
app.post('/',function(request,response){
    var ingredient = request.body;
    if( !ingredient || ingredient.text===""){
        response.status(500).send({error: "Your ingredient must have some text"});
    }else {
        ingredients.push(ingredient);
        response.status(200).send(ingredients);
    }
});
app.listen(3000, function () {
    /* body... */
    console.log('My first API running successfully on port 3000');
});
</code>```

so when I run the server using node server.js and send a POST request with the body text as

```<code>{"id":"i5","text":"cherries"}
</code>```

It pushes the object to the ingredients array. But when I run the same file using nodemon server.js , it pushes an empty object. Also, it doesn't return an error message if "text" property is left empty(also in the nodemon scenario). Can anyone from the community help me understand why did this happen ?

P.S. - I tested the requests using POSTMAN.

答:
The reason you are pushing blank object in array is you are not passing application/json on header .

And also your condition of checking text is not right.

```<code> var ingredient = request.body;
    if( !ingredient || ingredient.text===""){
</code>```

//when you assign request.body to ingredient if no data come it assign {} to it and when you check for if condition !ingredient  is not blank it has {} and in next condition ingredient.text return undefined which is not equal to ""

```<code>app.post('/',function(request,response){
    console.log("post");
    var ingredient = request.body;
    if (!('text' in ingredient)){
   // if(ingredient.text){
        response.status(500).send({error: "Your ingredient must have some text"});
    }else {
         console.log("post1",ingredient);
        ingredients.push(ingredient);
        response.status(200).send(ingredients);
    }
});
</code>```

Body:
my server.js looks like this:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

var ingredients = [
    {
        id:"i1",
        text:'eggs'
    },
    {
        id:'i2',
        text:'milk'
    },
    {
        id:'i3',
        text:'bacon'
    },
    {
        id:'i4',
        text:'frog legs'
    }
];
app.get('/',function (request,response){
    response.send(ingredients);
});
app.post('/',function(request,response){
    var ingredient = request.body;
    if( !ingredient || ingredient.text===""){
        response.status(500).send({error: "Your ingredient must have some text"});
    }else {
        ingredients.push(ingredient);
        response.status(200).send(ingredients);
    }
});
app.listen(3000, function () {
    /* body... */
    console.log('My first API running successfully on port 3000');
});

so when I run the server using node server.js and send a POST request with the body text as

{"id":"i5","text":"cherries"}

It pushes the object to the ingredients array. But when I run the same file using nodemon server.js , it pushes an empty object. Also, it doesn't return an error message if "text" property is left empty(also in the nodemon scenario). Can anyone from the community help me understand why did this happen ?

P.S. - I tested the requests using POSTMAN.

Body:
The reason you are pushing blank object in array is you are not passing application/json on header .

And also your condition of checking text is not right.

 var ingredient = request.body;
    if( !ingredient || ingredient.text===""){

//when you assign request.body to ingredient if no data come it assign {} to it and when you check for if condition !ingredient  is not blank it has {} and in next condition ingredient.text return undefined which is not equal to ""

app.post('/',function(request,response){
    console.log("post");
    var ingredient = request.body;
    if (!('text' in ingredient)){
   // if(ingredient.text){
        response.status(500).send({error: "Your ingredient must have some text"});
    }else {
         console.log("post1",ingredient);
        ingredients.push(ingredient);
        response.status(200).send(ingredients);
    }
});