问:
preg_replace not doing what I expect
I have the following paterns in a paragraph of text and I need to replace it with nothing, so that it disappears from the paragraph.

The sendtence contains CONSULTANTS [45416,2010-05-11] I need to remove the [] and everything within these [] , not the characters within the [] could be anything

I tried the below but this only removes the []

```<code>$par = preg_replace('/[\[*\]]/','',$par);
</code>```

答:
You can do:

```<code>$par = preg_replace('/\[.*?\]/s','',$par);
</code>```

Explanation:

```<code>/    - Start delimiter
\[   - A literal [
.*?  - A non-greedy anything
\]   - A literal ]
/    - End delimiter
s    - Modifier to make . match even a newline
</code>```

to make the replacement a bit faster you can do:

```<code>$par = preg_replace('/\[[^\]]*\]/s','',$par);
</code>```

Explanation:

```<code>/    - Start delimiter
\[   - A literal [
 [   - Start of character class
 ^   - Char class negator
 ]   - End of character class
\]   - A literal ]
/    - End delimiter
</code>```

Title: preg_replace not doing what I expect

Body:
I have the following paterns in a paragraph of text and I need to replace it with nothing, so that it disappears from the paragraph.

The sendtence contains CONSULTANTS [45416,2010-05-11] I need to remove the [] and everything within these [] , not the characters within the [] could be anything

I tried the below but this only removes the []

$par = preg_replace('/[\[*\]]/','',$par);

Body:
You can do:

$par = preg_replace('/\[.*?\]/s','',$par);

Explanation:

/    - Start delimiter
\[   - A literal [
.*?  - A non-greedy anything
\]   - A literal ]
/    - End delimiter
s    - Modifier to make . match even a newline

to make the replacement a bit faster you can do:

$par = preg_replace('/\[[^\]]*\]/s','',$par);

Explanation:

/    - Start delimiter
\[   - A literal [
 [   - Start of character class
 ^   - Char class negator
 ]   - End of character class
\]   - A literal ]
/    - End delimiter


来源: stackexchange

问:
Puppet agent on fail function?
Do Puppet agents have any type of on failure ability?

I want to create a rule that says if a puppet agent tries to check in fails due to an SSL issue it should remove its SSL certificates and attempt the check-in process again.

I know all the commands I want to run, it's just a matter of finding a way to execute a script on SSL failure.

Any suggestions on how to do this?

答:
Do Puppet agents have any type of on failure ability?

Not a built-in one, no.  They do log failures, of course.  Or I guess the PE version might have something like that -- I wouldn't know.

I know all the commands I want to run, it's just a matter of finding a
  way to execute a script on SSL failure.

Any suggestions on how to do this?

When run in --onetime mode, the agent's exit code conveys its success or failure, but you'd still have to analyze the log / console output to ascertain the nature of any failure.  To use this for scheduled runs you would want to use an external scheduler such as cron to run the agent, rather than letting it run as a daemon itself.  Some folks recommend that as a general good practice.

ContentLicense: CC BY-SA 3.0

Title: Puppet agent on fail function?


问:
How to obtain values within R.Java?
I presume this will be a bit of a noob question so please bear with me but i am wondering how the values Shown In Blue are generated for the different source files within R.Java file as shown? Thanks!

答:
As it's been mentioned in previous answers, R file is being generated every single time during the application build. Every value must be public and static. This file should be never edited manually.

You can compare this file with some kind of a "manifest" for the app that defines what property name is responsible for what. And in order to navigate to the R.x.x value usage - simply click on the property while holding CTRL.

Now to the more "in-depth" answer. To my mind here is the most accurate explanation of the generation process, if that's what you were looking for: 'Deep' answer.

Good luck!

ContentLicense: CC BY-SA 4.0

Title: How to obtain values within R.Java?


问:
Converting KML to Array in PHP
I've got stuck when i'm trying to convert a *.kml file to array using PHP language.

kml file >> path.kml

code

```<code>    $dom = new \DOMDocument();
    $dom->loadXml($file);
    $xpath = new \DOMXPath($dom);
    $xpath->registerNamespace('kml', 'http://www.opengis.net/kml/2.2');

    $result = array();
    $places = $xpath->evaluate('//kml:Placemark', NULL, FALSE);
    foreach ($places as $place) {
        $coord = $xpath->evaluate('string(kml:LineString/kml:coordinates)',$place, FALSE);
        $i = explode("\n", $coord);
        $result = array(
            'name' => $xpath->evaluate('string(kml:name)', $place, FALSE),
            'coords' => explode("\n", $coord, count($i)
            )
        );
    }

    var_dump($result);
</code>```

the problem is when i'm trying to explode the string using newLine delimeter, and the result is always like this

whereas i want the result like this

could anyone to help me for solve my problem ? Thank You!

答:
There is different new line characters, not just \r\n - try using something like preg_split ('/\R/', $string); instead to catch all new line characters.

For a more detailed explanation of what \R does, check out this SO answer.

Title: Converting KML to Array in PHP

Body:
I've got stuck when i'm trying to convert a *.kml file to array using PHP language.

kml file >> path.kml

code

    $dom = new \DOMDocument();
    $dom->loadXml($file);
    $xpath = new \DOMXPath($dom);
    $xpath->registerNamespace('kml', 'http://www.opengis.net/kml/2.2');

    $result = array();
    $places = $xpath->evaluate('//kml:Placemark', NULL, FALSE);
    foreach ($places as $place) {
        $coord = $xpath->evaluate('string(kml:LineString/kml:coordinates)',$place, FALSE);
        $i = explode("\n", $coord);
        $result = array(
            'name' => $xpath->evaluate('string(kml:name)', $place, FALSE),
            'coords' => explode("\n", $coord, count($i)
            )
        );
    }

    var_dump($result);

the problem is when i'm trying to explode the string using newLine delimeter, and the result is always like this

whereas i want the result like this

could anyone to help me for solve my problem ? Thank You!


问:
Ion-list not refreshing afer model change
I am having a problem with the ion-list, I can list all the items when the app loads for the first time, but when I make any changes to it, adding or removing data, the list isn't updating for the user.

I am using Pouch db to add and remove data for persistence in the app, all the functions are working correctly, it can be confirmed through console.log in the contents or using the fauxton PouchDb extension for chrome.

Resuming, the data is changing, but the view is not reflecting it.

the view code is this notas.html

<ion-content>
  <ion-list>
    <ion-item-sliding *ngFor="let n of notas">
      <ion-item>

{{n.descricao}}

URL: {{n.endereco}}

Data de expiração: {{n.vencimento}}

      </ion-item>
      <ion-item-options side="right">
        <button ion-button (click)="editar(n)">
          <ion-icon name="paper"></ion-icon>
          Editar
        </button>
        <button ion-button color="danger" (click)="excluir(n)">
          <ion-icon name="trash"></ion-icon>
          Excluir
        </button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>
</ion-content>
```

<p>And the controler code is this notas.ts</p>

```...
@Component({
  selector: 'page-notas',
  templateUrl: 'notas.html'
})
export class NotasPage {
  notas: any;

  constructor(public navCtrl: NavController, public alertCtrl: AlertController, public pouchDBService: PouchdbProvider) {
    //PARA USO DO EXTENSION DO CHROME *POUCHDB Fauxton
    (<any>window).PouchDB = PouchDB;
    this.notas = [];
  }

  ionViewDidLoad(){
    this.refresh();
  }

  refresh(){
    //console.log(this.notas);
    this.notas = [];
    this.pouchDBService.getData().then((data) => {
      this.notas = data;
      console.log(this.notas);
    });
    // console.log(this.notas);
  }

  excluir(nota){
    let prompt = this.alertCtrl.create({
      title: 'Excluir',
      message: 'Deseja realmente excluir o registro?',
      buttons: [
        {
          text: 'Cancelar'
        },
        {
          text: 'Excluir',
          handler: data => {
            this.pouchDBService.delete(nota);
            this.notas.pop(nota);
            this.refresh();
          }
        }
      ]
    });

    prompt.present();
  }
}
...
```

答:
Not 100% sure on this but usually if the view is not updating, it has to do with the code not running on zone, so:

```<code>import { NgZone } from '@angular/core';
...
zone: any = new NgZone({ enableLongStackTrace: false });
</code>```

And then change your refresh method to:

```<code>refresh(){
    //console.log(this.notas);
    this.notas = [];
    this.pouchDBService.getData().then((data) => {
      this.zone.run(() => {
        this.notas = data;
        console.log(this.notas);
      });
    });
    // console.log(this.notas);
  }
</code>```

I believe that should work.

Body:
I am having a problem with the ion-list, I can list all the items when the app loads for the first time, but when I make any changes to it, adding or removing data, the list isn't updating for the user.

I am using Pouch db to add and remove data for persistence in the app, all the functions are working correctly, it can be confirmed through console.log in the contents or using the fauxton PouchDb extension for chrome.

Resuming, the data is changing, but the view is not reflecting it.

the view code is this notas.html

<ion-content>
  <ion-list>
    <ion-item-sliding *ngFor="let n of notas">
      <ion-item>

{{n.descricao}}

URL: {{n.endereco}}

Data de expiração: {{n.vencimento}}

      </ion-item>
      <ion-item-options side="right">
        <button ion-button (click)="editar(n)">
          <ion-icon name="paper"></ion-icon>
          Editar
        </button>
        <button ion-button color="danger" (click)="excluir(n)">
          <ion-icon name="trash"></ion-icon>
          Excluir
        </button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>
</ion-content>

And the controler code is this notas.ts

...
@Component({
  selector: 'page-notas',
  templateUrl: 'notas.html'
})
export class NotasPage {
  notas: any;

  constructor(public navCtrl: NavController, public alertCtrl: AlertController, public pouchDBService: PouchdbProvider) {
    //PARA USO DO EXTENSION DO CHROME *POUCHDB Fauxton
    (<any>window).PouchDB = PouchDB;
    this.notas = [];
  }

  ionViewDidLoad(){
    this.refresh();
  }

  refresh(){
    //console.log(this.notas);
    this.notas = [];
    this.pouchDBService.getData().then((data) => {
      this.notas = data;
      console.log(this.notas);
    });
    // console.log(this.notas);
  }

  excluir(nota){
    let prompt = this.alertCtrl.create({
      title: 'Excluir',
      message: 'Deseja realmente excluir o registro?',
      buttons: [
        {
          text: 'Cancelar'
        },
        {
          text: 'Excluir',
          handler: data => {
            this.pouchDBService.delete(nota);
            this.notas.pop(nota);
            this.refresh();
          }
        }
      ]
    });

    prompt.present();
  }
}
...

Body:
Not 100% sure on this but usually if the view is not updating, it has to do with the code not running on zone, so:

import { NgZone } from '@angular/core';
...
zone: any = new NgZone({ enableLongStackTrace: false });

And then change your refresh method to:

refresh(){
    //console.log(this.notas);
    this.notas = [];
    this.pouchDBService.getData().then((data) => {
      this.zone.run(() => {
        this.notas = data;
        console.log(this.notas);
      });
    });
    // console.log(this.notas);
  }

I believe that should work.


问:
ClassCastException in onLongClick of ViewHolder
I'm following this tutorial to implement multi select in my RecyclerView but I have been getting the following runtime exception when I perform a long click:

```<code>java.lang.ClassCastException: com.abdralabs.talksee.MyApplication cannot be cast to android.support.v7.app.AppCompatActivity
                                                                       at com.abdralabs.talksee.IMListAdapter$IMListViewHolder.onLongClick(IMListAdapter.java:116)
                                                                       at android.view.View.performLongClick(View.java:5308)
                                                                       at android.view.View$CheckForLongPress.run(View.java:21522)
                                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                       at android.os.Looper.loop(Looper.java:207)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5740)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
</code>```

Activity code:

```<code>public class IMListActivity extends AppCompatActivity implements Sertivity{

private RecyclerView recyclerView;
private IMListAdapter imListAdapter;
private List<Chat> chatList = new ArrayList<>();
List<String> stringList;
ActiveChatsDB activeChatsDB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imlist);
    Toolbar toolbar = (Toolbar)findViewById(R.id.imlist_toolbar);
    setSupportActionBar(toolbar);
    setBackButtonOnToolbar();

    recyclerView = (RecyclerView)findViewById(R.id.rv_im_list);
    imListAdapter = new IMListAdapter(chatList, getApplicationContext());
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    recyclerView.setAdapter(imListAdapter);
    prepareChatListData();
}

private void prepareChatListData() {
    String friend;
    String latestMessage;
    activeChatsDB = new ActiveChatsDB(IMListActivity.this);
    stringList = activeChatsDB.getChatList();
    activeChatsDB.close();
    for (int i=0; i<stringList.size(); i++) {
        friend = stringList.get(i);
        DBAct dbAct = new  DBAct(IMListActivity.this,friend);
        latestMessage = dbAct.getLatestMessage();
        dbAct.close();
        Chat chat = new Chat(friend, latestMessage);
        chatList.add(chat);
    }
    imListAdapter.notifyDataSetChanged();
}

private void setBackButtonOnToolbar(){
    if(getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}

public RecyclerView getRecyclerView() {
    return recyclerView;
}
</code>```

}

Adapter code:

```<code>public class IMListAdapter extends RecyclerView.Adapter <com.abdralabs.talksee.IMListAdapter.IMListViewHolder> {

private List<Chat> chatList = new ArrayList<Chat>() ;
private Context ctx;
private MultiSelector multiSelector = new MultiSelector();
private ModalMultiSelectorCallback modalMultiSelectorCallback =
        new ModalMultiSelectorCallback(multiSelector) {
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                if (item.getItemId() == R.id.item_delete) {
                    mode.finish();

                    for (int i = chatList.size(); i >= 0; i--) {
                        if (multiSelector.isSelected(i, 0)) { // (1)
                            // remove item from list
                            ((IMListActivity)ctx).getRecyclerView().getAdapter().notifyItemRemoved(i);
                        }
                    }

                    multiSelector.clearSelections(); // (2)
                    return true;

                }
                return false;
            }

            @Override
            public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                super.onCreateActionMode(actionMode, menu);
                ((AppCompatActivity)ctx).getMenuInflater().inflate(R.menu.contextual_menu_friends, menu);
                return true;
            }
        };

public IMListAdapter(List<Chat> chatList, Context ctx){
    this.chatList = chatList;
    this.ctx = ctx;
}

@Override
public com.abdralabs.talksee.IMListAdapter.IMListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_list_row,parent,false);
    return new com.abdralabs.talksee.IMListAdapter.IMListViewHolder(itemView, chatList, ctx);    }

@Override
public void onBindViewHolder(com.abdralabs.talksee.IMListAdapter.IMListViewHolder holder, int position) {
    Chat chat = chatList.get(position);
    holder.name.setText(chat.getName());
    holder.recentMsg.setText(chat.getRecentMessage());
}

@Override
public int getItemCount() {
    return chatList.size();
}

public class IMListViewHolder extends SwappingHolder implements View.OnClickListener, View.OnLongClickListener{
    public TextView name;
    public TextView recentMsg;
    List<Chat> chatList = new ArrayList<Chat>();
    Context ctx;

    public IMListViewHolder(View itemView, List<Chat> chatList, Context ctx) {
        super(itemView, multiSelector);
        this.chatList = chatList;
        this.ctx = ctx;
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
        itemView.setLongClickable(true);
        name = (TextView) itemView.findViewById(R.id.name_chat);
        recentMsg = (TextView)itemView.findViewById(R.id.tv_recent_msg_im_list);
    }

    @Override
    public void onClick(View v) {
        int position = getAdapterPosition();
        Chat chat = this.chatList.get(position);
        Intent intent = new Intent(this.ctx, IMActivity.class);
        intent.putExtra("otherUserName",chat.getName());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.ctx.startActivity(intent);

    }

    @Override
    public boolean onLongClick(View v) {
        if (!multiSelector.isSelectable()) { // (3)
            ((AppCompatActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
            multiSelector.setSelectable(true); // (4)
            multiSelector.setSelected(com.abdralabs.talksee.IMListAdapter.IMListViewHolder.this, true); // (5)
            return true;
        }
        return false;
    }
}
</code>```

}

I don't know how I'm supposed to peform the right type casting. Please help.

EDIT 1:

I tried replacing the onLongClick code to

```<code>public boolean onLongClick(View v) {
        if (!multiSelector.isSelectable()) { // (3)
            ((IMListActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
            multiSelector.setSelectable(true); // (4)
            multiSelector.setSelected(IMListViewHolder.this, true); // (5)
            return true;
        }
        return false;
    }
</code>```

as Sachin Bahukhandi suggested, but I'm getting the same error

```<code>java.lang.ClassCastException: com.abdralabs.talksee.MyApplication cannot be cast to com.abdralabs.talksee.IMListActivity
                                                                     at com.abdralabs.talksee.IMListAdapter$IMListViewHolder.onLongClick(IMListAdapter.java:116)
                                                                     at android.view.View.performLongClick(View.java:5308)
                                                                     at android.view.View$CheckForLongPress.run(View.java:21522)
                                                                     at android.os.Handler.handleCallback(Handler.java:815)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                     at android.os.Looper.loop(Looper.java:207)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5740)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
</code>```

In the tutorial that I'm following the code is as such:

```<code>@Override
public boolean onLongClick(View view) {
    if (!mMultiSelector.isSelectable()) {
        ((AppCompatActivity) getActivity()).startSupportActionMode(mActionModeCallback); // (2)
        mMultiSelector.setSelectable(true);
        mMultiSelector.setSelected(MyViewHolder.this, true);
        return true;
    }
    return false;
}
</code>```

In the above code getActivity is called somehow from the Viewholder and type casted to AppCompatActivity. I don't know how to call getActivity directly from the ViewHolder since I'm getting and error so I tried to type cast a context object (which was passed from my Activity through the adapter constructor) to AppCompatActivity. So I don't exactly know what I'm doing wrong here.

答:
In the code you posted the application crashed because it cannot cast Context to AppCompatActivity.

```<code> @Override
public boolean onLongClick(View v) {
    if (!multiSelector.isSelectable()) { // (3)
        ((AppCompatActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
        multiSelector.setSelectable(true); // (4)
        multiSelector.setSelected(com.abdralabs.talksee.IMListAdapter.IMListViewHolder.this, true); // (5)
        return true;
    }
    return false;
}
</code>```

So I suggest to replace

```<code>((AppCompatActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
        multiSelector.setSelectable(true); // (4)
</code>```

To YourActivity:

```<code>((IMListActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
        multiSelector.setSelectable(true); // (4)
</code>```

Hope this helps.

Body:
I'm following this tutorial to implement multi select in my RecyclerView but I have been getting the following runtime exception when I perform a long click:

java.lang.ClassCastException: com.abdralabs.talksee.MyApplication cannot be cast to android.support.v7.app.AppCompatActivity
                                                                       at com.abdralabs.talksee.IMListAdapter$IMListViewHolder.onLongClick(IMListAdapter.java:116)
                                                                       at android.view.View.performLongClick(View.java:5308)
                                                                       at android.view.View$CheckForLongPress.run(View.java:21522)
                                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                       at android.os.Looper.loop(Looper.java:207)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5740)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)

Activity code:

public class IMListActivity extends AppCompatActivity implements Sertivity{

private RecyclerView recyclerView;
private IMListAdapter imListAdapter;
private List<Chat> chatList = new ArrayList<>();
List<String> stringList;
ActiveChatsDB activeChatsDB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imlist);
    Toolbar toolbar = (Toolbar)findViewById(R.id.imlist_toolbar);
    setSupportActionBar(toolbar);
    setBackButtonOnToolbar();

    recyclerView = (RecyclerView)findViewById(R.id.rv_im_list);
    imListAdapter = new IMListAdapter(chatList, getApplicationContext());
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    recyclerView.setAdapter(imListAdapter);
    prepareChatListData();
}

private void prepareChatListData() {
    String friend;
    String latestMessage;
    activeChatsDB = new ActiveChatsDB(IMListActivity.this);
    stringList = activeChatsDB.getChatList();
    activeChatsDB.close();
    for (int i=0; i<stringList.size(); i++) {
        friend = stringList.get(i);
        DBAct dbAct = new  DBAct(IMListActivity.this,friend);
        latestMessage = dbAct.getLatestMessage();
        dbAct.close();
        Chat chat = new Chat(friend, latestMessage);
        chatList.add(chat);
    }
    imListAdapter.notifyDataSetChanged();
}

private void setBackButtonOnToolbar(){
    if(getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}

public RecyclerView getRecyclerView() {
    return recyclerView;
}

}

Adapter code:

public class IMListAdapter extends RecyclerView.Adapter <com.abdralabs.talksee.IMListAdapter.IMListViewHolder> {

private List<Chat> chatList = new ArrayList<Chat>() ;
private Context ctx;
private MultiSelector multiSelector = new MultiSelector();
private ModalMultiSelectorCallback modalMultiSelectorCallback =
        new ModalMultiSelectorCallback(multiSelector) {
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                if (item.getItemId() == R.id.item_delete) {
                    mode.finish();

                    for (int i = chatList.size(); i >= 0; i--) {
                        if (multiSelector.isSelected(i, 0)) { // (1)
                            // remove item from list
                            ((IMListActivity)ctx).getRecyclerView().getAdapter().notifyItemRemoved(i);
                        }
                    }

                    multiSelector.clearSelections(); // (2)
                    return true;

                }
                return false;
            }

            @Override
            public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                super.onCreateActionMode(actionMode, menu);
                ((AppCompatActivity)ctx).getMenuInflater().inflate(R.menu.contextual_menu_friends, menu);
                return true;
            }
        };

public IMListAdapter(List<Chat> chatList, Context ctx){
    this.chatList = chatList;
    this.ctx = ctx;
}

@Override
public com.abdralabs.talksee.IMListAdapter.IMListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_list_row,parent,false);
    return new com.abdralabs.talksee.IMListAdapter.IMListViewHolder(itemView, chatList, ctx);    }

@Override
public void onBindViewHolder(com.abdralabs.talksee.IMListAdapter.IMListViewHolder holder, int position) {
    Chat chat = chatList.get(position);
    holder.name.setText(chat.getName());
    holder.recentMsg.setText(chat.getRecentMessage());
}

@Override
public int getItemCount() {
    return chatList.size();
}

public class IMListViewHolder extends SwappingHolder implements View.OnClickListener, View.OnLongClickListener{
    public TextView name;
    public TextView recentMsg;
    List<Chat> chatList = new ArrayList<Chat>();
    Context ctx;

    public IMListViewHolder(View itemView, List<Chat> chatList, Context ctx) {
        super(itemView, multiSelector);
        this.chatList = chatList;
        this.ctx = ctx;
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
        itemView.setLongClickable(true);
        name = (TextView) itemView.findViewById(R.id.name_chat);
        recentMsg = (TextView)itemView.findViewById(R.id.tv_recent_msg_im_list);
    }

    @Override
    public void onClick(View v) {
        int position = getAdapterPosition();
        Chat chat = this.chatList.get(position);
        Intent intent = new Intent(this.ctx, IMActivity.class);
        intent.putExtra("otherUserName",chat.getName());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.ctx.startActivity(intent);

    }

    @Override
    public boolean onLongClick(View v) {
        if (!multiSelector.isSelectable()) { // (3)
            ((AppCompatActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
            multiSelector.setSelectable(true); // (4)
            multiSelector.setSelected(com.abdralabs.talksee.IMListAdapter.IMListViewHolder.this, true); // (5)
            return true;
        }
        return false;
    }
}

}

I don't know how I'm supposed to peform the right type casting. Please help.

EDIT 1:

I tried replacing the onLongClick code to

public boolean onLongClick(View v) {
        if (!multiSelector.isSelectable()) { // (3)
            ((IMListActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
            multiSelector.setSelectable(true); // (4)
            multiSelector.setSelected(IMListViewHolder.this, true); // (5)
            return true;
        }
        return false;
    }

as Sachin Bahukhandi suggested, but I'm getting the same error

java.lang.ClassCastException: com.abdralabs.talksee.MyApplication cannot be cast to com.abdralabs.talksee.IMListActivity
                                                                     at com.abdralabs.talksee.IMListAdapter$IMListViewHolder.onLongClick(IMListAdapter.java:116)
                                                                     at android.view.View.performLongClick(View.java:5308)
                                                                     at android.view.View$CheckForLongPress.run(View.java:21522)
                                                                     at android.os.Handler.handleCallback(Handler.java:815)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                     at android.os.Looper.loop(Looper.java:207)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5740)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)

In the tutorial that I'm following the code is as such:

@Override
public boolean onLongClick(View view) {
    if (!mMultiSelector.isSelectable()) {
        ((AppCompatActivity) getActivity()).startSupportActionMode(mActionModeCallback); // (2)
        mMultiSelector.setSelectable(true);
        mMultiSelector.setSelected(MyViewHolder.this, true);
        return true;
    }
    return false;
}

In the above code getActivity is called somehow from the Viewholder and type casted to AppCompatActivity. I don't know how to call getActivity directly from the ViewHolder since I'm getting and error so I tried to type cast a context object (which was passed from my Activity through the adapter constructor) to AppCompatActivity. So I don't exactly know what I'm doing wrong here.

Body:
In the code you posted the application crashed because it cannot cast Context to AppCompatActivity.

 @Override
public boolean onLongClick(View v) {
    if (!multiSelector.isSelectable()) { // (3)
        ((AppCompatActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
        multiSelector.setSelectable(true); // (4)
        multiSelector.setSelected(com.abdralabs.talksee.IMListAdapter.IMListViewHolder.this, true); // (5)
        return true;
    }
    return false;
}

So I suggest to replace

((AppCompatActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
        multiSelector.setSelectable(true); // (4)

To YourActivity:

((IMListActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
        multiSelector.setSelectable(true); // (4)

Hope this helps.


问:
Installing Python Module in pycharm From GitHub
I have downloaded the py-earth module from GitHub and followed the provided installation procedures as well as done "pip install". Things seem to be installing in the terminal, but I cant find the module when I am in pycharm. I have restarted pycharm, reinstalled, and no matter what I can't find a way to install the module. Please help</p>

答: Have you gone into your settings and set your project interpreter in settings > Project: {project-name}> Project Interpreter to your version of python that has the module you installed?


问:
Datatables ajax sort by method
I have a basic datatables that I use with will_paginate.

```<code><table id="users" class="display" data-source="<%= url_for(:controller => "/account", :action => :paginate, :format => :json) %>">
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Role</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
</code>```

The jQuery is

```<code><script type="text/javascript">
    jQuery(function() {
      return $('#users').DataTable({
        processing: true,
        serverSide: true,
        ajax: $('#users').data('source'),
        columns : [
            { data: "first_name" },
            { data: "last_name" },
            { data: "username" },
            { data: "role" }
        ]
      });
    });
</script>
</code>```

While everything mostly work wonderfully, including the column search, my role column, however, does not.

While everything else are attributes that I use SQL to query, role is a method call.

```<code>def role
  return "admin" if self.admin?
  return "manager" if self.manager?
  return "user"
end
</code>```

This in turn will not work with column sorting.

With that said, is there a way to use will_paginate and datatables with ajax to use a custom sort with the method output? I tried using data-order on the column but that doesn't seem to be it.

答:
I was using will-paginate for while but I stopped using it. Try to use datatables only without pagination as it has a pagination inside.

Here is the code example

```<code><script type="text/javascript">
        // DO NOT REMOVE : GLOBAL FUNCTIONS!
        $(document).ready(function() {
                var responsiveHelper_dt_basic = undefined;
                var responsiveHelper_dt_basic2 = undefined;
                var breakpointDefinition = {
                    tablet : 1024,
                    phone : 480
                };
                $('#users_table').dataTable({
                    "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>"+
                        "t"+
                        "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                    "autoWidth" : true,
                    "preDrawCallback" : function() {
                        // Initialize the responsive datatables helper once.
                        if (!responsiveHelper_dt_basic) {
                            responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#users_table'), breakpointDefinition);
                        }
                    },
                    "rowCallback" : function(nRow) {
                        responsiveHelper_dt_basic.createExpandIcon(nRow);
                    },
                    "drawCallback" : function(oSettings) {
                        responsiveHelper_dt_basic.respond();
                    },
                    "iDisplayLength": 50
                });
        })
</script>
</code>```

Title: Datatables ajax sort by method

Body:
I have a basic datatables that I use with will_paginate.

<table id="users" class="display" data-source="<%= url_for(:controller => "/account", :action => :paginate, :format => :json) %>">

      First Name
      Last Name
      Email
      Role

The jQuery is

While everything mostly work wonderfully, including the column search, my role column, however, does not.

While everything else are attributes that I use SQL to query, role is a method call.

def role
  return "admin" if self.admin?
  return "manager" if self.manager?
  return "user"
end

This in turn will not work with column sorting.

With that said, is there a way to use will_paginate and datatables with ajax to use a custom sort with the method output? I tried using data-order on the column but that doesn't seem to be it.

Body:
I was using will-paginate for while but I stopped using it. Try to use datatables only without pagination as it has a pagination inside.

Here is the code example

<script type="text/javascript">
        // DO NOT REMOVE : GLOBAL FUNCTIONS!
        $(document).ready(function() {
                var responsiveHelper_dt_basic = undefined;
                var responsiveHelper_dt_basic2 = undefined;
                var breakpointDefinition = {
                    tablet : 1024,
                    phone : 480
                };
                $('#users_table').dataTable({
                    "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>"+
                        "t"+
                        "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                    "autoWidth" : true,
                    "preDrawCallback" : function() {
                        // Initialize the responsive datatables helper once.
                        if (!responsiveHelper_dt_basic) {
                            responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#users_table'), breakpointDefinition);
                        }
                    },
                    "rowCallback" : function(nRow) {
                        responsiveHelper_dt_basic.createExpandIcon(nRow);
                    },
                    "drawCallback" : function(oSettings) {
                        responsiveHelper_dt_basic.respond();
                    },
                    "iDisplayLength": 50
                });
        })
</script>


问:
yii 1.x after extending component with thread yii models not working
I have add pthreads in my xampp and its working fine without yii framework and also in yii framework by yii models, yii functions and included extension e.g. yiimailer is not working in this class, echo Yii::app()->basePath; is also not working

My component class

```<code>class SendEmailThreads extends Thread{
    private $sendTo;
    private $subject;
    private $bodyText;
    public function __construct($sendTo, $subject, $bodyText){
        $this->sendTo = $sendTo;
        $this->subject = $subject;
        $this->bodyText = $bodyText;
    }
    function run(){
        echo Yii::app()->basePath;
        sleep(1);

    }
}
</code>```

Used Here

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

for($i=0;$i<3;$i++){

   $pool[] = new SendEmailThreads('frazghuman@gmail.com','test bulk','test by fraz');
 }

 foreach($pool as $worker){
    $worker->start();
 }

 foreach($pool as $worker){
    $worker->join();
 }
</code>```

}

答:
The problem is that pthreads does not copy static members that are objects (with the exception of Threaded and Closure objects). This means that inside of the new thread, null is being returned when attempting to fetch the single instance via Yii::app().

The only workaround that I can think of for this - which, I have no idea of its suitability, given that I've never used Yii before - is to create a new singleton instance per thread.

Really, though, global state should be considered a red flag when it comes to threading. Therefore, if an application or framework makes heavy use of it (as do most PHP frameworks nowadays, it would seem), then threading isn't really a viable option.

Body:
I have add pthreads in my xampp and its working fine without yii framework and also in yii framework by yii models, yii functions and included extension e.g. yiimailer is not working in this class, echo Yii::app()->basePath; is also not working

My component class

class SendEmailThreads extends Thread{
    private $sendTo;
    private $subject;
    private $bodyText;
    public function __construct($sendTo, $subject, $bodyText){
        $this->sendTo = $sendTo;
        $this->subject = $subject;
        $this->bodyText = $bodyText;
    }
    function run(){
        echo Yii::app()->basePath;
        sleep(1);

    }
}

Used Here

public function actionBulkEmail(){

for($i=0;$i<3;$i++){

   $pool[] = new SendEmailThreads('frazghuman@gmail.com','test bulk','test by fraz');
 }

 foreach($pool as $worker){
    $worker->start();
 }

 foreach($pool as $worker){
    $worker->join();
 }

}


问:
how to search for multiple strings in multiple columns in ORACLE SQL where clause
My situation - I have to two tables with several columns each, and I need to find certain strings in certain columns in those two tables. For example the search string could be 'ExampleString1' , 'ExampleString2%' etc around 20 strings and about 5 - 6 columns in each table.

I m using the following to find atleast one string in the multiple columns, but this even is not working.

```<code>select * from table1 a where upper('ExampleString1%') in (a.Column1, a.column2, a.column3)
</code>```

Although I can do some basic sql queries, I m not that acquaint with sql. I like to know the solution or any material I can study to get to solution.

Thanks
rK

答:
You can combine all required fields and run a check on that:</p>

```<code>select *
from table1 a
where NVL(upper(a.Column1),'')||NVL(upper(a.column2),'')||NVL(upper(a.column3),'') like upper('ExampleString1%')
</code>```

Body:
My situation - I have to two tables with several columns each, and I need to find certain strings in certain columns in those two tables. For example the search string could be 'ExampleString1' , 'ExampleString2%' etc around 20 strings and about 5 - 6 columns in each table.

I m using the following to find atleast one string in the multiple columns, but this even is not working.

select * from table1 a where upper('ExampleString1%') in (a.Column1, a.column2, a.column3)

Although I can do some basic sql queries, I m not that acquaint with sql. I like to know the solution or any material I can study to get to solution.

Thanks
rK

Body:
You can combine all required fields and run a check on that:

select *
from table1 a
where NVL(upper(a.Column1),'')||NVL(upper(a.column2),'')||NVL(upper(a.column3),'') like upper('ExampleString1%')


问:
Initialize multiple variables with different parameters
I have the following code in python 3:

```<code>x = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(5)]
</code>```

Is there a better way to initialize multiple (5+) lists with different K values and in range()?

ex:

```<code>y = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
z = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(2)]
a = [(''.join(random.choices(string.ascii_lowercase, k=4))) for _ in range(3)]
b = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
c = [(''.join(random.choices(string.ascii_lowercase, k=1))) for _ in range(3)]
</code>```

答:
Sure: parameterise the arguments:</p>

```<code>import random
import string

k_val = [3, 7, 4, 3, 1]
r_val = [5, 2, 3, 5, 3]

x = [[(''.join(random.choice(string.ascii_lowercase, k=k_val[i])))
           for _ in range(r_val[i])] for i in range (len(r_val)) ]
</code>```

Body:
I have the following code in python 3:

x = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(5)]

Is there a better way to initialize multiple (5+) lists with different K values and in range()?

ex:

y = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
z = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(2)]
a = [(''.join(random.choices(string.ascii_lowercase, k=4))) for _ in range(3)]
b = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
c = [(''.join(random.choices(string.ascii_lowercase, k=1))) for _ in range(3)]

Body:
Sure: parameterise the arguments:

import random
import string

k_val = [3, 7, 4, 3, 1]
r_val = [5, 2, 3, 5, 3]

x = [[(''.join(random.choice(string.ascii_lowercase, k=k_val[i])))
           for _ in range(r_val[i])] for i in range (len(r_val)) ]


问:
How to extend inner nested objects into multiple objects
In Node.js, I want to convert to extend the nested objects into an array, details as follwing:

```<code> {
"topic":"myTopic",
"content":{
    "name": {
        "tom1" : {
            "value": "String",
        },
        "tom2" : {
            "value": "String",
        },
        "tom3" : {
            "value": "String",
        }
    }
}
}
</code>```

convert and extend to following format

```<code>[{
"topic":"myTopic",
"content":{
    "name": {
        "tom1" : {
            "value": "String",
        }
    }
}
},

{
"topic":"myTopic",
"content":{
    "name": {
        "tom2" : {
            "value": "String",
        }
    }
 }
 },
{
"topic":"myTopic",
"content":{
    "name": {
        "tom3" : {
            "value": "String",
        }
    }
}
}]
</code>```

答:
You could use map and some of the Object methods:

function splitObject(obj) {
    return Object.keys(obj.content.name).map( key => Object.assign({}, {
        content: { name: { [key]: obj.content.name[key] } }
    }) );
}

const obj = {
    topic: "myTopic",
    content: {
        name: {
            tom1: {
                value: "String",
            },
            tom2: {
                value: "String",
            },
            tom3: {
                value: "String",
            }
        }
    }
};

const result = splitObject(obj);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
In Node.js, I want to convert to extend the nested objects into an array, details as follwing:

 {
"topic":"myTopic",
"content":{
    "name": {
        "tom1" : {
            "value": "String",
        },
        "tom2" : {
            "value": "String",
        },
        "tom3" : {
            "value": "String",
        }
    }
}
}

convert and extend to following format

[{
"topic":"myTopic",
"content":{
    "name": {
        "tom1" : {
            "value": "String",
        }
    }
}
},

{
"topic":"myTopic",
"content":{
    "name": {
        "tom2" : {
            "value": "String",
        }
    }
 }
 },
{
"topic":"myTopic",
"content":{
    "name": {
        "tom3" : {
            "value": "String",
        }
    }
}
}]

Body:
You could use map and some of the Object methods:

function splitObject(obj) {
    return Object.keys(obj.content.name).map( key => Object.assign({}, {
        content: { name: { [key]: obj.content.name[key] } }
    }) );
}

const obj = {
    topic: "myTopic",
    content: {
        name: {
            tom1: {
                value: "String",
            },
            tom2: {
                value: "String",
            },
            tom3: {
                value: "String",
            }
        }
    }
};

const result = splitObject(obj);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
End to end testing of two or more mule applications
I have multiple mule applications forming one big application. Individual components have been tested but when it comes to automate end to end testing we are finding a way for it.

Application 1 takes an input, processes it and send the processed object to application 2 which processes the input and sends to application 3, output of third application is the final result.

I want to validate the integration among the application 1-2 and 2-3 and then 1-3 also, so that we can easily test whenever there are more applications added to the main application.

Can anyone help me out on this, are there any tools which can be used to test this inside or outside anypoint studio?

Thanks in advance.

答:
I'm not sure how objects are being passed between your applications, however what might work for you is to create "test" mule flows that use an HTTP inbound endpoint, the next step in the flow can setup your object, then you can call your main flow via a flow reference. Something like this:</p>

```<code><flow name="testFlow">
       <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
       <set-payload doc:name="Set Payload" value="required input"/>
       <flow-ref name="yourAppFlow" doc:name=""/>
</flow>
</code>```

Body:
I'm not sure how objects are being passed between your applications, however what might work for you is to create "test" mule flows that use an HTTP inbound endpoint, the next step in the flow can setup your object, then you can call your main flow via a flow reference. Something like this:

<flow name="testFlow">
       <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
       <set-payload doc:name="Set Payload" value="required input"/>
       <flow-ref name="yourAppFlow" doc:name=""/>
</flow>


问:
oracle sql: how do i sum different data points in a select statment?
i'm trying to return a sum which is the total of multiple rows of data that are returned. i'm trying to return data that shows an employee, account, and department. i want the sum of salary paid by those three data points. i also want a sum just by employee to show how their salary was distributed. an example is below. any help would be appreciated.

example

答:
what fhossfel wrote is basically how i want it to work.
here is what i have tried:

select employee, activity, SUM (salary_amt), SUM (salary_amt) OVER (PARTITION BY employee) AS "total salary by employee"
from mytable
where employee = 'xxx'
group by employee, activity

i'm getting the error that sum by employee is not a group by expression


问:
How to update particular field in mongo db by using MongoRepository Interface?
How to update a particular field in mongo db collection by using MongoRepository Interface in spring?</p>

答:
You can update specific field by below code:</p>
```<code>Query query1 = new Query(Criteria.where("id").is("123"));
Update update1 = new Update();
update1.set("available", false);
mongoTemplate.updateFirst(query1, update1, Customer.class);
</code>```

Body:
You can update specific field by below code:

Query query1 = new Query(Criteria.where("id").is("123"));
Update update1 = new Update();
update1.set("available", false);
mongoTemplate.updateFirst(query1, update1, Customer.class);


问:
Temporary memory leak in Swift
I have a big picture that consists of small pictures of 50 * 50 pixels. Number of small pictures n * m. You need to make a small copy of 50 * 50 -> 2 * 2 for each picture. I launch the code - on the simulator it is visible that at this stage it is 1.3-1.4 GB of RAM, so on real devices the crash goes on. N = 200 m = 180</p>

```<code>UIGraphicsBeginImageContextWithOptions (CGSize (width: n * 2, height: m * 2), false, 0.0) var cellImage: UIImage? For y in 0 ..

 UIGraphicsBeginImageContextWithOptions(CGSize(width: n*2, height: m*2), false, 0.0)
 var cellImage : UIImage?
 for y in 0..<n {
    for x in 0..<m {
                cellImage = вызов функции для получения картинки 50*50...
                cellImage?.draw(in: CGRect(x: y*2, y: x*2, width: 2, height: 2))
                cellImage = nil
     }
 }

        // End
        miniViewImage.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
</code>```

答:
revise as follows:

```<code>   for x in 0..<m {
      autoreleasepool {
                cellImage = вызов функции для получения картинки 50*50...
                cellImage?.draw(in: CGRect(x: y*2, y: x*2, width: 2, height: 2))
                cellImage = nil
      }
   }
</code>```

This will release memory each step of the iteration.

Title: Temporary memory leak in Swift

Body:
I have a big picture that consists of small pictures of 50 * 50 pixels. Number of small pictures n * m. You need to make a small copy of 50 * 50 -> 2 * 2 for each picture. I launch the code - on the simulator it is visible that at this stage it is 1.3-1.4 GB of RAM, so on real devices the crash goes on. N = 200 m = 180

UIGraphicsBeginImageContextWithOptions (CGSize (width: n * 2, height: m * 2), false, 0.0) var cellImage: UIImage? For y in 0 ..

 UIGraphicsBeginImageContextWithOptions(CGSize(width: n*2, height: m*2), false, 0.0)
 var cellImage : UIImage?
 for y in 0..<n {
    for x in 0..<m {
                cellImage = вызов функции для получения картинки 50*50...
                cellImage?.draw(in: CGRect(x: y*2, y: x*2, width: 2, height: 2))
                cellImage = nil
     }
 }

        // End
        miniViewImage.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

Body:
revise as follows:

   for x in 0..<m {
      autoreleasepool {
                cellImage = вызов функции для получения картинки 50*50...
                cellImage?.draw(in: CGRect(x: y*2, y: x*2, width: 2, height: 2))
                cellImage = nil
      }
   }

This will release memory each step of the iteration.


问:
Converting from vector<string> to wchar_t**
```<code>std::vector<std::string> elems = split(command, ' ');
const int argc = elems.size();
wchar_t** argv = new wchar_t*[argc]();
//wchar_t* argv[10];
for (int i = 0; i < argc; i++) {
    const char* arg = elems[i].c_str();
    int size = strlen(arg);
    size_t length = 0;
    wchar_t* e = new wchar_t[size];
    mbstowcs_s(&length, e, size + 1, arg, size);
    argv[i] = e;
}
</code>```

This is my code attempting to convert a vector of strings to a wchar_t**. When I comment out the third line and uncomment the fourth line, it works. But I want my wchar_t** to persist, so I want to use the third line and not the fourth. Please explain to me why the third line does not work as expected.

答:
You can convert from string to wstring like this:

```<code>std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
auto warg = cv.from_bytes(arg);
auto wargv = warg.c_str();  // wchar_t*
</code>```

But you may also consider passing vector instead of int and wchar_t**:

```<code>std::vector<std::wstring> args;
for(auto& elm : elms)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
    args.push_back(cv.from_bytes(elm));
}
</code>```

Body:
std::vector<std::string> elems = split(command, ' ');
const int argc = elems.size();
wchar_t** argv = new wchar_t*[argc]();
//wchar_t* argv[10];
for (int i = 0; i < argc; i++) {
    const char* arg = elems[i].c_str();
    int size = strlen(arg);
    size_t length = 0;
    wchar_t* e = new wchar_t[size];
    mbstowcs_s(&length, e, size + 1, arg, size);
    argv[i] = e;
}

This is my code attempting to convert a vector of strings to a wchar_t**. When I comment out the third line and uncomment the fourth line, it works. But I want my wchar_t** to persist, so I want to use the third line and not the fourth. Please explain to me why the third line does not work as expected.

Body:
You can convert from string to wstring like this:

std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
auto warg = cv.from_bytes(arg);
auto wargv = warg.c_str();  // wchar_t*

But you may also consider passing vector instead of int and wchar_t**:

std::vector<std::wstring> args;
for(auto& elm : elms)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
    args.push_back(cv.from_bytes(elm));
}


问:
Selling Digital goods via REST API
I'm using paypal's REST API for digital transaction on my website. I have it all setup and working and have been able to successfully accept payments from a few users and give them their digital product. However, as of yet PayPal sees the transactions as if they were for physical items. I didn't find anything in the REST documentation regarding marking a transaction as digital. An example of one of my requests for the payment looks like this:

```<code>{
  "intent": "sale",
  "redirect_urls": {
    "return_url": "http:\/\/www.googulator.com\/goPro?finishPurchase=true&googleid=123456789",
    "cancel_url": "http:\/\/www.googulator.com\/goPro"
  },
  "payer": {
    "payment_method": "paypal"
  },
  "transactions": [
    {
      "amount": {
        "total": "5.00",
        "currency": "USD"
      },
      "description": "PWYW Lifetime Googulator Pro",
      "item_list": {
        "items": [
          {
            "quantity": "1",
            "name": "Lifetime Googulator Pro",
            "price": "5.00",
            "currency": "USD"
          }
        ]
      }
    }
  ]
}
</code>```

So my question is, are digital transactions properly supported in the REST API, or do I have to resort to using PayPal's classic APIs?

答:
I know it's too late but I'm answering in case someone else finds this question.

This is how you to using the C# SDK.

Create a profile:

```<code>string createProfile(APIContext apiContext) {
    var profile = new WebProfile()
    {
        name = Guid.NewGuid().ToString(),
        input_fields = new InputFields()
        {
            no_shipping = 1
        },
        temporary = true
    };

    return profile.Create(apiContext).id;
}
</code>```

Then you set the ID returned in this function in your payment:

```<code>var profileCreated = createProfile(apiContext);
            Payment paymentParms = new Payment {
                intent = "sale",
                payer = new Payer
                {
                    payment_method = "paypal"
                },
                redirect_urls = new RedirectUrls
                {
                    return_url = WebConfig.WebSite.BaseUrl + "Paypal/Success",
                    cancel_url = WebConfig.WebSite.BaseUrl + "Paypal/Cancel",

                },
                experience_profile_id = profileCreated
            };
</code>```

Title: Selling Digital goods via REST API

Body:
I'm using paypal's REST API for digital transaction on my website. I have it all setup and working and have been able to successfully accept payments from a few users and give them their digital product. However, as of yet PayPal sees the transactions as if they were for physical items. I didn't find anything in the REST documentation regarding marking a transaction as digital. An example of one of my requests for the payment looks like this:

{
  "intent": "sale",
  "redirect_urls": {
    "return_url": "http:\/\/www.googulator.com\/goPro?finishPurchase=true&googleid=123456789",
    "cancel_url": "http:\/\/www.googulator.com\/goPro"
  },
  "payer": {
    "payment_method": "paypal"
  },
  "transactions": [
    {
      "amount": {
        "total": "5.00",
        "currency": "USD"
      },
      "description": "PWYW Lifetime Googulator Pro",
      "item_list": {
        "items": [
          {
            "quantity": "1",
            "name": "Lifetime Googulator Pro",
            "price": "5.00",
            "currency": "USD"
          }
        ]
      }
    }
  ]
}

So my question is, are digital transactions properly supported in the REST API, or do I have to resort to using PayPal's classic APIs?

Body:
I know it's too late but I'm answering in case someone else finds this question.

This is how you to using the C# SDK.

Create a profile:

string createProfile(APIContext apiContext) {
    var profile = new WebProfile()
    {
        name = Guid.NewGuid().ToString(),
        input_fields = new InputFields()
        {
            no_shipping = 1
        },
        temporary = true
    };

    return profile.Create(apiContext).id;
}

Then you set the ID returned in this function in your payment:

var profileCreated = createProfile(apiContext);
            Payment paymentParms = new Payment {
                intent = "sale",
                payer = new Payer
                {
                    payment_method = "paypal"
                },
                redirect_urls = new RedirectUrls
                {
                    return_url = WebConfig.WebSite.BaseUrl + "Paypal/Success",
                    cancel_url = WebConfig.WebSite.BaseUrl + "Paypal/Cancel",

                },
                experience_profile_id = profileCreated
            };


问:
Displaying Text in Cardview, does not fit in screen
I have a layout which contains a CardView. I added Scrollview, I added android:scrollable=vertical in Textview, I added         mytxtview.setMovementMethod(new ScrollingMovementMethod());

NOTHING works! I have a very large text in a textview and it does not fit into the screen, I cant see the whole text, please help me. Here is my layout, please help me.

```<code>  <?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:tag="cards main container">

        <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card_viewfrag5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff"
            card_view:cardBackgroundColor="#A9E2F3"
            card_view:cardCornerRadius="10dp"
            card_view:cardElevation="5dp"
            card_view:cardUseCompatPadding="true"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="12dp"
                    android:layout_weight="2"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <android.support.v7.widget.Toolbar
                        android:id="@+id/toolbarfrag5"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="0.96"
                        android:background="#A9E2F3"
                        android:minHeight="?attr/actionBarSize"
                        android:theme="?attr/actionBarTheme">

                        <ImageView
                            android:id="@+id/imageViewfrag5"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_margin="5dp"
                            android:layout_weight="1"
                            android:src="@drawable/testbild"
                            android:tag="image_tag" />

                    </android.support.v7.widget.Toolbar>

                    <TextView
                        android:id="@+id/textViewNamefrag5"
                        android:layout_width="340dp"
                        android:maxLines="25"
                        android:scrollbars="vertical"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="10dp"
                        android:text="here is a very very very long text that does not fit into the screen"
                        android:layout_weight="0.96"
                        android:textAppearance="?android:attr/textAppearanceLarge" />

                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>

</ScrollView>
</code>```

EDIT: Java Code

```<code>public class Fragment5 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragmentdescrip5, container, false);

        TextView mytxtview = (TextView) rootView.findViewById(R.id.textViewNamefrag5);
        mytxtview.setMovementMethod(new ScrollingMovementMethod());

        return rootView;
    }

}
</code>```

答: Remove maxLines="25"; this limits the length of the text to 25 lines.

Body:
I have a layout which contains a CardView. I added Scrollview, I added android:scrollable=vertical in Textview, I added         mytxtview.setMovementMethod(new ScrollingMovementMethod());

NOTHING works! I have a very large text in a textview and it does not fit into the screen, I cant see the whole text, please help me. Here is my layout, please help me.

  <?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:tag="cards main container">

        <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card_viewfrag5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff"
            card_view:cardBackgroundColor="#A9E2F3"
            card_view:cardCornerRadius="10dp"
            card_view:cardElevation="5dp"
            card_view:cardUseCompatPadding="true"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="12dp"
                    android:layout_weight="2"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <android.support.v7.widget.Toolbar
                        android:id="@+id/toolbarfrag5"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="0.96"
                        android:background="#A9E2F3"
                        android:minHeight="?attr/actionBarSize"
                        android:theme="?attr/actionBarTheme">

                        <ImageView
                            android:id="@+id/imageViewfrag5"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_margin="5dp"
                            android:layout_weight="1"
                            android:src="@drawable/testbild"
                            android:tag="image_tag" />

                    </android.support.v7.widget.Toolbar>

                    <TextView
                        android:id="@+id/textViewNamefrag5"
                        android:layout_width="340dp"
                        android:maxLines="25"
                        android:scrollbars="vertical"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="10dp"
                        android:text="here is a very very very long text that does not fit into the screen"
                        android:layout_weight="0.96"
                        android:textAppearance="?android:attr/textAppearanceLarge" />

                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>

</ScrollView>

EDIT: Java Code

public class Fragment5 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragmentdescrip5, container, false);

        TextView mytxtview = (TextView) rootView.findViewById(R.id.textViewNamefrag5);
        mytxtview.setMovementMethod(new ScrollingMovementMethod());

        return rootView;
    }

}


问:
Remove row from database if image not on server
I have a mysql database with a table in the following format:

ID: 1

Date: 2010-12-19

Image: 5d61240f-7aca-d34b-19-12-10-15-36.jpg

Caption: Merry Xmas

I want to create a php script which checks through each row in this table and checks that the image is present in a gallery folder on my server. If the image is not in the gallery folder then I want to delete this row from my database. Some pointers on how to go about doing this would be very much appreciated.

Thanks!

答:
Ok... use glob() or the DirectoryIterator, file_exists(), the mysql_ or mysqli_ functions, and 'DELETE FROM images WHERE id = ?'. :)

Hope this helps! If you supply some more information, I could give you more detailed advice. What have you tried so far?

EDIT: wait, I misread. You don't need the directory functions, as you already have the filename. dirname(__FILE__) might be useful.

ContentLicense: CC BY-SA 2.5


问:
Passing a function as an argument
I am teaching myself javascript and one of the exercises I have tried makes no sense to me.

In the code below 'position' is a parameter that must be defined. However, when I pass the function, displayLocation as an argument to navigator.geolocation.getCurrentPosition, the code executes flawlessly, despite no argument being passed. When I try coords.longitude in the console without the position argument, it does not work.

How does the code work without a defined argument?

```<code>function displayLocation(position)
{
  var latitude = latitude.coords.latitude;
  var longitude = position.coords.longitude;
  var div = document.getElementById("location");
  div.innerHTML = latitude + " " + longitude;
}

navigator.geolocation.getCurrentPosition(displayLocation);
</code>```

答:
What you are doing when you do

```<code>navigator.geolocation.getCurrentPosition(displayLocation);
</code>```

is that you are calling navigator.geolocation.getCurrentPosition, and giving it a handle to your function displayLocation.  You cannot say that displayLocation is getting called without an argument.  That depends on what getCurrentPosition does with that handle.  What it does is that it creates a position object, and then calls the function you gave it, with that object as a parameter.  More succinctly, getCurrentPosition calls displayLocation with a position object, it created, as a parameter.

Title: Passing a function as an argument

Body:
I am teaching myself javascript and one of the exercises I have tried makes no sense to me.

In the code below 'position' is a parameter that must be defined. However, when I pass the function, displayLocation as an argument to navigator.geolocation.getCurrentPosition, the code executes flawlessly, despite no argument being passed. When I try coords.longitude in the console without the position argument, it does not work.

How does the code work without a defined argument?

function displayLocation(position)
{
  var latitude = latitude.coords.latitude;
  var longitude = position.coords.longitude;
  var div = document.getElementById("location");
  div.innerHTML = latitude + " " + longitude;
}

navigator.geolocation.getCurrentPosition(displayLocation);

Body:
What you are doing when you do

navigator.geolocation.getCurrentPosition(displayLocation);

is that you are calling navigator.geolocation.getCurrentPosition, and giving it a handle to your function displayLocation.  You cannot say that displayLocation is getting called without an argument.  That depends on what getCurrentPosition does with that handle.  What it does is that it creates a position object, and then calls the function you gave it, with that object as a parameter.  More succinctly, getCurrentPosition calls displayLocation with a position object, it created, as a parameter.


问:
Behaviour of array during recursion
```<code>#include <iostream>
#include <vector>
using namespace std;
int count;
vector<char*> ans;
char result[1000];   //result will store the current subsequence
void printAllSubsequences(char str[], int beg, int res_index) {
    if(str[beg] == '\0') {  // if you reach end of string, print the result(i.e.,one of the subsequences). Recursion quits after encountering the last element in the given string str
        result[res_index] = '\0';
        ++count;
        cout<<result<<' ';
        ans.push_back(result);
        return;
    }

    printAllSubsequences(str, beg+1, res_index);
    result[res_index] = str[beg];
    printAllSubsequences(str, beg+1, res_index+1);
}
int main() {
    char str[1000];   //str is the string whose permutations we have to find
    cin >> str;
    char result[1000];
    printAllSubsequences(str, 0, 0);
    cout<<count<<endl;
    for(vector<char*>::iterator ii = ans.begin(); ii!=ans.end(); ++ii){
        cout<<(*ii)<<' ';
    }
    cout<<endl;
}
</code>```

When I give an input as

```<code>abcd
</code>```

I get the following as output

```<code> d c cd b bd bc bcd a ad ac acd ab abd abc abcd 16
 abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd
</code>```

So, the first line returns the subsequences; great!
For, the second if I store the same in a vector and then try to print it out, it gives me the same string over and over again. Where could the implementation be possibly going wrong ?

Thanks.

答:
Where could the implementation be possibly going wrong?

Here:

```<code>vector<char*> ans;
</code>```

Explanation: You have created a vector of a pointer. Since every time you push the same pointer in the array so once the pointed memory output gets changed it will change the output of already pushed entries as well.

To fix the issue use std::string instead of char array

Title: Behaviour of array during recursion

Body:
#include <iostream>
#include <vector>
using namespace std;
int count;
vector<char*> ans;
char result[1000];   //result will store the current subsequence
void printAllSubsequences(char str[], int beg, int res_index) {
    if(str[beg] == '\0') {  // if you reach end of string, print the result(i.e.,one of the subsequences). Recursion quits after encountering the last element in the given string str
        result[res_index] = '\0';
        ++count;
        cout<<result<<' ';
        ans.push_back(result);
        return;
    }

    printAllSubsequences(str, beg+1, res_index);
    result[res_index] = str[beg];
    printAllSubsequences(str, beg+1, res_index+1);
}
int main() {
    char str[1000];   //str is the string whose permutations we have to find
    cin >> str;
    char result[1000];
    printAllSubsequences(str, 0, 0);
    cout<<count<<endl;
    for(vector<char*>::iterator ii = ans.begin(); ii!=ans.end(); ++ii){
        cout<<(*ii)<<' ';
    }
    cout<<endl;
}

When I give an input as

abcd

I get the following as output

 d c cd b bd bc bcd a ad ac acd ab abd abc abcd 16
 abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd

So, the first line returns the subsequences; great!
For, the second if I store the same in a vector and then try to print it out, it gives me the same string over and over again. Where could the implementation be possibly going wrong ?

Thanks.

Body:
Where could the implementation be possibly going wrong?

Here:

vector<char*> ans;

Explanation: You have created a vector of a pointer. Since every time you push the same pointer in the array so once the pointed memory output gets changed it will change the output of already pushed entries as well.

To fix the issue use std::string instead of char array


问:
Differentiate two on Activity Results by Request Code, How to write Request Code for "loginWIthFB" in the code
```<code>public  class MainActivity extends AppCompatActivity
        implements LoginSocial.OnFragmentInteractionListener, Updates.OnFragmentInteractionListener,View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {
    private SignInButton sign;
    private GoogleApiClient googleApiClient;
    static final int Set_Ringtone = 0;
    static final int PICK_CONTACT_REQUEST = 1;
    private static final int RC_SIGN_IN = 9001;
    private String TAG;
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());

        setContentView(R.layout.activity_main);
        initializeControls();
        loginWithFB();
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        sign = (SignInButton)findViewById(R.id.sign_in_button);

        sign.setOnClickListener(this);

    }
    @Override
    public void onClick(View view) {

        switch (view.getId())

        {
            case R.id.sign_in_button:
                sign();
                break;
        }
    }

    private void sign() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    private void handleResult(GoogleSignInResult result) {

        Log.d(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            updateUI(true);
        } else {
            // Signed out, show unauthenticated UI.
            updateUI(false);
        }

    }

    private void updateUI(boolean b) {

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new LoginSocial(), "ONE");
        adapter.addFragment(new Updates(), "TWO");
        viewPager.setAdapter(adapter);

    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    TextView txtStatus;
    LoginButton fb_login;
    CallbackManager callbackManager;

    private void initializeControls(){

        callbackManager = CallbackManager.Factory.create();
        txtStatus = (TextView) findViewById(R.id.txtStatus);
        fb_login = (LoginButton) findViewById(R.id.fb_login);
    }

    private void loginWithFB(){

        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                txtStatus.setText("Login Success");
            }

            @Override
            public void onCancel() {
                txtStatus.setText("Login Cancelled.");
            }

            @Override
            public void onError(FacebookException error) {
                txtStatus.setText("Login Error:"+error.getMessage());
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            callbackManager.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleResult(result);

        }
</code>```

答:
You can use FacebookSdk.isFacebookRequestCode() to check if the request code is from Facebook.

```<code>protected void onActivityResult(int requestCode, int resultCode, Intent data)
    super.onActivityResult(requestCode, resultCode, data);
    if (FacebookSdk.isFacebookRequestCode(requestCode) {
        // Facebook
        callbackManager.onActivityResult(requestCode, resultCode, data);
    } else if (requestCode == RC_SIGN_IN) {
       // Google
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleResult(result);
    }
}
</code>```

Body:
You can use FacebookSdk.isFacebookRequestCode() to check if the request code is from Facebook.

protected void onActivityResult(int requestCode, int resultCode, Intent data)
    super.onActivityResult(requestCode, resultCode, data);
    if (FacebookSdk.isFacebookRequestCode(requestCode) {
        // Facebook
        callbackManager.onActivityResult(requestCode, resultCode, data);
    } else if (requestCode == RC_SIGN_IN) {
       // Google
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleResult(result);
    }
}


问:
JavaScript pen objects with replaceable nibs
I have a JavaScript question. Imagine a virtual pen. There are many different possible nibs the pen can have, although the pen can only have one nib. I want to create a pen object and then assign it a nib. The nib needs to access the properties and methods of the pen.

This is probably a well-known design pattern. What is the name of this design pattern?

```<code>function Pen() {
  var p1=5;
  this.nib=null;
}

function Nib1() {
  // needs access to p1.
}

function Nib2() {
  // needs access to p1.
}

var p = new Pen();
var n1 = new Nib1();
p.nib = n1;
// n1 needs access to p1
</code>```

答:
It sounds a bit like using a constructor. This chapter describes a similar situation but with rabbits instead of pens: http://eloquentjavascript.net/06_object.html#constructors.

The pen would be the constructor:

```<code>function Pen(nib) {
  // shared scope
  this.nib = nib;
}
</code>```

Then you can create

```<code>var bluePen = new Pen(blue)
</code>```

... Although I guess it's slightly different because you're describing a single pen and with the constructor you can end up with multiple instances.

Body:
I have a JavaScript question. Imagine a virtual pen. There are many different possible nibs the pen can have, although the pen can only have one nib. I want to create a pen object and then assign it a nib. The nib needs to access the properties and methods of the pen.

This is probably a well-known design pattern. What is the name of this design pattern?

function Pen() {
  var p1=5;
  this.nib=null;
}

function Nib1() {
  // needs access to p1.
}

function Nib2() {
  // needs access to p1.
}

var p = new Pen();
var n1 = new Nib1();
p.nib = n1;
// n1 needs access to p1

Body:
It sounds a bit like using a constructor. This chapter describes a similar situation but with rabbits instead of pens: http://eloquentjavascript.net/06_object.html#constructors.

The pen would be the constructor:

function Pen(nib) {
  // shared scope
  this.nib = nib;
}

Then you can create

var bluePen = new Pen(blue)

... Although I guess it's slightly different because you're describing a single pen and with the constructor you can end up with multiple instances.


问:
posting a value and retrieve it in php
I have two fields in a form category name and id. The id is an auto increment. After posting the category name, I want that posted category id pass to next page.

I think i am doing some mistake in select statement.

http://pastebin.com/3Tu2Hr6g

答:
Instead of

```<code>"SELECT ThirdPartyCategoryID,'".$ThirdPartyCategoryName."' FROM  thirdpartycategorymaster"
</code>```

you probably want something like this:

```<code>"SELECT ThirdPartyCategoryID,ThirdPartyCategoryName FROM  thirdpartycategorymaster WHERE ThirdPartyCategoryName='".$ThirdPartyCategoryName."'"
</code>```

And before I forget: PLEASE check and escape user input from HTTP requests before you insert it into your queries. The code you posted is extremely vulnerable to SQL injection.

OwnerDisplayName: Please delete me

LastEditorDisplayName: Please delete me

Title: posting a value and retrieve it in php

Body:
Instead of

"SELECT ThirdPartyCategoryID,'".$ThirdPartyCategoryName."' FROM  thirdpartycategorymaster"

you probably want something like this:

"SELECT ThirdPartyCategoryID,ThirdPartyCategoryName FROM  thirdpartycategorymaster WHERE ThirdPartyCategoryName='".$ThirdPartyCategoryName."'"

And before I forget: PLEASE check and escape user input from HTTP requests before you insert it into your queries. The code you posted is extremely vulnerable to SQL injection.


问:
Double slash (//) as XML comment
I was a bit surprised that using double slash as comments seems to be valid XML.

The following parses correctly with Python and xml.etree.ElementTree and under xmllint --format:

```<code><root>
    <child1>text1</child1>
    <child2></child2> //this is a valid comment
    <child3></child3>
</root>
</code>```

I first thought that this could be seen as text node for root element, but trying it on python3 proved me wrong:

```<code>>>> import xml.etree.ElementTree as ET
>>> r=ET.parse("test.xml").getroot()
>>> r.text
'\n    '
>>> child2=r[1]
>>> child2.text
>>> ET.tostring(child2)
b'<child2 /> //this is a valid comment\n    '
</code>```

Can someone point me to the spec where this is allowed ?

答:
XML Explanation

No, comments can only be  in XML.  You're seeing //this is a valid comment as text, which is allowed between elements in mixed content.  You could just as easily have left out the //.

Python ElementTree Explanation

ET.tostring(e) is returning e.tail (the text appearing after e) as part of its string representation of e.  This can be confusing as most would expect ET.tostring(e) to return strictly some string value of the element of e and not include its text node sibling.  But, since e.tail is part of ET's element data structure, I suppose ET's designers felt justified in including e.tail too.

Title: Double slash (//) as XML comment

Body:
I was a bit surprised that using double slash as comments seems to be valid XML.

The following parses correctly with Python and xml.etree.ElementTree and under xmllint --format:

<root>
    <child1>text1</child1>
    <child2></child2> //this is a valid comment
    <child3></child3>
</root>

I first thought that this could be seen as text node for root element, but trying it on python3 proved me wrong:

>>> import xml.etree.ElementTree as ET
>>> r=ET.parse("test.xml").getroot()
>>> r.text
'\n    '
>>> child2=r[1]
>>> child2.text
>>> ET.tostring(child2)
b'<child2 /> //this is a valid comment\n    '

Can someone point me to the spec where this is allowed ?

Body:
XML Explanation

No, comments can only be <!-- comment --> in XML.  You're seeing //this is a valid comment as text, which is allowed between elements in mixed content.  You could just as easily have left out the //.

Python ElementTree Explanation

ET.tostring(e) is returning e.tail (the text appearing after e) as part of its string representation of e.  This can be confusing as most would expect ET.tostring(e) to return strictly some string value of the element of e and not include its text node sibling.  But, since e.tail is part of ET's element data structure, I suppose ET's designers felt justified in including e.tail too.


问:
How to initialize a Swing form created by the Intellij Designer?
I have to build multiple Swing forms and I thought to speed up the process by using the Form Designer provided by Intellij IDEA.

First of all, I've created a new GUI form.

Then I added some labels, text fields and a button to the form.

Now I want to add this form to another Panel. I've been checking out the Intellij help and I found this. Unfortunately it doesn't work like this. There is no accessible contentPane in this class, which is generated by the IDE.

What magic do I have to apply to get this to work?

Bonus question:
Usually I extend a Swing component. For example in that case I would have something like public class BullshitForm extends JPanel{}. Is this possible with the Intellij Designer?

答: Select the class BullshitForm press ALT + Insert and select Form main().


问:
VS code right click menu new class c#
I'm currently following some tutorial I bought which refers to 2 options called
"New C# class / New C# Interface", while I'm only seeing "New file."

I'm new to VSCODE and installed only C# from OmniSharp.

I'd like to have "New C# class" and "New C# Interface" in this menu as well.

答:
If you want those options in your right click menu, then you need to install the "C# Extensions" extension from the marketplace.

The link is here

Keep in mind this is just a shortcut extension, it is not actually required.

You can simply choose new file and give it the .cs extension if you want a new C# file.

Title: VS code right click menu new class c#


问:
My commented code becomes one line in Eclipse
Is there a way to not let code blocks become one line? Example:

```<code>                /*
                 * for (String word : tokens) { if (!StringUtil.hasUppercaseOrNonletter(word)) { filtered.add(word); } }
                 */
</code>```

I don't want to reduce the length of my comment line. For other general comments, I still want to keep the line length.

答:
After you write the block, just add /* to the line before the block, and */ after the block, like this:

```<code>    /*
    for (String word : tokens) {
        if (!StringUtil.hasUppercaseOrNonletter(word)) {
            filtered.add(word);
        }
    }
    */
</code>```

This will comment the whole block of code, without changing the formatting. Just write/paste the block first.

Or you can do command + /on a mac(for windows use ⊞ + /), which will make the block look like this:

```<code>//      for (String word : tokens) {
//          if (!StringUtil.hasUppercaseOrNonletter(word)) {
//              filtered.add(word);
//          }
//      }
</code>```

Body:
Is there a way to not let code blocks become one line? Example:

                /*
                 * for (String word : tokens) { if (!StringUtil.hasUppercaseOrNonletter(word)) { filtered.add(word); } }
                 */

I don't want to reduce the length of my comment line. For other general comments, I still want to keep the line length.

Body:
After you write the block, just add /* to the line before the block, and */ after the block, like this:

    /*
    for (String word : tokens) {
        if (!StringUtil.hasUppercaseOrNonletter(word)) {
            filtered.add(word);
        }
    }
    */

This will comment the whole block of code, without changing the formatting. Just write/paste the block first.

Or you can do command + /on a mac(for windows use ⊞ + /), which will make the block look like this:

//      for (String word : tokens) {
//          if (!StringUtil.hasUppercaseOrNonletter(word)) {
//              filtered.add(word);
//          }
//      }


问:
Query Waypoints need to scroll in both directions
I am using jQuery-waypoints and the infinite shortcut to load listings on my page. I have this all working and am trying to comply with Google's Guidelines on this by using pushState() to alter the browsers history. This is all working fine using this.

```<code>if ($('#list-col.active .list-col-content').length > 0 && !wayPoints) {
    initWaypoint();
}
;
function initWaypoint() {
    let infinite = new Waypoint.Infinite({
        element: $('#list-col.active .list-col-content'),
        offset: function () {
            return this.context.innerHeight() - this.adapter.outerHeight() + 2000
        },
        onAfterPageLoad: function (direction) {
            var last = $('.page-loaded:last');
            last.waypoint(function (direction) {
                if (direction == 'down') {
                    if (window[window.GoogleAnalyticsObject]) {
                        ga('set', 'page', last.data('url'));
                        ga('send', 'pageview');
                        console.log('pageview ' + last.data('url'));
                    }
                    history.pushState('', last.data('title'), last.data('url'));
                } else {
                    history.pushState('', last.data('prev_title'), last.data('prev_url'));
                }
            })
        }
    });
    wayPoints = true;
};
</code>```

Here is my issue/questions.

The new browser's URL is now https://www.example.com/listingpage?page=15. Per Google's Guidelines, that "component page" needs to load content with page 15's listings, and only page 15's content. No problem, I can do that. But now I have an issue with the content BEFORE page 15.

I now need to scroll up, loading more content (now above the existing content) as the user scrolls up.

I am at a loss on how to add a second infinite (really finite since it is loading down to 0) scroller that loads pages as you scroll up the page.

I know I am not the first to encounter this so any help or direction would be appreciated.

答:
No responses in several days so I researched and found an answer on my own. Posting some info here in case anyone else has same issue with infinite scrolling in both directions.

Best solution I found was on Google's Infinite Scroll search-friendly recommendations. That pages lists an infinite scroll with pagination demo. I had to do some modification for my specific use, but it is a great example and obviously following Google's recommendation is a good way to go.

Hope this helps someone.

Body:
I am using jQuery-waypoints and the infinite shortcut to load listings on my page. I have this all working and am trying to comply with Google's Guidelines on this by using pushState() to alter the browsers history. This is all working fine using this.

if ($('#list-col.active .list-col-content').length > 0 && !wayPoints) {
    initWaypoint();
}
;
function initWaypoint() {
    let infinite = new Waypoint.Infinite({
        element: $('#list-col.active .list-col-content'),
        offset: function () {
            return this.context.innerHeight() - this.adapter.outerHeight() + 2000
        },
        onAfterPageLoad: function (direction) {
            var last = $('.page-loaded:last');
            last.waypoint(function (direction) {
                if (direction == 'down') {
                    if (window[window.GoogleAnalyticsObject]) {
                        ga('set', 'page', last.data('url'));
                        ga('send', 'pageview');
                        console.log('pageview ' + last.data('url'));
                    }
                    history.pushState('', last.data('title'), last.data('url'));
                } else {
                    history.pushState('', last.data('prev_title'), last.data('prev_url'));
                }
            })
        }
    });
    wayPoints = true;
};

Here is my issue/questions.

The new browser's URL is now https://www.example.com/listingpage?page=15. Per Google's Guidelines, that "component page" needs to load content with page 15's listings, and only page 15's content. No problem, I can do that. But now I have an issue with the content BEFORE page 15.

I now need to scroll up, loading more content (now above the existing content) as the user scrolls up.

I am at a loss on how to add a second infinite (really finite since it is loading down to 0) scroller that loads pages as you scroll up the page.

I know I am not the first to encounter this so any help or direction would be appreciated.


问:
grep curl output starting with string but show without it
```<code>   curl -i -v --silent \
     -H "Content-Type: application/json" \
     -d '
   {some data>
   }' \
     https://foo  2>&1 |grep  -w '^boo:'    }
</code>```

I receive

```<code>boo: foo
</code>```

I only want the foo string without whitespace

Body:
   curl -i -v --silent \
     -H "Content-Type: application/json" \
     -d '
   {some data>
   }' \
     https://foo  2>&1 |grep  -w '^boo:'    }

I receive

boo: foo

I only want the foo string without whitespace

Body: 2>&1 | grep  -w '^boo:' | awk -F' ' '{print $2}'


问:
How can update the badge number on app icon of Motorola and google nexus devices in android?
Want to update the badge count in android app icon, we successfully updated on the Samsung, LG Sony etc devices, but can't update the badge on Motorola and Google nexus device. Can you please suggests any solution for the same?

答:
I know that this question is from 7 months ago, but anyway: recently, I was searching about badges in Android Apps, and I found that you are not able do it in Stock devices (like Motorola and Nexus devices).

Take a look at this link.