问:
Why do I have to stage a file in order to make git realise that a conflict has been resolved?
Problem: I change multiple lines, and stage + commit all but one of them, then I want to push the commit. However, before I push them I want to merge from another branch to see if there's a conflict to be resolved as well.

Uh-oh, a conflict! I fix it, but in order to make git agree that it's fixed, I have to stage the entire file. Noooo, I want to keep that single line unstaged. Staging the entire file will bury that line among 1000 lines of conflict-resolved changes (so finding it and unstaging it will take days ;-).

Why can't I just tell git "listen, relax, forget it, it's not a problem anymore, I want to just leave things as they are now - when I'm done with the final fix to that single line I promise I'll stage everything (eventually;-) and commit it".

Am I missing something? Is there a simple workflow that'll get around this issue?

Cheers,
Stein

答:
The reason you have to git add to resolve the conflict is that the conflict is actually stored in the index, which is the same place that git add updates.  And, unfortunately, this storage disrupts the carefully tweaked version you stored earlier.

Description

Fundamentally, Git stores every file having to do with the current-and-next commits in three places, not just two.

There is a copy of every file, stored in Git's special Gitty format (compressed etc), permanently and read-only, as part of the HEAD commit.  That is, if .git/HEAD contains ref: refs/heads/branchX so that you are on branch branchX, and branchX means "commit 1234567...", then the commit whose hash ID is 1234567... contains a complete snapshot of your source tree.  (No big deal so far, nothing surprising here.)

There's also a copy of every file, stored in plain format—not some special Gitty variety—so that you can edit and compile and run programs and so on, in your work-tree.  (Nothing surprising here either.)

But in between, there is a third copy of every file.  That third copy is normally, and initially, the same as the HEAD commit copy.  (In fact, it's in the special Gitty format, which replaces the actual files with a hash ID.  Plus, that hash ID is kept in an ordinary data file, .git/index, along with some cache information, so it hardly takes any extra space at all:

```<code>$ ls -l .git/index
...  300971 Dec  6 20:23 .git/index
</code>```

for an index of the Git tree for Git, for instance.)

When you run git add on a file, what you're really doing is copying it back into the index.  When you run git add <file>, Git turns <file> into the special Gitty format—this is when it actually goes into the repository!—and shoves the resulting hash into the index.  If you git add -p <file> and stage most but not all of it, the most-but-not-all version is what's now stored in the index.

Whatever is in the index, is what Git will snapshot into the next commit.  The new commit will then take over as "the current commit", so that HEAD—i.e., branchX—will now mean, say, "commit fedcba9...", which will be permanent and read-only and contain the final snapshot of your file.  (Meanwhile the hash 1234567... is now remembered via the fact that it's the parent hash stored in fedcba9....)

In other words, after committing, the index matches the HEAD commit again, because the HEAD commit was made from the index.  Everything is still there in slot zero, undisturbed.

How git merge wrecks this

Each of these index entries is a stage zero entry.  Stage zero is the normal stage, for a unconflicted entry.  But each index entry actually has up to four slots.  You can either have something in stage 0, or—by removing the stage zero entry—you can have something in slots 1, 2, and/or 3.  When git merge discovers that it has to merge a file, it does just that: it wipes out the stage zero entry, copies the merge base version to stage#1, copies the HEAD or --ours version to stage#2, and copies the remaining --theirs version to stage#3.

Git leaves it up to the low level file merge handler to resolve the conflicts, if it can (and if you use -X ours or -X theirs, it always can).  If the low level driver does resolve the conflicts, that driver will git add the work-tree copy for you.  If not, it leaves the conflicts in the work-tree file, and leaves the three nonzero-stage entries in place.

When you git add the final version, you tell Git: Remove stages 1 through 3, and put whatever's in the work-tree in as stage 0.  (This remains true even with git add -p.)

Until you do this, git commit cannot commit, because it can only commit entries that are stored in the stage-zero slot.

Body:
The reason you have to git add to resolve the conflict is that the conflict is actually stored in the index, which is the same place that git add updates.  And, unfortunately, this storage disrupts the carefully tweaked version you stored earlier.

Description

Fundamentally, Git stores every file having to do with the current-and-next commits in three places, not just two.

There is a copy of every file, stored in Git's special Gitty format (compressed etc), permanently and read-only, as part of the HEAD commit.  That is, if .git/HEAD contains ref: refs/heads/branchX so that you are on branch branchX, and branchX means "commit 1234567...", then the commit whose hash ID is 1234567... contains a complete snapshot of your source tree.  (No big deal so far, nothing surprising here.)

There's also a copy of every file, stored in plain format—not some special Gitty variety—so that you can edit and compile and run programs and so on, in your work-tree.  (Nothing surprising here either.)

But in between, there is a third copy of every file.  That third copy is normally, and initially, the same as the HEAD commit copy.  (In fact, it's in the special Gitty format, which replaces the actual files with a hash ID.  Plus, that hash ID is kept in an ordinary data file, .git/index, along with some cache information, so it hardly takes any extra space at all:

$ ls -l .git/index
...  300971 Dec  6 20:23 .git/index

for an index of the Git tree for Git, for instance.)

When you run git add on a file, what you're really doing is copying it back into the index.  When you run git add <file>, Git turns <file> into the special Gitty format—this is when it actually goes into the repository!—and shoves the resulting hash into the index.  If you git add -p <file> and stage most but not all of it, the most-but-not-all version is what's now stored in the index.

Whatever is in the index, is what Git will snapshot into the next commit.  The new commit will then take over as "the current commit", so that HEAD—i.e., branchX—will now mean, say, "commit fedcba9...", which will be permanent and read-only and contain the final snapshot of your file.  (Meanwhile the hash 1234567... is now remembered via the fact that it's the parent hash stored in fedcba9....)

In other words, after committing, the index matches the HEAD commit again, because the HEAD commit was made from the index.  Everything is still there in slot zero, undisturbed.

How git merge wrecks this

Each of these index entries is a stage zero entry.  Stage zero is the normal stage, for a unconflicted entry.  But each index entry actually has up to four slots.  You can either have something in stage 0, or—by removing the stage zero entry—you can have something in slots 1, 2, and/or 3.  When git merge discovers that it has to merge a file, it does just that: it wipes out the stage zero entry, copies the merge base version to stage#1, copies the HEAD or --ours version to stage#2, and copies the remaining --theirs version to stage#3.

Git leaves it up to the low level file merge handler to resolve the conflicts, if it can (and if you use -X ours or -X theirs, it always can).  If the low level driver does resolve the conflicts, that driver will git add the work-tree copy for you.  If not, it leaves the conflicts in the work-tree file, and leaves the three nonzero-stage entries in place.

When you git add the final version, you tell Git: Remove stages 1 through 3, and put whatever's in the work-tree in as stage 0.  (This remains true even with git add -p.)

Until you do this, git commit cannot commit, because it can only commit entries that are stored in the stage-zero slot.


来源: stackexchange

问:
RecyclerView duplicating certain UI elements
I'm trying to implement a dynamic view inside of a RecyclerView and I'm having issues with certain controls being duplicated.

Here is my RecyclerView.ViewHolder

```<code>class CardHolder extends RecyclerView.ViewHolder{
    private ICard card;
    private TextView cost;
    private ImageView quickAction;
    private TextView range;
    private TextView life;
    private TextView defense;
    private TextView spellName;
    private ImageView addCard;
    private TextView maximumCards;
    private ImageView removeCard;
    private ImageView cardImage;
    private LinearLayout cardImageRow;
    private LinearLayout traitsRow;
    private TextView effects;
    private LinearLayout attackColumn;

    public CardHolder(View itemView) {
        super(itemView);

        cost = (TextView)itemView.findViewById(R.id.card_cost);
        quickAction = (ImageView)itemView.findViewById(R.id.quickAction);
        range = (TextView)itemView.findViewById(R.id.range);
        life = (TextView)itemView.findViewById(R.id.life);
        defense = (TextView)itemView.findViewById(R.id.defense);
        spellName = (TextView)itemView.findViewById(R.id.spellName);
        addCard = (ImageView)itemView.findViewById(R.id.addCard);
        addCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        maximumCards = (TextView)itemView.findViewById(R.id.maximumCards);
        removeCard = (ImageView)itemView.findViewById(R.id.removeCard);
        removeCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        cardImage = (ImageView)itemView.findViewById(R.id.cardImage);
        cardImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        cardImageRow = (LinearLayout)itemView.findViewById(R.id.cardImageRow);
        traitsRow = (LinearLayout)itemView.findViewById(R.id.traitsRow);
        effects = (TextView)itemView.findViewById(R.id.effects);
        attackColumn = (LinearLayout)itemView.findViewById(R.id.attackColumn);
    }

    public void setCard(Card card){
        this.card = card;

        cost.setText(card.getCost() + "");
        quickAction.setImageResource(card.isQuickAction() ? R.drawable.quickaction : R.drawable.fullaction);
        range.setText(card.getMinRange() + "-" + card.getMaxRange());
        spellName.setText(card.getSpellName());
        cardImage.setImageResource(card.getCardImageResourceId());
        effects.setText(card.getEffect());

        if(card instanceof AttackCard){
            AttackCard c = (AttackCard)card;
            handleAttack(c.getAttack());
        }

        if(card.getTrait() != null){
            boolean isFirst = true;
            StringBuilder builder = new StringBuilder();
            for(int i = 0; i < card.getTrait().getAll().size(); i++){
                if(isFirst){
                    builder.append(card.getTrait().get(i).getType().toString());
                    isFirst = false;
                }
                else{
                    builder.append(" \u2022 ");
                    builder.append(card.getTrait().get(i).getType().toString());
                }
            }

            TextView t = new TextView(getActivity());
            t.setText(builder.toString());
            t.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
            t.setTextColor(Color.BLACK);
            t.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            t.setTypeface(Typeface.DEFAULT_BOLD);
            traitsRow.addView(t);

        }
    }
    private void handleAttack(ICardProperty<IAttack> attack){
        if(attack == null){
            return;
        }

        for(int i = 0; i < attack.getAll().size(); i++) {

            IAttack a = attack.get(i);

            //Layout for entire Attack
            RelativeLayout layout = new RelativeLayout(getActivity());
            //layout.setId(Utils.generateViewId());
            layout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));

            //Attack name
            TextView attackName = new TextView(getActivity());
            attackName.setId(Utils.generateViewId());
            attackName.setText(a.getName());
            attackName.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            attackName.setTextColor(Color.BLACK);
            attackName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
            layout.addView(attackName);

            //Quick action or Full action
            ImageView quickAction = new ImageView(getActivity());
            quickAction.setId(Utils.generateViewId());
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(R.dimen.card_header_width,R.dimen.card_header_height);
            lp.addRule(RelativeLayout.BELOW,attackName.getId());
            lp.addRule(RelativeLayout.CENTER_VERTICAL);
            quickAction.setLayoutParams(lp);
            quickAction.setImageResource(a.isQuickAction() ? R.drawable.quickaction : R.drawable.fullaction);
            layout.addView(quickAction);

            //Attack type (Melee or Ranged)
            TextView attackType = new TextView(getActivity());
            attackType.setId(Utils.generateViewId());
            attackType.setGravity(Gravity.CENTER);

            RelativeLayout.LayoutParams p1 = new RelativeLayout.LayoutParams(R.dimen.attack_width,R.dimen.attack_height);
            p1.addRule(RelativeLayout.RIGHT_OF,quickAction.getId());
            p1.addRule(RelativeLayout.BELOW,attackName.getId());
            p1.setMargins(2,0,2,0);

            if(a.getAttackType() == IAttack.AttackType.Melee){
                attackType.setBackgroundResource(R.drawable.melee);
            }
            else if(a.getAttackType() == IAttack.AttackType.Ranged){
                attackType.setBackgroundResource(R.drawable.range);
                attackType.setText(a.getMinRange() + "-" + a.getMaxRange());
                attackType.setTextColor(Color.WHITE);
                attackType.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                attackType.setTypeface(Typeface.DEFAULT_BOLD);
            }

            layout.addView(attackType);
            attackColumn.addView(layout);
        }
    }

}
</code>```

Here is my adapter

```<code>public class CardAdapter extends RecyclerView.Adapter<CardHolder> {
    private ArrayList<ICard> cards;

    public CardAdapter(ArrayList<ICard> cards){
        super();
        this.cards = cards;
    }
    @Override
    public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_card_row, parent, false);
        return new CardHolder(itemView);
    }

    @Override
    public void onBindViewHolder(CardHolder holder, int position) {
        ICard card = cards.get(position);
        holder.setCard((Card)card);
    }

    @Override
    public int getItemCount() {
        return cards.size();
    }
}
</code>```

In the setCard method I'm interrogating the Card object and adding various UI elements accordingly. It seems to work fine for a short period of time but it quickly becomes apparent that UI elements that are dynamically added are duplicating themselves. As you scroll up and down there will be more and more of them.

Am I doing something wrong by dynamically adding UI code in the onBindViewHolder of the adapter? If so what would be the correct way to go about what I'm trying to do?

答: Simply remove all views from your parent on   onBindViewHolder().</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to implement a dynamic view inside of a RecyclerView and I'm having issues with certain controls being duplicated.

Here is my RecyclerView.ViewHolder

class CardHolder extends RecyclerView.ViewHolder{
    private ICard card;
    private TextView cost;
    private ImageView quickAction;
    private TextView range;
    private TextView life;
    private TextView defense;
    private TextView spellName;
    private ImageView addCard;
    private TextView maximumCards;
    private ImageView removeCard;
    private ImageView cardImage;
    private LinearLayout cardImageRow;
    private LinearLayout traitsRow;
    private TextView effects;
    private LinearLayout attackColumn;

    public CardHolder(View itemView) {
        super(itemView);

        cost = (TextView)itemView.findViewById(R.id.card_cost);
        quickAction = (ImageView)itemView.findViewById(R.id.quickAction);
        range = (TextView)itemView.findViewById(R.id.range);
        life = (TextView)itemView.findViewById(R.id.life);
        defense = (TextView)itemView.findViewById(R.id.defense);
        spellName = (TextView)itemView.findViewById(R.id.spellName);
        addCard = (ImageView)itemView.findViewById(R.id.addCard);
        addCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        maximumCards = (TextView)itemView.findViewById(R.id.maximumCards);
        removeCard = (ImageView)itemView.findViewById(R.id.removeCard);
        removeCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        cardImage = (ImageView)itemView.findViewById(R.id.cardImage);
        cardImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        cardImageRow = (LinearLayout)itemView.findViewById(R.id.cardImageRow);
        traitsRow = (LinearLayout)itemView.findViewById(R.id.traitsRow);
        effects = (TextView)itemView.findViewById(R.id.effects);
        attackColumn = (LinearLayout)itemView.findViewById(R.id.attackColumn);
    }

    public void setCard(Card card){
        this.card = card;

        cost.setText(card.getCost() + "");
        quickAction.setImageResource(card.isQuickAction() ? R.drawable.quickaction : R.drawable.fullaction);
        range.setText(card.getMinRange() + "-" + card.getMaxRange());
        spellName.setText(card.getSpellName());
        cardImage.setImageResource(card.getCardImageResourceId());
        effects.setText(card.getEffect());

        if(card instanceof AttackCard){
            AttackCard c = (AttackCard)card;
            handleAttack(c.getAttack());
        }

        if(card.getTrait() != null){
            boolean isFirst = true;
            StringBuilder builder = new StringBuilder();
            for(int i = 0; i < card.getTrait().getAll().size(); i++){
                if(isFirst){
                    builder.append(card.getTrait().get(i).getType().toString());
                    isFirst = false;
                }
                else{
                    builder.append(" \u2022 ");
                    builder.append(card.getTrait().get(i).getType().toString());
                }
            }

            TextView t = new TextView(getActivity());
            t.setText(builder.toString());
            t.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
            t.setTextColor(Color.BLACK);
            t.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            t.setTypeface(Typeface.DEFAULT_BOLD);
            traitsRow.addView(t);

        }
    }
    private void handleAttack(ICardProperty<IAttack> attack){
        if(attack == null){
            return;
        }

        for(int i = 0; i < attack.getAll().size(); i++) {

            IAttack a = attack.get(i);

            //Layout for entire Attack
            RelativeLayout layout = new RelativeLayout(getActivity());
            //layout.setId(Utils.generateViewId());
            layout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));

            //Attack name
            TextView attackName = new TextView(getActivity());
            attackName.setId(Utils.generateViewId());
            attackName.setText(a.getName());
            attackName.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            attackName.setTextColor(Color.BLACK);
            attackName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
            layout.addView(attackName);

            //Quick action or Full action
            ImageView quickAction = new ImageView(getActivity());
            quickAction.setId(Utils.generateViewId());
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(R.dimen.card_header_width,R.dimen.card_header_height);
            lp.addRule(RelativeLayout.BELOW,attackName.getId());
            lp.addRule(RelativeLayout.CENTER_VERTICAL);
            quickAction.setLayoutParams(lp);
            quickAction.setImageResource(a.isQuickAction() ? R.drawable.quickaction : R.drawable.fullaction);
            layout.addView(quickAction);

            //Attack type (Melee or Ranged)
            TextView attackType = new TextView(getActivity());
            attackType.setId(Utils.generateViewId());
            attackType.setGravity(Gravity.CENTER);

            RelativeLayout.LayoutParams p1 = new RelativeLayout.LayoutParams(R.dimen.attack_width,R.dimen.attack_height);
            p1.addRule(RelativeLayout.RIGHT_OF,quickAction.getId());
            p1.addRule(RelativeLayout.BELOW,attackName.getId());
            p1.setMargins(2,0,2,0);

            if(a.getAttackType() == IAttack.AttackType.Melee){
                attackType.setBackgroundResource(R.drawable.melee);
            }
            else if(a.getAttackType() == IAttack.AttackType.Ranged){
                attackType.setBackgroundResource(R.drawable.range);
                attackType.setText(a.getMinRange() + "-" + a.getMaxRange());
                attackType.setTextColor(Color.WHITE);
                attackType.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                attackType.setTypeface(Typeface.DEFAULT_BOLD);
            }

            layout.addView(attackType);
            attackColumn.addView(layout);
        }
    }

}

Here is my adapter

public class CardAdapter extends RecyclerView.Adapter<CardHolder> {
    private ArrayList<ICard> cards;

    public CardAdapter(ArrayList<ICard> cards){
        super();
        this.cards = cards;
    }
    @Override
    public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_card_row, parent, false);
        return new CardHolder(itemView);
    }

    @Override
    public void onBindViewHolder(CardHolder holder, int position) {
        ICard card = cards.get(position);
        holder.setCard((Card)card);
    }

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

In the setCard method I'm interrogating the Card object and adding various UI elements accordingly. It seems to work fine for a short period of time but it quickly becomes apparent that UI elements that are dynamically added are duplicating themselves. As you scroll up and down there will be more and more of them.

Am I doing something wrong by dynamically adding UI code in the onBindViewHolder of the adapter? If so what would be the correct way to go about what I'm trying to do?


问:
Setting onSeekBarChangeListener causes null object exception
I'm trying to update a textview with the value of a seekbar, and I'm having trouble setting an OnSeekBarChangeListener. I don't have any compile errors, but every time I try to run the app, I get a null pointer exception.

The error says:

Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference

I can't for the life of me figure out why, despite trawling through StackOverflow. Every similar problem, or tutorial on how to set an OnSeekBarChangeListener seems to suggest I do exactly what I've done. Help!

```<code>    public class MainActivity extends AppCompatActivity {
public TextView time;
public SeekBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    time = (TextView) findViewById(R.id.time);
    bar = (SeekBar) findViewById(R.id.bar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bar.setOnSeekBarChangeListener(listener);

}

private SeekBar.OnSeekBarChangeListener listener = new OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        time.setText((String.valueOf(progress/100) + ":" + String.valueOf(progress % 100)));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
};}
</code>```

答:
This error occur too when you call  an wrong  activity or when you call the correct activity and call another wrong activity that do not have the component you want, example

```<code>setContentView(R.layout.correct_activity_with_your_component);
some code....    setContentView(R.layout.wrong_activity_without_your_component_bar_activity_main);
bar = (SeekBar) findViewById(R.id.bar);
</code>```

So one solution is write the line similar to
    setContentView(R.layout.correct_activity_with_your_component);
before your componenet and verify if there is not another command
similar to

```<code>setContentView(R.layout.correct_activity_with_your_component);
</code>```

before you call your component with:

```<code>bar = (SeekBar) findViewById(R.id.bar);
</code>```

Body:
I'm trying to update a textview with the value of a seekbar, and I'm having trouble setting an OnSeekBarChangeListener. I don't have any compile errors, but every time I try to run the app, I get a null pointer exception.

The error says:

Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference

I can't for the life of me figure out why, despite trawling through StackOverflow. Every similar problem, or tutorial on how to set an OnSeekBarChangeListener seems to suggest I do exactly what I've done. Help!

    public class MainActivity extends AppCompatActivity {
public TextView time;
public SeekBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    time = (TextView) findViewById(R.id.time);
    bar = (SeekBar) findViewById(R.id.bar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bar.setOnSeekBarChangeListener(listener);

}

private SeekBar.OnSeekBarChangeListener listener = new OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        time.setText((String.valueOf(progress/100) + ":" + String.valueOf(progress % 100)));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
};}

Body:
This error occur too when you call  an wrong  activity or when you call the correct activity and call another wrong activity that do not have the component you want, example

setContentView(R.layout.correct_activity_with_your_component);
some code....    setContentView(R.layout.wrong_activity_without_your_component_bar_activity_main);
bar = (SeekBar) findViewById(R.id.bar);

So one solution is write the line similar to
    setContentView(R.layout.correct_activity_with_your_component);
before your componenet and verify if there is not another command
similar to

setContentView(R.layout.correct_activity_with_your_component);

before you call your component with:

bar = (SeekBar) findViewById(R.id.bar);


问:
How do I fix this simple CSS floating issue in IE?
I've got four div elements floated to the left. The third div is cleared.

In Firefox and Chrome the elements are positioned as expected: The first and second divs are adjacent to each other and are above the third and fourth divs which are also adjacent to each other.

IE7 on the other hand places the fourth div adjacent to the first and second divs with the third div below.

I know I can fix it by adding a br element after the second div but I'd rather not edit the markup if I don't have to. Is there a more elegant way of fixing the problem?

I've been trying to Google for a fix for a while now but haven't found one, which is rather surprising considering how elementary the problem seems. Perhaps I'm missing something obvious, is there a reference site that lists simple CSS issues like this one or am I just ignorant about basic CSS?

Edit: I've made the sample code slightly more complex after Nazgulled "solved" the problem (see the comments). There are now four divs instead of three and the third div is cleared instead of the second.

Here is the complete source code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>IE Float Test</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <style type="text/css">
            div
            {
                width: 100px;
                height: 100px;
                color: white;
                font-size: 3em;
                float: left;
            }

            #divone
            {
                background-color: red;
            }

            #divtwo
            {
                background-color: blue;
            }

            #divthree
            {
                background-color: green;
                clear: both;
            }

            #divfour
            {
                background-color: purple;
            }
        </style>
    </head>
    <body>
        <div id="divone">one</div>
        <div id="divtwo">two</div>
        <div id="divthree">three</div>
        <div id="divfour">four</div>
    </body>
</html>
</code>```

Here is what is looks like in Chrome:

Here is what is looks like in IE7:

答:
I don't know if this fixes your real problem, but I fixed your sample like this:

Remove the float attribute from div

Remove the clear attribute from #divtwo

Add float: left to #divtwo and #divthree

This makes it look like your chrome sample both in Firefox and IE 7 (browsers I tested).

OwnerDisplayName: brianpeiris

ContentLicense: CC BY-SA 4.0

Body:
I've got four div elements floated to the left. The third div is cleared.

In Firefox and Chrome the elements are positioned as expected: The first and second divs are adjacent to each other and are above the third and fourth divs which are also adjacent to each other.

IE7 on the other hand places the fourth div adjacent to the first and second divs with the third div below.

I know I can fix it by adding a br element after the second div but I'd rather not edit the markup if I don't have to. Is there a more elegant way of fixing the problem?

I've been trying to Google for a fix for a while now but haven't found one, which is rather surprising considering how elementary the problem seems. Perhaps I'm missing something obvious, is there a reference site that lists simple CSS issues like this one or am I just ignorant about basic CSS?

Edit: I've made the sample code slightly more complex after Nazgulled "solved" the problem (see the comments). There are now four divs instead of three and the third div is cleared instead of the second.

Here is the complete source code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>IE Float Test</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

one

two

three

four

Here is what is looks like in Chrome:

Here is what is looks like in IE7:

LastEditorDisplayName: brianpeiris

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5


问:
Conf files and static files in a deb package
I'm using dh_help to build a package template and trying to follow the ubuntu and debian packaging guides for creating a binary package.

How do I tell debuild which file is a conf file and should go for example to /etc/mypkg.conf ?
I've tried to put it under mypkg-0.1/etc/mypkg/fname.conf but debuild ignores it.
The debian guide says all files under etc/ are treated automatically as conf files but it doesn't work for me (http://www.debian.org/doc/maint-guid...ml#s-conffiles).
I've tried putting the conf file under mypkg-1.0/etc/mypkg.conf and under mypkg-1.0/debain/etc/mypkg.conf but it is not included. I also tried to list the file in conffiles but I'm getting an error that it can't be found when building the package.

I also don't understand how to include static files in the package.
Do I have to use the install file to list all the files and folders?
I thought that putting everything with the full path under the mypkgs-0.1 folder should work like it does when using dpkg manually.

Thanks

答:
As viraptor said you can put an install command for each file into your debian/rules to install the files into the debian/pkgname directory.

Or you can use a debian/install file to simply list all the files (or just directories) and have a dh_install command in your debian/rules to do it for you.

It seems you are a little confused about how packages are built and which files are included. This is extremely generalized, but when the debian/rules script compiles a program using standard ./configure && make && make install method, it instructs the make install to install the files to debian/pkgname instead of /. Then it knows that everything under debian/pkgname is what should be in the final .deb. If the make install step doesn't put everything in the correct location, then the debian/rules script needs to do that. Previously it seems calling install ... from debian/rules to copy the files to the debian/pkgname directory was common but now using a debian/install file seems to be the preferred method.


问:
How do I get WordPress posts from a specific date?
I am unable to figure out how to retrieve WordPress posts from a specific date to the present date.

The following is the URL for getting all posts:

```<code>[<Literal>]
let private APIBaseAddress =   "https://public-api.wordpress.com/"

[<Literal>]
let private ArticlesUrl =      "rest/v1/sites/{0}/posts?number=100&page={1}"
</code>```

答:
A list of all of the parameters can be found here.

Add the after parameter.

```<code>let private ArticlesUrl = "rest/v1/sites/{0}/posts?number=100&page={1}&after=yyyymmdd"
</code>```

Body:
I am unable to figure out how to retrieve WordPress posts from a specific date to the present date.

The following is the URL for getting all posts:

[<Literal>]
let private APIBaseAddress =   "https://public-api.wordpress.com/"

[<Literal>]
let private ArticlesUrl =      "rest/v1/sites/{0}/posts?number=100&page={1}"

Body:
A list of all of the parameters can be found here.

Add the after parameter.

let private ArticlesUrl = "rest/v1/sites/{0}/posts?number=100&page={1}&after=yyyymmdd"


问:
Multiple different conditions and if statments within a loop
I want to assign different letters from A:U to a new column vector according to some conditions that depend on a different column that takes the numbers 1:99.

I came up with the following solution, but I want to write it more efficiently.

```<code>for (i in 1:99){

  if (i %in% 1:3 == T  ){
    id<-which(H07_NACE$NACE2.Code==i)
    H07_NACE$NACE2.Sectors[id]<-"A"
  }

   .............

    if (i %in% 45:60 == T  ){
      id<-which(H07_NACE$NACE2.Code==i)
      H07_NACE$NACE2.Sectors[id]<-"D"
    }
      .....................

     if (i == 99  ){
id<-which(H07_NACE$NACE2.Code==i)
H07_NACE$NACE2.Sectors[id]<-"U"
  }

}
</code>```

In the previous code I skipped multiple other line which essentially do the same thing. Notice that conditions changing all the time within this loop that I created and are of two types. One is for example of the type i %in% 45:60 == T and the other of the type 'i == 99 '

My original code has multiple such ifs within this loop so any help on how I can write it more efficiently or compactly will be appreciated.

答:
Here is a quick and dirty solution that should do the job (I'm sure there is more efficient/elegant way to do this). We can setup a constraint vector and use indexing from there to produce the desired results.

```<code>## Here is some random data that resembles the OP's
set.seed(3)
H07_NACE <- data.frame(NACE2.Code = sample(99, replace = TRUE))

## "T" is the 20th element... we need to gurantee
## that the number corresponding to "U"
## corresponds to max(NACE2.Code)
maxCode <- max(H07_NACE$NACE2.Code)
constraintVec <- sort(sample(maxCode - 1, 20))
constraintVec <- c(constraintVec, maxCode)

H07_NACE$NACE2.Sector <- LETTERS[vapply(H07_NACE$NACE2.Code, function(x) {
                                            which(constraintVec >= x)[1]
                                    }, 1L)]

## Add optional check column to ensure we are mapping the
## Code to the correct Sector
H07_NACE$NACE2.Check <- constraintVec[vapply(H07_NACE$NACE2.Code, function(x) {
    which(constraintVec >= x)[1]
}, 1L)]

head(H07_NACE)
  NACE2.Code NACE2.Sector NACE2.Check
1         17            E          18
2         80            R          85
3         39            K          54
4         33            J          37
5         60            N          66
6         60            N          66
</code>```

Update courtesy of @Frank

As suspected, there is a much simpler solution assuming the above logic is correct.  We use findInterval and set the arguments rightmost.closed and left.open to TRUE (we also have to add 1L to the resulting vector):

```<code>H07_NACE$NACE2.Sector2 <- LETTERS[findInterval(H07_NACE$NACE2.Code, constraintVec,
                                    rightmost.closed = TRUE, , left.open = TRUE) + 1L]

head(H07_NACE)
  NACE2.Code NACE2.Sector NACE2.Check NACE2.Sector2
1         17            E          18             E
2         80            R          85             R
3         39            K          54             K
4         33            J          37             J
5         60            N          66             N
6         60            N          66             N

identical(H07_NACE$NACE2.Sector, H07_NACE$NACE2.Sector2)
[1] TRUE
</code>```

Body:
I want to assign different letters from A:U to a new column vector according to some conditions that depend on a different column that takes the numbers 1:99.

I came up with the following solution, but I want to write it more efficiently.

for (i in 1:99){

  if (i %in% 1:3 == T  ){
    id<-which(H07_NACE$NACE2.Code==i)
    H07_NACE$NACE2.Sectors[id]<-"A"
  }

   .............

    if (i %in% 45:60 == T  ){
      id<-which(H07_NACE$NACE2.Code==i)
      H07_NACE$NACE2.Sectors[id]<-"D"
    }
      .....................

     if (i == 99  ){
id<-which(H07_NACE$NACE2.Code==i)
H07_NACE$NACE2.Sectors[id]<-"U"
  }

}

In the previous code I skipped multiple other line which essentially do the same thing. Notice that conditions changing all the time within this loop that I created and are of two types. One is for example of the type i %in% 45:60 == T and the other of the type 'i == 99 '

My original code has multiple such ifs within this loop so any help on how I can write it more efficiently or compactly will be appreciated.

Body:
Here is a quick and dirty solution that should do the job (I'm sure there is more efficient/elegant way to do this). We can setup a constraint vector and use indexing from there to produce the desired results.

## Here is some random data that resembles the OP's
set.seed(3)
H07_NACE <- data.frame(NACE2.Code = sample(99, replace = TRUE))

## "T" is the 20th element... we need to gurantee
## that the number corresponding to "U"
## corresponds to max(NACE2.Code)
maxCode <- max(H07_NACE$NACE2.Code)
constraintVec <- sort(sample(maxCode - 1, 20))
constraintVec <- c(constraintVec, maxCode)

H07_NACE$NACE2.Sector <- LETTERS[vapply(H07_NACE$NACE2.Code, function(x) {
                                            which(constraintVec >= x)[1]
                                    }, 1L)]

## Add optional check column to ensure we are mapping the
## Code to the correct Sector
H07_NACE$NACE2.Check <- constraintVec[vapply(H07_NACE$NACE2.Code, function(x) {
    which(constraintVec >= x)[1]
}, 1L)]

head(H07_NACE)
  NACE2.Code NACE2.Sector NACE2.Check
1         17            E          18
2         80            R          85
3         39            K          54
4         33            J          37
5         60            N          66
6         60            N          66

Update courtesy of @Frank

As suspected, there is a much simpler solution assuming the above logic is correct.  We use findInterval and set the arguments rightmost.closed and left.open to TRUE (we also have to add 1L to the resulting vector):

H07_NACE$NACE2.Sector2 <- LETTERS[findInterval(H07_NACE$NACE2.Code, constraintVec,
                                    rightmost.closed = TRUE, , left.open = TRUE) + 1L]

head(H07_NACE)
  NACE2.Code NACE2.Sector NACE2.Check NACE2.Sector2
1         17            E          18             E
2         80            R          85             R
3         39            K          54             K
4         33            J          37             J
5         60            N          66             N
6         60            N          66             N

identical(H07_NACE$NACE2.Sector, H07_NACE$NACE2.Sector2)
[1] TRUE


问:
Correlate start/stop dates and sum their duration
UPDATE: At the bottom I added expected output with the table I had envisioned

My goal is two correlate downtime events to show causation of one event and the downtime it caused.

I have an overall schema of:

```<code>DECLARE @EquipmentDownTime TABLE
(
ID INT IDENTITY(1,1),
Equipment varchar(5),
Time DATETIME,
StartStop NVARCHAR(15)
)
</code>```

so a record looks like this:

```<code> 1, Motor, '18/8/2017 12:00:00', Stop
 2, Motor, '18/8/2017 12:10:00', Start
</code>```

I'm currently using a matching pairs table function to sum the total duration of downtime between user entered date ranged but I want to expand the functionality to say how long an event caused another based on those durations.

What I'm trying to do is correlate when another piece of equipment "Stop" is in between the record above and then determine it's total time of being. Using the Sample data below:

```<code>INSERT INTO @EquipmentDownTime (Equipment, [Time], StartStop)
VALUES
  ('Motor', '20170812 12:00:00', 'Stop'), --ID 1
  ('Valve', '20170812 12:05:00', 'Stop'), --ID 2
  ('Motor', '20170812 12:30:00', 'Start'), --ID 3
  ('Valve', '20170812 13:05:00', 'Start'), --ID 4
  ('Motor', '20170812 14:00:00', 'Stop'), --ID 5
  ('Valve', '20170812 14:05:00', 'Stop'), --ID 6
  ('Motor', '20170812 15:30:00', 'Start'), --ID 7
  ('Valve', '20170812 15:05:00', 'Start'); --ID 8
</code>```

In this case I would say ID 1 Caused 1 hour of downtime for ID 2 since it's stop fell in between 1 and 3 which are a Stop/Start Pair.

I imagine the end result would look something like this:

```<code> DECLARE @Causation TABLE
(
ID INT                     IDENTITY(1,1),
CauationEquipment          varchar(5),
CauationEquipmentShutdown  DATETIME,
AffectedEquipment          varchar(5),
AffectedEquipmentShutdown  DATETIME,
DurationOfAffectedEquip    INT
)
</code>```

Records Result (Causation Id and Affected, comes from Identity Id in @EquipmentDowntime Table):

```<code> 1, Motor, '20170812 12:00:00', Valve, '20170812 12:05:00', 60
 2, Motor, '20170812 14:00:00', Valve, '20170812 14:05:00', 60
</code>```

The piece I am missing here is effectively linking the correlation I have thought to use a while loop going through all the downtime events and grab the stop and its next start and store it in temp tables but it is getting messy.

SQL Server 2014

答:
Assuming you're on SQL Server 2012+, and that a single Downtime will only have 2 entries (one for the stop and one for the start):</p>

```<code>WITH Downtime AS (
    SELECT *,
           LEAD([Time]) OVER (PARTITION BY Equipment ORDER BY [Time] ASC) AS NextStatus
    FROM @EquipmentDownTime)
SELECT ID,
       Equipment,
       DATEDIFF(MINUTE,[Time],NextStatus) AS Duration
FROM Downtime
WHERE StartStop = 'Stop';
</code>```

Body:
UPDATE: At the bottom I added expected output with the table I had envisioned

My goal is two correlate downtime events to show causation of one event and the downtime it caused.

I have an overall schema of:

DECLARE @EquipmentDownTime TABLE
(
ID INT IDENTITY(1,1),
Equipment varchar(5),
Time DATETIME,
StartStop NVARCHAR(15)
)

so a record looks like this:

 1, Motor, '18/8/2017 12:00:00', Stop
 2, Motor, '18/8/2017 12:10:00', Start

I'm currently using a matching pairs table function to sum the total duration of downtime between user entered date ranged but I want to expand the functionality to say how long an event caused another based on those durations.

What I'm trying to do is correlate when another piece of equipment "Stop" is in between the record above and then determine it's total time of being. Using the Sample data below:

INSERT INTO @EquipmentDownTime (Equipment, [Time], StartStop)
VALUES
  ('Motor', '20170812 12:00:00', 'Stop'), --ID 1
  ('Valve', '20170812 12:05:00', 'Stop'), --ID 2
  ('Motor', '20170812 12:30:00', 'Start'), --ID 3
  ('Valve', '20170812 13:05:00', 'Start'), --ID 4
  ('Motor', '20170812 14:00:00', 'Stop'), --ID 5
  ('Valve', '20170812 14:05:00', 'Stop'), --ID 6
  ('Motor', '20170812 15:30:00', 'Start'), --ID 7
  ('Valve', '20170812 15:05:00', 'Start'); --ID 8

In this case I would say ID 1 Caused 1 hour of downtime for ID 2 since it's stop fell in between 1 and 3 which are a Stop/Start Pair.

I imagine the end result would look something like this:

 DECLARE @Causation TABLE
(
ID INT                     IDENTITY(1,1),
CauationEquipment          varchar(5),
CauationEquipmentShutdown  DATETIME,
AffectedEquipment          varchar(5),
AffectedEquipmentShutdown  DATETIME,
DurationOfAffectedEquip    INT
)

Records Result (Causation Id and Affected, comes from Identity Id in @EquipmentDowntime Table):

 1, Motor, '20170812 12:00:00', Valve, '20170812 12:05:00', 60
 2, Motor, '20170812 14:00:00', Valve, '20170812 14:05:00', 60

The piece I am missing here is effectively linking the correlation I have thought to use a while loop going through all the downtime events and grab the stop and its next start and store it in temp tables but it is getting messy.

SQL Server 2014

Body:
Assuming you're on SQL Server 2012+, and that a single Downtime will only have 2 entries (one for the stop and one for the start):

WITH Downtime AS (
    SELECT *,
           LEAD([Time]) OVER (PARTITION BY Equipment ORDER BY [Time] ASC) AS NextStatus
    FROM @EquipmentDownTime)
SELECT ID,
       Equipment,
       DATEDIFF(MINUTE,[Time],NextStatus) AS Duration
FROM Downtime
WHERE StartStop = 'Stop';


问:
Passing template tabs value while creating envelope
I know there exists an question similar to the one which I am going to ask but that question was asked 4 years back and no concrete answer is given. Link for the question is here

I am creating an envelope using existing template and everything works smooth as butter. But, when I try to pre fill tabs value in template, tabs values are not being added to envelope. I have tried two different JSON requests, one with tabId and one with tabLabel. None of them worked.

Try 1:

```<code>{
    "status":"sent",
    "emailSubject":"Testing with DocuSign",
    "templateId":"124faf68-3b42-43b9-9b6d-814d465e161d",
    "templateRoles":
        [{
            "roleName":"Climber",
            "name":"xyz",
            "email":"temp@email.com",
            "clientUserId":"126789",
            "tabs":{
                "fullNameTabs":[{
                    "tabId":"bb56d91a-1665-4817-99a6-643c67defbc1",
                    "value":"abc"
                }],
                "companyTabs":[{
                    "tabId":"ba5p67cb-bcf5-42b0-aa04-a0cfec448ddc",
                    "value":"Temporary companyname"
                }]
            }
         }]
}
</code>```

Try 2:

```<code>{
    "status":"sent",
    "emailSubject":"Testing with DocuSign",
    "templateId":"124faf68-3b42-43b9-9b6d-814d465e161d",
    "templateRoles":
        [{
            "roleName":"Climber",
            "name":"xyz",
            "email":"temp@email.com",
            "clientUserId":"126789",
            "tabs":{
                "fullNameTabs":[{
                    "tabLabel":"CustomField1",
                    "value":"abc"
                }],
                "companyTabs":[{
                    "tabLabel":"Company 2fdbb190-2f3e-4d39-8202-e15b9a1c332a,
                    "value":"Temporary companyname"
                }]
            }
         }]
}
</code>```

Can someone tell me if I am doing wrong.

答:
To populate tab values via a Create Envelope request, you'll need to use the compositeTemplates structure within the request body.  Here's an example of that request structure that uses the data you provided in your post -- but populates a single textTab, instead of the companyTab and fullnameTab. As Amit mentioned in his post, the companyTab and fullnameTab cannot be set via the API.

```<code>POST https://demo.docusign.net/restapi/v2/accounts/ACCOUNT_NUMBER/envelopes

{
    "status" : "sent",
    "emailSubject": "Testing with DocuSign",
    "compositeTemplates": [
    {
        "serverTemplates": [
        {
            "sequence" : 1,
            "templateId": "124faf68-3b42-43b9-9b6d-814d465e161d"
        }],
        "inlineTemplates": [
        {
            "sequence" : 2,
            "recipients": {
                "signers" : [{
                    "roleName": "Climber",
                    "name": "xyz",
                    "email": "temp@email.com",
                    "clientUserId": "126789",
                    "recipientId": "1",
                    "tabs": {
                      "textTabs": [
                          {
                              "tabLabel": "field1",
                              "value": "field-1-value"
                          }
                      ]
                    }
                }]
            }
        }]
    }]
}
</code>```

Body:
I know there exists an question similar to the one which I am going to ask but that question was asked 4 years back and no concrete answer is given. Link for the question is here

I am creating an envelope using existing template and everything works smooth as butter. But, when I try to pre fill tabs value in template, tabs values are not being added to envelope. I have tried two different JSON requests, one with tabId and one with tabLabel. None of them worked.

Try 1:

{
    "status":"sent",
    "emailSubject":"Testing with DocuSign",
    "templateId":"124faf68-3b42-43b9-9b6d-814d465e161d",
    "templateRoles":
        [{
            "roleName":"Climber",
            "name":"xyz",
            "email":"temp@email.com",
            "clientUserId":"126789",
            "tabs":{
                "fullNameTabs":[{
                    "tabId":"bb56d91a-1665-4817-99a6-643c67defbc1",
                    "value":"abc"
                }],
                "companyTabs":[{
                    "tabId":"ba5p67cb-bcf5-42b0-aa04-a0cfec448ddc",
                    "value":"Temporary companyname"
                }]
            }
         }]
}

Try 2:

{
    "status":"sent",
    "emailSubject":"Testing with DocuSign",
    "templateId":"124faf68-3b42-43b9-9b6d-814d465e161d",
    "templateRoles":
        [{
            "roleName":"Climber",
            "name":"xyz",
            "email":"temp@email.com",
            "clientUserId":"126789",
            "tabs":{
                "fullNameTabs":[{
                    "tabLabel":"CustomField1",
                    "value":"abc"
                }],
                "companyTabs":[{
                    "tabLabel":"Company 2fdbb190-2f3e-4d39-8202-e15b9a1c332a,
                    "value":"Temporary companyname"
                }]
            }
         }]
}

Can someone tell me if I am doing wrong.

Body:
To populate tab values via a Create Envelope request, you'll need to use the compositeTemplates structure within the request body.  Here's an example of that request structure that uses the data you provided in your post -- but populates a single textTab, instead of the companyTab and fullnameTab. As Amit mentioned in his post, the companyTab and fullnameTab cannot be set via the API.

POST https://demo.docusign.net/restapi/v2/accounts/ACCOUNT_NUMBER/envelopes

{
    "status" : "sent",
    "emailSubject": "Testing with DocuSign",
    "compositeTemplates": [
    {
        "serverTemplates": [
        {
            "sequence" : 1,
            "templateId": "124faf68-3b42-43b9-9b6d-814d465e161d"
        }],
        "inlineTemplates": [
        {
            "sequence" : 2,
            "recipients": {
                "signers" : [{
                    "roleName": "Climber",
                    "name": "xyz",
                    "email": "temp@email.com",
                    "clientUserId": "126789",
                    "recipientId": "1",
                    "tabs": {
                      "textTabs": [
                          {
                              "tabLabel": "field1",
                              "value": "field-1-value"
                          }
                      ]
                    }
                }]
            }
        }]
    }]
}


问:
Which Magento Soap V2 method should I use for external links?
I am working on a script that imports all product information from a Magento 1.9.3.1 website.

I cant seem to find a method which allows me to get the external links data which is associated with every product.

(See screenshot)

Does anyone know which method I need to use?

A list of methods can be found here:

http://devdocs.magento.com/guides/m1x/api/soap/introduction.html#Introduction-APIMethods

I think I have used all catalog related methods but none of them seem to return the data I need.

答:
You can use this method: http://devdocs.magento.com/guides/m1x/api/soap/catalog/catalogProduct/catalog_product.update.html

From your screenshots, these look like custom attributes. Obtain their codes from Catalog > Attributes > Manage Attributes. Then, in the catalog_product.update call, include them in additonal_attributes as an array or arrays.

Example:
'additional_attributes' => array(
    array('key' => 'ready_link', 'value'=> '...'),
    array('key' => 'itunes_link', 'value'=> '...'),
)


问:
Get bounding box with Google Maps Api Js
How can I get the bounding box of a polygon in google maps api? With open layers if I could achieve it, but not with google maps.

I need to get the boundig box to be able to manipulate an intersection with JSTS by increasing or reducing the size of the bounding box.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: { lat: 24.886, lng: -70.268 },
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  // Define the LatLng coordinates for the polygon's path.
  var bermudaCoords = [
    { lat: 25.774, lng: -80.190 },
    { lat: 18.466, lng: -66.118 },
    { lat: 32.321, lng: -64.757 },
    { lat: 25.774, lng: -80.190 }
  ];

  // Construct the polygon. //triangulo azul
  var bermudaTriangle = new google.maps.Polygon({
    paths: bermudaCoords,
    strokeColor: '#0404B4',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#0404B4',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);

  // Construct another polygon.
  var anotherCoords = [
    { lat: 25.774, lng: -85.101 },
    { lat: 35.406, lng: -85.101 },
    { lat: 35.406, lng: -54.127 },
    { lat: 25.774, lng: -60.010 }
  ];

//poligono amarillo
  var anotherArea = new google.maps.Polygon({
    paths: anotherCoords,
    strokeColor: '#FFFF00',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FFFF00',
    fillOpacity: 0.35
  });
  anotherArea.setMap(map);

  //calc polygons intersection
  var geometryFactory = new jsts.geom.GeometryFactory();
  var bermudaPolygon = createJstsPolygon(geometryFactory, bermudaTriangle);
  var anotherPolygon = createJstsPolygon(geometryFactory, anotherArea);
  var intersection = bermudaPolygon.intersection(anotherPolygon);
  drawIntersectionArea(map, intersection);
}

function drawIntersectionArea(map, polygon) {
  var coords = polygon.getCoordinates().map(function (coord) {
    return { lat: coord.x, lng: coord.y };
  });

//area de interseccion rosa
  var intersectionArea = new google.maps.Polygon({
    paths: coords,
    strokeColor: '#FE2EF7',
    strokeOpacity: 0.8,
    strokeWeight: 4,
    fillColor: '#FE2EF7',
    fillOpacity: 0.35
  });
  intersectionArea.setMap(map);
}

function createJstsPolygon(geometryFactory, polygon) {
  var path = polygon.getPath();
  var coordinates = path.getArray().map(function name(coord) {
    return new jsts.geom.Coordinate(coord.lat(), coord.lng());
  });
  coordinates.push(coordinates[0]);
  var shell = geometryFactory.createLinearRing(coordinates);
  return geometryFactory.createPolygon(shell);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map,
        html,
        body {
            padding: 0;
            margin: 0;
            height: 100%;
        }</code>```

```

https://jsfiddle.net/vgrem/3ukpuxq9/

答:
The function below will compute the bounds of a google.maps.Polygon

```<code>function polygonBounds(polygon) {
   var bounds = new google.maps.LatLngBounds();
   for (var i=0; i<polygon.getPaths().getLength(); i++) {
     for (var j=0; j<polygon.getPaths().getAt(i).getLength(); j++) {
        bounds.extend(polygon.getPaths().getAt(i).getAt(j));
     }
   }
   return bounds;
}
</code>```

proof of concept fiddle

code snippet:

function polygonBounds(polygon) {
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < polygon.getPaths().getLength(); i++) {
    for (var j = 0; j < polygon.getPaths().getAt(i).getLength(); j++) {
      bounds.extend(polygon.getPaths().getAt(i).getAt(j));
    }
  }
  return bounds;
}

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: 24.886,
      lng: -70.268
    },
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  // Define the LatLng coordinates for the polygon's path.
  var bermudaCoords = [{
      lat: 25.774,
      lng: -80.190
    },
    {
      lat: 18.466,
      lng: -66.118
    },
    {
      lat: 32.321,
      lng: -64.757
    },
    {
      lat: 25.774,
      lng: -80.190
    }
  ];

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: bermudaCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);
  var triBnds = new google.maps.Rectangle({
    map: map,
    bounds: polygonBounds(bermudaTriangle)
  })

  // Construct another polygon.
  var anotherCoords = [{
      lat: 25.774,
      lng: -85.101
    },
    {
      lat: 35.406,
      lng: -85.101
    },
    {
      lat: 35.406,
      lng: -54.127
    },
    {
      lat: 25.774,
      lng: -60.010
    }
  ];

  var anotherArea = new google.maps.Polygon({
    paths: anotherCoords,
    strokeColor: '#0000FF',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#0000FF',
    fillOpacity: 0.35
  });
  anotherArea.setMap(map);
  var otherBnds = new google.maps.Rectangle({
    map: map,
    bounds: polygonBounds(anotherArea)
  })

  //calc polygons intersection
  var geometryFactory = new jsts.geom.GeometryFactory();
  var bermudaPolygon = createJstsPolygon(geometryFactory, bermudaTriangle);
  var anotherPolygon = createJstsPolygon(geometryFactory, anotherArea);
  var intersection = bermudaPolygon.intersection(anotherPolygon);
  drawIntersectionArea(map, intersection);
}

function drawIntersectionArea(map, polygon) {
  var coords = polygon.getCoordinates().map(function(coord) {
    return {
      lat: coord.x,
      lng: coord.y
    };
  });

  var intersectionArea = new google.maps.Polygon({
    paths: coords,
    strokeColor: '#00FF00',
    strokeOpacity: 0.8,
    strokeWeight: 4,
    fillColor: '#00FF00',
    fillOpacity: 0.35
  });
  intersectionArea.setMap(map);
}

function createJstsPolygon(geometryFactory, polygon) {
  var path = polygon.getPath();
  var coordinates = path.getArray().map(function name(coord) {
    return new jsts.geom.Coordinate(coord.lat(), coord.lng());
  });
  coordinates.push(coordinates[0]);
  var shell = geometryFactory.createLinearRing(coordinates);
  return geometryFactory.createPolygon(shell);
}

google.maps.event.addDomListener(window, 'load', initMap);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map,
html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}</code>```

```

Body:
How can I get the bounding box of a polygon in google maps api? With open layers if I could achieve it, but not with google maps.

I need to get the boundig box to be able to manipulate an intersection with JSTS by increasing or reducing the size of the bounding box.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: { lat: 24.886, lng: -70.268 },
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  // Define the LatLng coordinates for the polygon's path.
  var bermudaCoords = [
    { lat: 25.774, lng: -80.190 },
    { lat: 18.466, lng: -66.118 },
    { lat: 32.321, lng: -64.757 },
    { lat: 25.774, lng: -80.190 }
  ];

  // Construct the polygon. //triangulo azul
  var bermudaTriangle = new google.maps.Polygon({
    paths: bermudaCoords,
    strokeColor: '#0404B4',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#0404B4',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);

  // Construct another polygon.
  var anotherCoords = [
    { lat: 25.774, lng: -85.101 },
    { lat: 35.406, lng: -85.101 },
    { lat: 35.406, lng: -54.127 },
    { lat: 25.774, lng: -60.010 }
  ];

//poligono amarillo
  var anotherArea = new google.maps.Polygon({
    paths: anotherCoords,
    strokeColor: '#FFFF00',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FFFF00',
    fillOpacity: 0.35
  });
  anotherArea.setMap(map);

  //calc polygons intersection
  var geometryFactory = new jsts.geom.GeometryFactory();
  var bermudaPolygon = createJstsPolygon(geometryFactory, bermudaTriangle);
  var anotherPolygon = createJstsPolygon(geometryFactory, anotherArea);
  var intersection = bermudaPolygon.intersection(anotherPolygon);
  drawIntersectionArea(map, intersection);
}

function drawIntersectionArea(map, polygon) {
  var coords = polygon.getCoordinates().map(function (coord) {
    return { lat: coord.x, lng: coord.y };
  });

//area de interseccion rosa
  var intersectionArea = new google.maps.Polygon({
    paths: coords,
    strokeColor: '#FE2EF7',
    strokeOpacity: 0.8,
    strokeWeight: 4,
    fillColor: '#FE2EF7',
    fillOpacity: 0.35
  });
  intersectionArea.setMap(map);
}

function createJstsPolygon(geometryFactory, polygon) {
  var path = polygon.getPath();
  var coordinates = path.getArray().map(function name(coord) {
    return new jsts.geom.Coordinate(coord.lat(), coord.lng());
  });
  coordinates.push(coordinates[0]);
  var shell = geometryFactory.createLinearRing(coordinates);
  return geometryFactory.createPolygon(shell);
}

#map,
        html,
        body {
            padding: 0;
            margin: 0;
            height: 100%;
        }

https://jsfiddle.net/vgrem/3ukpuxq9/

Body:
The function below will compute the bounds of a google.maps.Polygon

function polygonBounds(polygon) {
   var bounds = new google.maps.LatLngBounds();
   for (var i=0; i<polygon.getPaths().getLength(); i++) {
     for (var j=0; j<polygon.getPaths().getAt(i).getLength(); j++) {
        bounds.extend(polygon.getPaths().getAt(i).getAt(j));
     }
   }
   return bounds;
}

proof of concept fiddle

code snippet:

function polygonBounds(polygon) {
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < polygon.getPaths().getLength(); i++) {
    for (var j = 0; j < polygon.getPaths().getAt(i).getLength(); j++) {
      bounds.extend(polygon.getPaths().getAt(i).getAt(j));
    }
  }
  return bounds;
}

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: 24.886,
      lng: -70.268
    },
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  // Define the LatLng coordinates for the polygon's path.
  var bermudaCoords = [{
      lat: 25.774,
      lng: -80.190
    },
    {
      lat: 18.466,
      lng: -66.118
    },
    {
      lat: 32.321,
      lng: -64.757
    },
    {
      lat: 25.774,
      lng: -80.190
    }
  ];

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: bermudaCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);
  var triBnds = new google.maps.Rectangle({
    map: map,
    bounds: polygonBounds(bermudaTriangle)
  })

  // Construct another polygon.
  var anotherCoords = [{
      lat: 25.774,
      lng: -85.101
    },
    {
      lat: 35.406,
      lng: -85.101
    },
    {
      lat: 35.406,
      lng: -54.127
    },
    {
      lat: 25.774,
      lng: -60.010
    }
  ];

  var anotherArea = new google.maps.Polygon({
    paths: anotherCoords,
    strokeColor: '#0000FF',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#0000FF',
    fillOpacity: 0.35
  });
  anotherArea.setMap(map);
  var otherBnds = new google.maps.Rectangle({
    map: map,
    bounds: polygonBounds(anotherArea)
  })

  //calc polygons intersection
  var geometryFactory = new jsts.geom.GeometryFactory();
  var bermudaPolygon = createJstsPolygon(geometryFactory, bermudaTriangle);
  var anotherPolygon = createJstsPolygon(geometryFactory, anotherArea);
  var intersection = bermudaPolygon.intersection(anotherPolygon);
  drawIntersectionArea(map, intersection);
}

function drawIntersectionArea(map, polygon) {
  var coords = polygon.getCoordinates().map(function(coord) {
    return {
      lat: coord.x,
      lng: coord.y
    };
  });

  var intersectionArea = new google.maps.Polygon({
    paths: coords,
    strokeColor: '#00FF00',
    strokeOpacity: 0.8,
    strokeWeight: 4,
    fillColor: '#00FF00',
    fillOpacity: 0.35
  });
  intersectionArea.setMap(map);
}

function createJstsPolygon(geometryFactory, polygon) {
  var path = polygon.getPath();
  var coordinates = path.getArray().map(function name(coord) {
    return new jsts.geom.Coordinate(coord.lat(), coord.lng());
  });
  coordinates.push(coordinates[0]);
  var shell = geometryFactory.createLinearRing(coordinates);
  return geometryFactory.createPolygon(shell);
}

google.maps.event.addDomListener(window, 'load', initMap);

#map,
html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
<script src="https://cdn.rawgit.com/bjornharrtell/jsts/gh-pages/1.1.2/jsts.min.js"></script>
<div id="map"></div>


问:
R - Pick out documents from VCorpus (or TermDocumentMatrix) containing key words
I have a list of keywords in a text file:

```<code>tagSrc <- "20171107 keyword dictionary v2.txt"
tagDictionary <- readLines(tagSrc, encoding="UTF-8")
</code>```

...and I have a .csv file full of event reports, which I turn into a VCorpus and TermDocumentMatrix:

```<code>srcFile <- "20170831 Event Log April 17.csv"
incidents <- read.csv(srcFile, stringsAsFactors = FALSE)
descriptions <- incidents$Description

desc_source <- VectorSource(descriptions)
desc_corpus <- VCorpus(desc_source)
desc_corpus <- tm_map(desc_corpus, removeNumbers)
desc_corpus <- tm_map(desc_corpus, removeWords, c(stopwords("en"))

#Various text-cleaning routines
desc_corpus <- tm_map(desc_corpus, content_transformer(replace_abbreviation))
desc_corpus <- tm_map(desc_corpus, content_transformer(replace_contraction))

desc_stem <- tm_map(desc_corpus, content_transformer(stemDocument), language="english")

#Here, the corpus is turned into a TDM
desc_dtm <- TermDocumentMatrix(desc_stem, control = list(dictionary = tagDictionary))
</code>```

The last line above gives me a TDM which only uses the terms in the list of key words (tagDictionary). Is there a way I could also reduce the number of documents, to only those which contain one or more of the key words?

答:
After more searching around, I found that the best way to do this is to reduce the number of documents before constructing the TDM. Running a grep search on the corpus via tm_filter picks out the documents:

```<code>#collapse the search terms in `tagDictionary` into a single string:
allTags<-paste(tagDictionary, collapse='|')

#filter the VCorpus (see code in OP):
corp_subset <- tm_filter(desc_stem, function(i), any(grep(allTags, content(i), ignore.case = TRUE)))

#create the TDM from the filtered VCorpus:
desc_dtm <- TermDocumentMatrix(corp_subset)
</code>```

Body:
I have a list of keywords in a text file:

tagSrc <- "20171107 keyword dictionary v2.txt"
tagDictionary <- readLines(tagSrc, encoding="UTF-8")

...and I have a .csv file full of event reports, which I turn into a VCorpus and TermDocumentMatrix:

srcFile <- "20170831 Event Log April 17.csv"
incidents <- read.csv(srcFile, stringsAsFactors = FALSE)
descriptions <- incidents$Description

desc_source <- VectorSource(descriptions)
desc_corpus <- VCorpus(desc_source)
desc_corpus <- tm_map(desc_corpus, removeNumbers)
desc_corpus <- tm_map(desc_corpus, removeWords, c(stopwords("en"))

#Various text-cleaning routines
desc_corpus <- tm_map(desc_corpus, content_transformer(replace_abbreviation))
desc_corpus <- tm_map(desc_corpus, content_transformer(replace_contraction))

desc_stem <- tm_map(desc_corpus, content_transformer(stemDocument), language="english")

#Here, the corpus is turned into a TDM
desc_dtm <- TermDocumentMatrix(desc_stem, control = list(dictionary = tagDictionary))

The last line above gives me a TDM which only uses the terms in the list of key words (tagDictionary). Is there a way I could also reduce the number of documents, to only those which contain one or more of the key words?

Body:
After more searching around, I found that the best way to do this is to reduce the number of documents before constructing the TDM. Running a grep search on the corpus via tm_filter picks out the documents:

#collapse the search terms in `tagDictionary` into a single string:
allTags<-paste(tagDictionary, collapse='|')

#filter the VCorpus (see code in OP):
corp_subset <- tm_filter(desc_stem, function(i), any(grep(allTags, content(i), ignore.case = TRUE)))

#create the TDM from the filtered VCorpus:
desc_dtm <- TermDocumentMatrix(corp_subset)


问:
Transpose rows and columns in a 2D array
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:

```<code>    //Creating rows and columns for text file
    echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($result as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";
}

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}
</code>```

My first table displays as expected and looks somthing like this:

```<code>1 2 3 4 5
6 7 8 9 10
</code>```

I need it to appear as such (i.e rotating the position of the rows and columns):

```<code>1 6
2 7
3 8
4 9
5 10
</code>```

I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix

答:
Your function seems to be working fine you just need to call it.

Add this below the function:

```<code>//Creating rows and columns for text file
$result[0] = ['1','2','3','4','5'];
$result[1] = ['6','7','8','9','10'];
$result[2] = ['11','12','13','14','15'];
$result[3] = ['16','17','18','19','20'];
$result[4] = ['21','22','23','24','25'];
    echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($result as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}

$mat = transpose_matrix($result);
echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($mat as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";
</code>```

Body:
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:

    //Creating rows and columns for text file
    echo "
Data Table
";
    echo "
";
    foreach($result as $key=>$value){
        echo "
";
        foreach($value as $v){
            echo "".$v."	";
        }
        echo "
";

    }
    echo "
";
}

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}

My first table displays as expected and looks somthing like this:

1 2 3 4 5
6 7 8 9 10

I need it to appear as such (i.e rotating the position of the rows and columns):

1 6
2 7
3 8
4 9
5 10

I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix

Body:
Your function seems to be working fine you just need to call it.

Add this below the function:

//Creating rows and columns for text file
$result[0] = ['1','2','3','4','5'];
$result[1] = ['6','7','8','9','10'];
$result[2] = ['11','12','13','14','15'];
$result[3] = ['16','17','18','19','20'];
$result[4] = ['21','22','23','24','25'];
    echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($result as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}

$mat = transpose_matrix($result);
echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($mat as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";


问:
Assistance in understanding sqr logic

Hello, I am new to learning how to develop sqr programs within PeopleSoft. I've been going through some programs we are utilizing and wanted to see if someone could help provide clarification with what the below snippet of code is doing in this While loop.

```<code> if $path != ''
   let $Archive_File = $path || 'ARCHIVE\' || $filename || $Curr_Date || '.dat'
   open $Out_File  as 1  for-reading record=450:vary status=#fileread
   open $Archive_File as 2  for-writing record=450:vary status=#filewrite
   While 1
     if #END-FILE
        break
     else
        read 1 into $Current_Line:999
        write 2 from $Current_Line
    end-if
 End-While
 close 1
 close 2
end-if
</code>```

I'm trying to understand if the WHILE statement is evaluating the "$Out_File as 1" as the logical expression, or is 1 being evaluated as the value of the variable #END-FILE (As I understand this variable is set to either 0 or 1).

答:
Its a true loop, it will go there until reach a BREAK.
In this case if #END-FILE is true, the loop will break.</p>

Title: Assistance in understanding sqr logic

Body:
Hello, I am new to learning how to develop sqr programs within PeopleSoft. I've been going through some programs we are utilizing and wanted to see if someone could help provide clarification with what the below snippet of code is doing in this While loop.

 if $path != ''
   let $Archive_File = $path || 'ARCHIVE\' || $filename || $Curr_Date || '.dat'
   open $Out_File  as 1  for-reading record=450:vary status=#fileread
   open $Archive_File as 2  for-writing record=450:vary status=#filewrite
   While 1
     if #END-FILE
        break
     else
        read 1 into $Current_Line:999
        write 2 from $Current_Line
    end-if
 End-While
 close 1
 close 2
end-if

I'm trying to understand if the WHILE statement is evaluating the "$Out_File as 1" as the logical expression, or is 1 being evaluated as the value of the variable #END-FILE (As I understand this variable is set to either 0 or 1).


问:
R problems with function 'subset'
I'm just learning to use R, so it may seems as a noob question for you, but I have some problems with function “subset”. I tried to find an answer in previous questions, but failed(

For example, I have a data frame q with 3 variables x, y, z

```<code>q = read.csv("test.csv",encoding = "UTF-8",
                  header = TRUE, sep = ",", na.strings = c("",NA))
</code>```

Variable x has 4 meanings a, b, c, d

I'm trying to make a data frame q1 only with 2 meanings of variable x - a & c

```<code>q1 = subset(q, q$x == 'a' | q$x == 'c')
</code>```

As a result I have new data frame with 2 meanings of variable x (I check it by opening new dataframe).

But when I table variable x from new dataset q1, I see again 4 meanings, but with the number of b & d =0.

What do I do incorrectly? Why do I see b & d, when I table x in new data set?

Thanks for your help!

答:
The column in your data frame is a factor, which is another name for a categorical variable, a thing that can take one of a number of possible character values, or "levels", such as "Male" or "Female".

When you subset a factor you don't change the levels. What you are seeing is the levels tabulated, so there are some zeroes.

If you want to avoid this then convert your factors to character values with the as.character function or read them in as character with the stringsAsFactors=FALSE option to read.csv.

Title: R problems with function 'subset'

Body:
I'm just learning to use R, so it may seems as a noob question for you, but I have some problems with function “subset”. I tried to find an answer in previous questions, but failed(

For example, I have a data frame q with 3 variables x, y, z

q = read.csv("test.csv",encoding = "UTF-8",
                  header = TRUE, sep = ",", na.strings = c("",NA))

Variable x has 4 meanings a, b, c, d

I'm trying to make a data frame q1 only with 2 meanings of variable x - a & c

q1 = subset(q, q$x == 'a' | q$x == 'c')

As a result I have new data frame with 2 meanings of variable x (I check it by opening new dataframe).

But when I table variable x from new dataset q1, I see again 4 meanings, but with the number of b & d =0.

What do I do incorrectly? Why do I see b & d, when I table x in new data set?

Thanks for your help!


问:
Newbie question about Jquery scope
Quick question regarding a jquery scope in following example:

```<code>$(function(){
  var test;
  $.get('txtfile.txt', function(txtfile) {
      test = txtfile.split('\n');
  });
  console.log(test);
});
</code>```

console returns 'test' is undefined. Could u please point me where im making a mistake.
Thanks.

答:
$.get works asynchronously (The "A" in "Ajax" stands for "Asynchronous"). The success callback (which you are defining using the function(){} construct) is called only after the Ajax call has finished. When the code arrives at

```<code>console.log(test);
</code>```

that has  not yet happened.

If you put the console.log call into the success callback, it will work as expected.

Title: Newbie question about Jquery scope

Body:
Quick question regarding a jquery scope in following example:

$(function(){
  var test;
  $.get('txtfile.txt', function(txtfile) {
      test = txtfile.split('\n');
  });
  console.log(test);
});

console returns 'test' is undefined. Could u please point me where im making a mistake.
Thanks.

Body:
$.get works asynchronously (The "A" in "Ajax" stands for "Asynchronous"). The success callback (which you are defining using the function(){} construct) is called only after the Ajax call has finished. When the code arrives at

console.log(test);

that has  not yet happened.

If you put the console.log call into the success callback, it will work as expected.


问:
Python coding flaw for making acronyms
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.

Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.

Code is as follows:

```<code>#ask for Input
name = input('Input words to make acroname :')

#make all in caps
name = name.upper()

#turn them in list
listname = name.split()

#cycle through
for namee in listname:
    #Get the first letter & type in same line
    print(name[0],end="")
print()

input (' press a key to move out' )
</code>```

答:
You may correct your code. Instead of print(name[0]) you should use print(namee[0]) as you want to print the first letter of the word, not the original name.

A good practice is to name the variables the more descriptive you can so as to avoid such typos.

If you want to print the acronym in same line I would suggest to use below code to get variable acronym with the desired output:

```<code>phrase = raw_input('Input words to make acronym:')
phrase = phrase.upper()
list_words = phrase.split()
acronym = [word[0] for word in list_words]
acronym = "".join(acronym)
print acronym
</code>```

Title: Python coding flaw for making acronyms

Body:
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.

Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.

Code is as follows:

#ask for Input
name = input('Input words to make acroname :')

#make all in caps
name = name.upper()

#turn them in list
listname = name.split()

#cycle through
for namee in listname:
    #Get the first letter & type in same line
    print(name[0],end="")
print()

input (' press a key to move out' )

Body:
You may correct your code. Instead of print(name[0]) you should use print(namee[0]) as you want to print the first letter of the word, not the original name.

A good practice is to name the variables the more descriptive you can so as to avoid such typos.

If you want to print the acronym in same line I would suggest to use below code to get variable acronym with the desired output:

phrase = raw_input('Input words to make acronym:')
phrase = phrase.upper()
list_words = phrase.split()
acronym = [word[0] for word in list_words]
acronym = "".join(acronym)
print acronym


问:
SQL Server concatenation separated by comma only when column is not null
I have the following SQL statement:

```<code>@All = COALESCE(NULLIF(@Asc1, '') + ',', '') +
        OALESCE(NULLIF(@Asc2, '') + ',', '') +
        OALESCE(NULLIF(@Asc3, '') + ',', '');
</code>```

This will insert a comma at the end even if any of the variables (@Asc1, @Asc2, @Asc3) have NULL or empty values.

For example:

if @Asc1 = 1234 and @Asc2 = 3456 and @Asc3 = '', then @All will end up being 1234,3456,

I would like @All to be 1234,3456

Thanks.

答:
I know this post is already answered and is correct. But would like to post the below answer because from SQL Server 2017 onwards, this is too easy and someoen might find this helpful in future.</p>

```<code>SELECT @all = CONCAT_WS(',',@Asc1,@Asc2,@Asc3)
</code>```

Body:
I have the following SQL statement:

@All = COALESCE(NULLIF(@Asc1, '') + ',', '') +
        OALESCE(NULLIF(@Asc2, '') + ',', '') +
        OALESCE(NULLIF(@Asc3, '') + ',', '');

This will insert a comma at the end even if any of the variables (@Asc1, @Asc2, @Asc3) have NULL or empty values.

For example:

if @Asc1 = 1234 and @Asc2 = 3456 and @Asc3 = '', then @All will end up being 1234,3456,

I would like @All to be 1234,3456

Thanks.

Body:
I know this post is already answered and is correct. But would like to post the below answer because from SQL Server 2017 onwards, this is too easy and someoen might find this helpful in future.

SELECT @all = CONCAT_WS(',',@Asc1,@Asc2,@Asc3)


问:
How to loop through all sheets in all workbooks within a folder
I use a macro to make changes on each sheet of each workbook in a given folder on my computer.

Sequence of events:

Open each Excel file within the user-selected folder

Perform a task on each sheet in the workbook

Save the file

Close the workbook

The macro doesn't work. The problem seems to be arising from Selection.AutoFilter.

Sub LoopAllExcelFilesInFolder()
    'OBJECTIVE: To loop through all Excel files in a user specified folder and perform a set task on them
    'SOURCE: www.TheSpreadsheetGuru.com

    Dim wb As Workbook
    Dim Current As Worksheet
    Dim myPath As String
    Dim myFile As String
    Dim myExtension As String
    Dim FldrPicker As FileDialog

    'Optimize Macro Speed
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    'Retrieve Target Folder Path From User
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
        .Title = "Select A Target Folder"
        .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

    'In Case of Cancel
    NextCode:
    myPath = myPath
    If myPath = "" Then GoTo ResetSettings

    'Target File Extension (must include wildcard "*")
    myExtension = "*.xlsx*"

    'Target Path with Ending Extention
    myFile = Dir(myPath & myExtension)

    'Loop through each Excel file in folder
    Do While myFile <> ""
        'Set variable equal to opened workbook
        Set wb = Workbooks.Open(Filename:=myPath & myFile)

        'Ensure Workbook has opened before moving on to next line of code
        DoEvents

        'Task: For each worksheet, delete the first column, make A1 bold, and filter and remove all rows in column A that do not contain anything

        For Each Current In wb.Worksheets
            Columns("A:A").Select
            Selection.Delete Shift:=xlToLeft
            Range("A1").Select
            Selection.Font.Bold = True
            Selection.AutoFilter
            ActiveSheet.Range("$A$1:$A$5000").AutoFilter Field:=1, Criteria1:="="
            Rows("2:2").Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.Delete Shift:=xlUp
            ActiveSheet.ShowAllData
            Range("A1").Select
         Next

        'Save and Close Workbook
        wb.Close SaveChanges:=True

        'Ensure Workbook has closed before moving on to next line of code
        DoEvents

        'Get next file name
        myFile = Dir
    Loop

    'Message Box when tasks are completed
    MsgBox "Task Complete!"

    ResetSettings:
    'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
```

答:
You should try it like this.

```<code>Sub Example()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String, Fnum As Long
    Dim mybook As Workbook
    Dim CalcMode As Long
    Dim sh As Worksheet
    Dim ErrorYes As Boolean

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                'Change cell value(s) in one worksheet in mybook
                On Error Resume Next
                With mybook.Worksheets(1)
                    If .ProtectContents = False Then
                        .Range("A1").Value = "My New Header"
                    Else
                        ErrorYes = True
                    End If
                End With

                If Err.Number > 0 Then
                    ErrorYes = True
                    Err.Clear
                    'Close mybook without saving
                    mybook.Close savechanges:=False
                Else
                    'Save and close mybook
                    mybook.Close savechanges:=True
                End If
                On Error GoTo 0
            Else
                'Not possible to open the workbook
                ErrorYes = True
            End If

        Next Fnum
    End If

    If ErrorYes = True Then
        MsgBox "There are problems in one or more files, possible problem:" _
             & vbNewLine & "protected workbook/sheet or a sheet/range that not exist"
    End If

    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub
</code>```

https://www.rondebruin.nl/win/s3/win010.htm

Body:
You should try it like this.

Sub Example()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String, Fnum As Long
    Dim mybook As Workbook
    Dim CalcMode As Long
    Dim sh As Worksheet
    Dim ErrorYes As Boolean

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                'Change cell value(s) in one worksheet in mybook
                On Error Resume Next
                With mybook.Worksheets(1)
                    If .ProtectContents = False Then
                        .Range("A1").Value = "My New Header"
                    Else
                        ErrorYes = True
                    End If
                End With

                If Err.Number > 0 Then
                    ErrorYes = True
                    Err.Clear
                    'Close mybook without saving
                    mybook.Close savechanges:=False
                Else
                    'Save and close mybook
                    mybook.Close savechanges:=True
                End If
                On Error GoTo 0
            Else
                'Not possible to open the workbook
                ErrorYes = True
            End If

        Next Fnum
    End If

    If ErrorYes = True Then
        MsgBox "There are problems in one or more files, possible problem:" _
             & vbNewLine & "protected workbook/sheet or a sheet/range that not exist"
    End If

    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

https://www.rondebruin.nl/win/s3/win010.htm


问:
Calculate percentile column from a numeric column
I am trying to create a calculated column called percentile_Idle_Time(I am trying to calculate percentile for every value). The column is percentile value from idle_time% column.

So, the input data is

```<code>Total Time   Idle Time    Idle Time %
 5:10:00      0:14:00       4.6%
 3:09:00      0:20:00       9.49%
   .             .            .
   .             .            .
</code>```

So, I am trying to create a new column called percentile_Idle_Time which is nothing but the percentile position of the Idle Time % value

So, the output data should be like

```<code>Total Time   Idle Time    Idle Time %    percentile_Idle_Time
 5:10:00      0:14:00       4.6%             75.4
 3:09:00      0:20:00       9.49%            97.9
   .             .            .               .
   .             .            .               .
</code>```

Note: The numbers are pretty rough(not accurate)
I tried using

```<code> proc univariate data=WORK.QUERY_FOR_PEOPLENET_DATA_00_0000 noprint;
 by DriverId;
 var 'Short Idle Time %'n;
 output pctlpre=P_ ;
 run;
</code>```

But its not working. The other challenge is to take percentile score from the % column

答:
Do it manually then. Sort the data ascending and use the NOBS to get the number of observations. Use n to divide by NOBS to get the total value.

```<code>proc sort data=sashelp.class out=class;
by weight;
run;

data want;
  set class Nobs=myobs;

   percentile = _n_ / myobs;
run;
</code>```

NOTE that this does not deal with ties. If you do have ties that need to be dealt with, use PROC RANK instead. I usually do it with a group of 100 and then you'll get the 1 to 100 groups. But its' 96.5 percentile if that's what you're looking for.

```<code> proc rank data=sashelp.class out=ranked_class groups=100;
 var weight;
 ranks  weight_percentile;
 run;
</code>```

EDIT: Fixed references in data step and sort to align.

Body:
I am trying to create a calculated column called percentile_Idle_Time(I am trying to calculate percentile for every value). The column is percentile value from idle_time% column.

So, the input data is

Total Time   Idle Time    Idle Time %
 5:10:00      0:14:00       4.6%
 3:09:00      0:20:00       9.49%
   .             .            .
   .             .            .

So, I am trying to create a new column called percentile_Idle_Time which is nothing but the percentile position of the Idle Time % value

So, the output data should be like

Total Time   Idle Time    Idle Time %    percentile_Idle_Time
 5:10:00      0:14:00       4.6%             75.4
 3:09:00      0:20:00       9.49%            97.9
   .             .            .               .
   .             .            .               .

Note: The numbers are pretty rough(not accurate)
I tried using

 proc univariate data=WORK.QUERY_FOR_PEOPLENET_DATA_00_0000 noprint;
 by DriverId;
 var 'Short Idle Time %'n;
 output pctlpre=P_ ;
 run;

But its not working. The other challenge is to take percentile score from the % column

Body:
Do it manually then. Sort the data ascending and use the NOBS to get the number of observations. Use n to divide by NOBS to get the total value.

proc sort data=sashelp.class out=class;
by weight;
run;

data want;
  set class Nobs=myobs;

   percentile = _n_ / myobs;
run;

NOTE that this does not deal with ties. If you do have ties that need to be dealt with, use PROC RANK instead. I usually do it with a group of 100 and then you'll get the 1 to 100 groups. But its' 96.5 percentile if that's what you're looking for.

 proc rank data=sashelp.class out=ranked_class groups=100;
 var weight;
 ranks  weight_percentile;
 run;

EDIT: Fixed references in data step and sort to align.


答: factor variables (R version of categorical variables) remember all possible categories unless you tell them not to. You can "forget" them with q1 = droplevels(q1) or by converting the factor to an ordinary string: q1$x = as.character(q1$x)

Title: R problems with function 'subset'


问:
Mocking a system communicating with JMS messages on IBM MQ?
I have two applications SystemA and SystemB communicating via request and response messages and using correlation IDs.

I would like to be able to test SystemA in isolation without having to rely on the availability of our IBM MQ broker and SystemB. Ideally I would like to do it in our continuous integration environment (Jenkins). I am looking for common approaches to this problem, before I code a solution myself in-house.

How can I create a mockup of the IBM MQ broker and SystemB for the purpose of testing SystemA in isolation?

答: Why mock the queue?  Have you considered mocking the consumer from the queue instead?  This would be simpler and would leave the queues in place for when the full featured service became available.</p>