问:
The three biggest numbers in array
```<code>#include<iostream>
using namespace std;
int main()
{
    int s;
    cin>>s;
    int t=3;
    int maxValue,imax[t],maxIndex,arr[s];
    for(int i=0; i<s; i++){
        cin>>arr[i];
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if(arr[i]>maxValue){
             maxValue=arr[i];
             imax[0] = i;
        }
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if (i == imax[0]) { continue; }
        if(arr[i]>maxValue){
            maxValue=arr[i];
            imax[1] = i;
        }
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if (i == imax[0]) { continue; }
        if (i == imax[1]) { continue; }
        if(arr[i]>maxValue){
            maxValue=arr[i];
            imax[2] = i;
        }
    }
    cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
    cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
    cout<<"Third biggest number:"<<arr[imax[2]];
    return 0;
}
</code>```

This program must return tree numbers which is biggest in this arraybut , i do not know why when  I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.

答:
You use uninitialized array values in lines

```<code>cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
</code>```

If there are less than 3 different numbers in input, some imax array elements will not be initialized. Also if input array is empty, imax will not be initialized at all.

Therefore in expression arr[imax[1]] you read element of arr with index, which was not initialized and can be some very big number. It can be fixed if you declare iarr as

```<code>int imax[t] = {};
</code>```

This will zero-initialize all elements of array and will prevent crashing.

Your program also doesn't check number of elements in input array, so if there are less than three input numbers arr[2] will also print uninitialized value.

Here's proper solution using STL algorithms and std::vector. It works with any number of t - you can easily change it to print largest 10 numbers. It is also memory efficient - it does not need to store whole input array so you can process large inputs with it.

```<code>#include <algorithm>
#include <iostream>
#include <vector>

int main() {
  int s;
  std::cin >> s;

  unsigned t = 3;
  std::vector<int> max_numbers;
  max_numbers.reserve(t + 1);

  for (int i = 0; i < s; ++i) {
    int number;
    if (std::cin >> number) { //Check basic input errors
      max_numbers.push_back(number); // Add number to top-3 list

      // Sort elements in descending order
      std::sort(max_numbers.begin(), max_numbers.end(), std::greater<int>());

      // Remove duplicates
      max_numbers.erase(std::unique(max_numbers.begin(), max_numbers.end()),
                        max_numbers.end());

      // Remove excess elements
      if (max_numbers.size() > t) {
        max_numbers.resize(t);
      }
    }
  }

  std::cout << "Biggest " << t << " numbers are" << std::endl;
  for (int i : max_numbers) {
    std::cout << i << std::endl;
  }
}
</code>```

Title: The three biggest numbers in array

Body:
#include<iostream>
using namespace std;
int main()
{
    int s;
    cin>>s;
    int t=3;
    int maxValue,imax[t],maxIndex,arr[s];
    for(int i=0; i<s; i++){
        cin>>arr[i];
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if(arr[i]>maxValue){
             maxValue=arr[i];
             imax[0] = i;
        }
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if (i == imax[0]) { continue; }
        if(arr[i]>maxValue){
            maxValue=arr[i];
            imax[1] = i;
        }
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if (i == imax[0]) { continue; }
        if (i == imax[1]) { continue; }
        if(arr[i]>maxValue){
            maxValue=arr[i];
            imax[2] = i;
        }
    }
    cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
    cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
    cout<<"Third biggest number:"<<arr[imax[2]];
    return 0;
}

This program must return tree numbers which is biggest in this arraybut , i do not know why when  I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.

Body:
You use uninitialized array values in lines

cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];

If there are less than 3 different numbers in input, some imax array elements will not be initialized. Also if input array is empty, imax will not be initialized at all.

Therefore in expression arr[imax[1]] you read element of arr with index, which was not initialized and can be some very big number. It can be fixed if you declare iarr as

int imax[t] = {};

This will zero-initialize all elements of array and will prevent crashing.

Your program also doesn't check number of elements in input array, so if there are less than three input numbers arr[2] will also print uninitialized value.

Here's proper solution using STL algorithms and std::vector. It works with any number of t - you can easily change it to print largest 10 numbers. It is also memory efficient - it does not need to store whole input array so you can process large inputs with it.

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
  int s;
  std::cin >> s;

  unsigned t = 3;
  std::vector<int> max_numbers;
  max_numbers.reserve(t + 1);

  for (int i = 0; i < s; ++i) {
    int number;
    if (std::cin >> number) { //Check basic input errors
      max_numbers.push_back(number); // Add number to top-3 list

      // Sort elements in descending order
      std::sort(max_numbers.begin(), max_numbers.end(), std::greater<int>());

      // Remove duplicates
      max_numbers.erase(std::unique(max_numbers.begin(), max_numbers.end()),
                        max_numbers.end());

      // Remove excess elements
      if (max_numbers.size() > t) {
        max_numbers.resize(t);
      }
    }
  }

  std::cout << "Biggest " << t << " numbers are" << std::endl;
  for (int i : max_numbers) {
    std::cout << i << std::endl;
  }
}


来源: stackexchange

问:
how to get the previous 3 months in php
how to get the previous 3 months in php ex(If i say DEC.. It should display the previous 3 months i.e., OCT NOV DEC)</p>

答:
```<code>    $month = date('M');
    $year = date('Y');
    $no_of_mnths = date('n',strtotime("-2 months"));
    $remaining_months = (12 - $no_of_mnths)."\r\n";
    $tot = $remaining_months+1;
    for($j=0;$j<$tot;$j++){
            echo  date('M',strtotime(''.$no_of_mnths.' months'))
            $no_of_mnths++;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: how to get the previous 3 months in php


问:
Is there a way to compare two diffs or patches?
Is there a way to test if two diffs or patches are equivalent?

Let's say you have the following git commit history, where features F and G are cleanly rebaseable to E:

```<code>     G
    /
A--B--C--D--E
 \
  F
</code>```

Due to limitations in our current deployment process, we have the following, somewhat related graph (it's not version controlled)

```<code>              G'
             /
------------E'
             \
              F'
</code>```

F' and G' will ultimately be applied to the head E', in some to be determined order, so it would end up like

```<code>------------E'--G'--F'
</code>```

Is there a way to test that the diff from E' to G' is the same as the patch produced by the git commit of G from B?

I fully realize that in an ideal world, revision control would solve this, and we're getting there, but that's not where we are currently.

You could essentially play both patches on separate checkouts and compare the outputs, but that seems kind of clunky. And comparing the diffs themselves, I'm assuming, wouldn't work because line numbers could change. Even if G' and F' were rebased to E', the patch for F' would ultimately be applied to G', making the diff context of the patch different.

答:
For the benefit of the reader, here is an update to the answer of @mrbrdo with a little tweak:

Adds git sdiff alias for easy access of this.  sdiff stands for show diff.

Ignore annotated tag headers using the ^{} suffix.

Allow diff options to be used like -u etc.

Run this once in each of your accounts in which you use git:

```<code>git config --global alias.sdiff '!'"bash -c 'O=(); A=(); while x=\"\$1\"; shift; do case \$x in -*) O+=(\"\$x\");; *) A+=(\"\$x^{}\");; esac; done; g(){ git show \"\${A[\$1]}\" && return; echo FAIL \${A[\$1]}; git show \"\${A[\$2]}\"; }; diff \"\${O[@]}\" <(g 0 1) <(g 1 0)' --"
</code>```

Afterwards you can use this:

```<code>git sdiff F G
</code>```

Please note that this needs bash version 3 or above.

Explained:

git config --global alias.sdiff adds an alias named git sdiff into the global ~/.gitconfig.

! runs the alias as shell command

bash -c we need bash (or ksh), as <(..) does not work in dash (aka. /bin/sh).

O=(); A=(); while x="$1"; shift; do case $x in -*) O+=("$x");; *) A+=("$x^{}");; esac; done; separates options (-something) and arguments (everything else).  Options are in array O while arguments are in array A.  Note that all arguments get ^{} attached, too, which skipps over annotations (such that you can use annotated tags).

g(){ git show "${A[$1]}" && return; echo FAIL ${A[$1]}; git show "${A[$2]}"; }; creates a helper function, which does git show for the first argument.  If that fails, it outputs "FAIL first-argument" and then outputs the second argument.  This is a trick to reduce the overhead in case something fails.  (A proper error managment would be too much.)

diff "${O[@]}" <(g 0 1) <(g 1 0) runs diff with the given options against the first argument and the second argument (with said FAIL-error fallback to the other argument to reduce the diff).

-- allows to pass diff-options (-something) to this alias/script.

Bugs:

Number of arguments is not checked.  Everything behind the 2nd argument is ignored, and if you give it too few, you just see FAIL or nothing at all.

Errors act a bit strange and clutter the output.  If you do not like this, run it with 2>/dev/null (or change the script appropriately).

It does not return an error if something breaks.

You probably want to feed this into a pager by default.

Please note that it is easy to define some more aliases like:

```<code>git config --global alias.udiff '!git sdiff -u'
git config --global alias.bdiff '!git sdiff -b'

git config --global alias.pager '!pager() { cd "$GIT_PREFIX" && git -c color.status=always -c color.ui=always "$@" 2>&1 | less -XFR; }; pager'
git config --global alias.ddiff '!git pager udiff'
</code>```

I hope this does not need to be explained further.

For more aliases like that, perhaps have a look at my GitHub repo

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to test if two diffs or patches are equivalent?

Let's say you have the following git commit history, where features F and G are cleanly rebaseable to E:

     G
    /
A--B--C--D--E
 \
  F

Due to limitations in our current deployment process, we have the following, somewhat related graph (it's not version controlled)

              G'
             /
------------E'
             \
              F'

F' and G' will ultimately be applied to the head E', in some to be determined order, so it would end up like

------------E'--G'--F'

Is there a way to test that the diff from E' to G' is the same as the patch produced by the git commit of G from B?

I fully realize that in an ideal world, revision control would solve this, and we're getting there, but that's not where we are currently.

You could essentially play both patches on separate checkouts and compare the outputs, but that seems kind of clunky. And comparing the diffs themselves, I'm assuming, wouldn't work because line numbers could change. Even if G' and F' were rebased to E', the patch for F' would ultimately be applied to G', making the diff context of the patch different.

Body:
For the benefit of the reader, here is an update to the answer of @mrbrdo with a little tweak:

Adds git sdiff alias for easy access of this.  sdiff stands for show diff.

Ignore annotated tag headers using the ^{} suffix.

Allow diff options to be used like -u etc.

Run this once in each of your accounts in which you use git:

git config --global alias.sdiff '!'"bash -c 'O=(); A=(); while x=\"\$1\"; shift; do case \$x in -*) O+=(\"\$x\");; *) A+=(\"\$x^{}\");; esac; done; g(){ git show \"\${A[\$1]}\" && return; echo FAIL \${A[\$1]}; git show \"\${A[\$2]}\"; }; diff \"\${O[@]}\" <(g 0 1) <(g 1 0)' --"

Afterwards you can use this:

git sdiff F G

Please note that this needs bash version 3 or above.

Explained:

git config --global alias.sdiff adds an alias named git sdiff into the global ~/.gitconfig.

! runs the alias as shell command

bash -c we need bash (or ksh), as <(..) does not work in dash (aka. /bin/sh).

O=(); A=(); while x="$1"; shift; do case $x in -*) O+=("$x");; *) A+=("$x^{}");; esac; done; separates options (-something) and arguments (everything else).  Options are in array O while arguments are in array A.  Note that all arguments get ^{} attached, too, which skipps over annotations (such that you can use annotated tags).

g(){ git show "${A[$1]}" && return; echo FAIL ${A[$1]}; git show "${A[$2]}"; }; creates a helper function, which does git show for the first argument.  If that fails, it outputs "FAIL first-argument" and then outputs the second argument.  This is a trick to reduce the overhead in case something fails.  (A proper error managment would be too much.)

diff "${O[@]}" <(g 0 1) <(g 1 0) runs diff with the given options against the first argument and the second argument (with said FAIL-error fallback to the other argument to reduce the diff).

-- allows to pass diff-options (-something) to this alias/script.

Bugs:

Number of arguments is not checked.  Everything behind the 2nd argument is ignored, and if you give it too few, you just see FAIL or nothing at all.

Errors act a bit strange and clutter the output.  If you do not like this, run it with 2>/dev/null (or change the script appropriately).

It does not return an error if something breaks.

You probably want to feed this into a pager by default.

Please note that it is easy to define some more aliases like:

git config --global alias.udiff '!git sdiff -u'
git config --global alias.bdiff '!git sdiff -b'

git config --global alias.pager '!pager() { cd "$GIT_PREFIX" && git -c color.status=always -c color.ui=always "$@" 2>&1 | less -XFR; }; pager'
git config --global alias.ddiff '!git pager udiff'

I hope this does not need to be explained further.

For more aliases like that, perhaps have a look at my GitHub repo


问:
Why does Python have a limit on the number of static blocks that can be nested?
The number of statically nested blocks in Python is limited to 20.
That is, nesting 19 for loops will be fine (although excessively time consuming; O(n^19) is insane), but nesting 20 will fail with:

```<code>SyntaxError: too many statically nested blocks
</code>```

What is the underlying reason for having such a limit?
Is there a way to increase the limit?

答:
This limit not only applies to for loops, but to all other control flow blocks as well. The limit for the number of nested control flow blocks is defined inside of code.h with a constant named CO_MAXBLOCKS:

#define CO_MAXBLOCKS 20 /* Max static block nesting within a function */
```

<p>This constant is used to set the maximum size for the stack Python uses to execute exceptions and loops named <code>blockstack</code>. This limit is imposed upon all frame objects and is shown in frameobject.h:</p>

<pre class="lang-c prettyprint-override"><code>int blockstack[CO_MAXBLOCKS];       /* Walking the 'finally' blocks */
</code>```

The most likely reason for this limit is to keep memory usage at a sane level when executing nested blocks. It's probably similar to the limit Python imposes on recursive calls. This limit can be seen being enforced in compile.c:

if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
    PyErr_SetString(PyExc_SyntaxError,
                    "too many statically nested blocks");
    return 0;
}
```

A more concrete answer as to why Python has this specfic limit and why they cannot get rid of it, was given by Michael Hudson in a 2004 Python mailing list letter:

Spot on.  This has to do with the 'blockstack', very much an internal
  detail to Python's implementation.  We'd like to get rid of it (not
  because we want to let people write code with more than 20 nested for
  loops :-) but it's not especially easy (finally: blocks are the
  biggest problem).

Note that in Python 2.6 and lower, breaking the maximum number of nested loops would've cause a SystemError not a SyntaxError. This was changed however  in Python 3 and back-patched to Python 2.7 so a SyntaxError would be raised instead. This was documented in #issue 27514:

Issue #27514: Make having too many statically nested blocks a SyntaxError
    instead of SystemError.

The reason for this change in exception types was given by Serhiy Storchaka :

[...] SystemError is not an exception that should be raised. SystemError is for errors that can't be occurred in normal case. It should only be caused by incorrect use of C API or hacking Python internals. I think SyntaxError is more appropriate in this case [...].

Body:
The number of statically nested blocks in Python is limited to 20.
That is, nesting 19 for loops will be fine (although excessively time consuming; O(n^19) is insane), but nesting 20 will fail with:

SyntaxError: too many statically nested blocks

What is the underlying reason for having such a limit?
Is there a way to increase the limit?

Body:
This limit not only applies to for loops, but to all other control flow blocks as well. The limit for the number of nested control flow blocks is defined inside of code.h with a constant named CO_MAXBLOCKS:

#define CO_MAXBLOCKS 20 /* Max static block nesting within a function */

This constant is used to set the maximum size for the stack Python uses to execute exceptions and loops named blockstack. This limit is imposed upon all frame objects and is shown in frameobject.h:

int blockstack[CO_MAXBLOCKS];       /* Walking the 'finally' blocks */

The most likely reason for this limit is to keep memory usage at a sane level when executing nested blocks. It's probably similar to the limit Python imposes on recursive calls. This limit can be seen being enforced in compile.c:

if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
    PyErr_SetString(PyExc_SyntaxError,
                    "too many statically nested blocks");
    return 0;
}

A more concrete answer as to why Python has this specfic limit and why they cannot get rid of it, was given by Michael Hudson in a 2004 Python mailing list letter:

Spot on.  This has to do with the 'blockstack', very much an internal
  detail to Python's implementation.  We'd like to get rid of it (not
  because we want to let people write code with more than 20 nested for
  loops :-) but it's not especially easy (finally: blocks are the
  biggest problem).

Note that in Python 2.6 and lower, breaking the maximum number of nested loops would've cause a SystemError not a SyntaxError. This was changed however  in Python 3 and back-patched to Python 2.7 so a SyntaxError would be raised instead. This was documented in #issue 27514:

Issue #27514: Make having too many statically nested blocks a SyntaxError
    instead of SystemError.

The reason for this change in exception types was given by Serhiy Storchaka :

[...] SystemError is not an exception that should be raised. SystemError is for errors that can't be occurred in normal case. It should only be caused by incorrect use of C API or hacking Python internals. I think SyntaxError is more appropriate in this case [...].


问:
Ephesoft is not installing libreoffice dependecy
Im working on ubuntu 16.04.2 LTS and i need to integrate ephesoft 4.0.2.0 to alfresco community so i have to install ephesoft.

While im installing i stack in a point that it can´t install its libreoffice dependency, i first deleted the libreoffice coming in my OS but realize that was not the problem, then i installed another one and again that was not the problem, so i don´t know what to do, the ephesoft installation can not move foward because of it.

Please if there is anyone who can help me with it, I will be gratefull.

Att, MGM

答: I had the same problem and try a lot of things and then found out that 16.04 is not supported by ephesoft, only 14.04 and 14.10 work. </p>


问:
When to call findViewById in an Activity
I am encountering the following issue.
I have the following lines of code :

```<code>Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
domainSpinner.setVisibility(View.VISIBLE);
</code>```

These get executed after the user clicks on menu item in the UI. So I am pretty sure the UI is drawn on the screen. The spinner should be on the screen, and already filled with data.
The menu item is to change the language of the screen. The spinner should than fill up with items in the newly selected language.

In GooglePlay I sometimes get an error report where the stackTrace gives a NullPointerException in the 2nd line. So it must be that domainSpinner is null.

I have never experienced this issue myself. Also we use a beta version of the app for our own use, and none of my collegues has ever had this issue.

I have no idea why the findViewById should sometimes return null. I have tried going back and forward, rotating, .... But I never have this problem.

Note that the item R.id.domain can have a visibility of GONE setted programmatically. But I also played with this but could not reproduce the problem.

Code of the menu item action :

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item)
{
   int id = item.getItemId();
   if (id == R.id.action_nl)
   {
      changeLanguage("nl", true);
      return true;
   }
   else if (id == R.id.action_fr)
   {
      changeLanguage("fr", true);
      return true;
   }
   else if (id == R.id.action_en)
   {
      changeLanguage("en", true);
      return true;
   }
   else if (id == R.id.action_de)
   {
      changeLanguage("de", true);
      return true;
   }

   return super.onOptionsItemSelected(item);
</code>```

}

答:
You should always initialise your views on the OnCreate method in an activity to make sure the view exists when you want to reference it.
Like below:

```<code>private Spinner domainSpinner;

@Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        domainSpinner = (Spinner) findViewById(R.id.domain);
    }
</code>```

Let me know if this helps!

UPDATE: If you need to use the variable outside of the on create method, then declare a global variable and still initialise it on create, then use it where needed.

Body:
I am encountering the following issue.
I have the following lines of code :

Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
domainSpinner.setVisibility(View.VISIBLE);

These get executed after the user clicks on menu item in the UI. So I am pretty sure the UI is drawn on the screen. The spinner should be on the screen, and already filled with data.
The menu item is to change the language of the screen. The spinner should than fill up with items in the newly selected language.

In GooglePlay I sometimes get an error report where the stackTrace gives a NullPointerException in the 2nd line. So it must be that domainSpinner is null.

I have never experienced this issue myself. Also we use a beta version of the app for our own use, and none of my collegues has ever had this issue.

I have no idea why the findViewById should sometimes return null. I have tried going back and forward, rotating, .... But I never have this problem.

Note that the item R.id.domain can have a visibility of GONE setted programmatically. But I also played with this but could not reproduce the problem.

Code of the menu item action :

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
   int id = item.getItemId();
   if (id == R.id.action_nl)
   {
      changeLanguage("nl", true);
      return true;
   }
   else if (id == R.id.action_fr)
   {
      changeLanguage("fr", true);
      return true;
   }
   else if (id == R.id.action_en)
   {
      changeLanguage("en", true);
      return true;
   }
   else if (id == R.id.action_de)
   {
      changeLanguage("de", true);
      return true;
   }

   return super.onOptionsItemSelected(item);

}

Body:
You should always initialise your views on the OnCreate method in an activity to make sure the view exists when you want to reference it.
Like below:

private Spinner domainSpinner;

@Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        domainSpinner = (Spinner) findViewById(R.id.domain);
    }

Let me know if this helps!

UPDATE: If you need to use the variable outside of the on create method, then declare a global variable and still initialise it on create, then use it where needed.


问:
How do I disable a jqueryui button
When I click on a jquery ui button, it still triggers the click event callback. How do I block that event? Do I have to manually keep track of the state or does jquery ui take care of that for me?</p>

答:
If you define like this:

```<code>$("#mybtn").button();
</code>```

you must enable/disable like this:

```<code>$("#mybtn").button("enable");
// OR
$("#mybtn").button("disable");
</code>```

Title: How do I disable a jqueryui button

Body:
If you define like this:

$("#mybtn").button();

you must enable/disable like this:

$("#mybtn").button("enable");
// OR
$("#mybtn").button("disable");


问:
how to setvalue in formbuilder array
I have a problem about set array value to formBuilder.array. In the formBuilder that not array it can use this way to setValue but in formBuilder.array I can't do it. I try set value to formbuilder 'listServiceFeature' and 'listservicefeature' but it's not set value either way.

ts

```<code>listServiceFeature: any = ['m1', 'm2']

contentFormValidate(): void {

  this.contentForm = this.formBuilder.group({
          'listservicefeature': this.formBuilder.array([
              this.formBuilder.group({
                 listServiceFeature: ['', [Validators.required]
              });
          ]),
  });

  this.contentForm.controls['listservicefeature'].setValue(this.listServiceFeature);
}

addServiceFeature() {
    const control = <FormArray>this.contentForm.controls['listservicefeature'];
    control.push(this.initServiceFeature());
}

removeServiceFeature(i: number) {
    const control = <FormArray>this.contentForm.controls['listservicefeature'];
    control.removeAt(i);
}
</code>```

html

```<code><div formArrayName="listservicefeature">
  <div class="form-group" *ngFor="let servicefeature of contentForm.controls.listservicefeature.controls; let i=index">
    <label for="Service">Features {{i+1}}</label>
    <div class="input-group" [formGroupName]="i">
        <input type="text" class="form-control" formControlName="listServiceFeature">
        <template [ngIf]="i == 0">
            <span class="input-group-btn">
            <button (click)="addServiceFeature()" class="btn btn-default" type="button">
            <span class="lnr lnr-plus-circle icon-orange-gable-buttom"></span>
            </button>
            </span>
        </template>
        <template [ngIf]="i > 0">
            <span class="input-group-btn">
            <button (click)="removeServiceFeature(i)" class="btn btn-default" type="button">
            <span class="lnr lnr-trash icon-orange-gable-buttom"></span>
            </button>
            </span>
        </template>
    </div>
  </div>
</div>
</code>```

答:
It looks to me like what you want to do is to add a control to the formArray.
Take a look at the documentation for reactive-forms

https://angular.io/guide/reactive-forms

quote:

Notice that you replace the previous FormArray with the FormGroup.setControl method, not with setValue. You're replacing a control, not the value of a control.

in the documentation they do like this:
1) Add a getter as shortcut to the formArray:

```<code> get listservicefeatures(): FormArray {
    return this.contentform.get('listservicefeature') as FormArray;
  };
</code>```

2) create an add method that would look like this:

```<code>addServiceFeature()  {
this.listservicefeatures.push(this.fb.group({newservicefeature: 'defaultvalue', [Validators.required]}));
}
</code>```

also your inital declaration of the formArray should probably look like this:

```<code>this.contentForm = this.formBuilder.group({
          'listservicefeature': this.formBuilder.array([]),
  });
</code>```

I hope this helps :)

Title: how to setvalue in formbuilder array

Body:
I have a problem about set array value to formBuilder.array. In the formBuilder that not array it can use this way to setValue but in formBuilder.array I can't do it. I try set value to formbuilder 'listServiceFeature' and 'listservicefeature' but it's not set value either way.

ts

listServiceFeature: any = ['m1', 'm2']

contentFormValidate(): void {

  this.contentForm = this.formBuilder.group({
          'listservicefeature': this.formBuilder.array([
              this.formBuilder.group({
                 listServiceFeature: ['', [Validators.required]
              });
          ]),
  });

  this.contentForm.controls['listservicefeature'].setValue(this.listServiceFeature);
}

addServiceFeature() {
    const control = <FormArray>this.contentForm.controls['listservicefeature'];
    control.push(this.initServiceFeature());
}

removeServiceFeature(i: number) {
    const control = <FormArray>this.contentForm.controls['listservicefeature'];
    control.removeAt(i);
}

html

    Features {{i+1}}

        <input type="text" class="form-control" formControlName="listServiceFeature">
        <template [ngIf]="i == 0">

            <button (click)="addServiceFeature()" class="btn btn-default" type="button">

            </button>

        </template>
        <template [ngIf]="i > 0">

            <button (click)="removeServiceFeature(i)" class="btn btn-default" type="button">

            </button>

        </template>

Body:
It looks to me like what you want to do is to add a control to the formArray.
Take a look at the documentation for reactive-forms

https://angular.io/guide/reactive-forms

quote:

Notice that you replace the previous FormArray with the FormGroup.setControl method, not with setValue. You're replacing a control, not the value of a control.

in the documentation they do like this:
1) Add a getter as shortcut to the formArray:

 get listservicefeatures(): FormArray {
    return this.contentform.get('listservicefeature') as FormArray;
  };

2) create an add method that would look like this:

addServiceFeature()  {
this.listservicefeatures.push(this.fb.group({newservicefeature: 'defaultvalue', [Validators.required]}));
}

also your inital declaration of the formArray should probably look like this:

this.contentForm = this.formBuilder.group({
          'listservicefeature': this.formBuilder.array([]),
  });

I hope this helps :)


问:
Split an array into smaller arrays using R
I have a 1D array with an odd number of rows, 2435 rows. I want to split the array into smaller arrays and each time perform a small test.

Firstly, I want to split the big array into two smaller arrays.

Then I would like to split my array into 4 smaller arrays, then into 8 small arrays and so on.

Can anyone help with that?

An example is the following:

A<-1:2435

A1
  1,2,3,4,...,1237

A2
  1238, 1239,...,2435

Thanks in advance

答:
If you want to split the data through the middle of the array, you can also use the split function:

```<code>a <- 1:2435

divide <- function(x, n = 2)
{
  i <- ceiling(length(x)/n)
  split(x,x%/%i+1)

}

divide(a)
</code>```

and with more parts you can use

```<code>divide(a, n = 4)
</code>```

Or in two itterations use

```<code>lapply(divide(a,2),function(x) divide(x,2))
</code>```

With a higher value of n, the sizes will not be equal anymore, due to rounding issues. Which warrants the use of the nested approach.

Body:
If you want to split the data through the middle of the array, you can also use the split function:

a <- 1:2435

divide <- function(x, n = 2)
{
  i <- ceiling(length(x)/n)
  split(x,x%/%i+1)

}

divide(a)

and with more parts you can use

divide(a, n = 4)

Or in two itterations use

lapply(divide(a,2),function(x) divide(x,2))

With a higher value of n, the sizes will not be equal anymore, due to rounding issues. Which warrants the use of the nested approach.


问:
VBA Copy and paste data skipping the first row
I have 40 different excel data files (data1.csv ~ data40.csv) with the same format. I am trying to generate a graph based on all the data read from those 40 files.
My idea is, create a new temporary .csv file (tempOut.csv) into which I copy and paste all data read from each file in order one by one, and in the end generate a graph using the data in that temporary file.

The problem is that, each file has the title row like (ID, name, val1, val2,,,,). When I copy data from each file, I need to remove this row, or skip this row at all and copy, and then paste it in the temporary .csv file, EXCEPT FOR the first file.

How could this be achieved using the code I wrote?
Here is my code:

```<code>Dim thisFile As String   'input file name
Dim outFile As String    'output file name
Dim dataRead As String   'containing data copied and pasted
outFile = "tempOut.csv"
Open outFile For Output As #1
For i = 1 To 40
  thisFile = "C:\datafolder\data" + CStr(i) + ".csv"
  Open thisFile For Input As #2
  Do Until EOF(2)         'read until the end of the file
    Line Input #2, dataRead
    Print #1, dataRead
  Loop
  Close #2
Next i
Close #1
</code>```

This code does create a new file, and copy and paste all data from each file in order. However, each time, it copy and pastes the title row too. I have added if statement such that when i = 1, it reads everything. But I am quite not sure how to copy skipping the first row, from the 2nd file read till the last file.

Can anyone please help me with this? Thank you in advance.

Add:
For example, the data1.csv looks like

|ID|Name|Val1|Val2| ...

|0 |aaaa|　1　|　2　| ...

|1 |bbbb|　3　|　4　| ...

|2 |cccc|　5　|　6　| ...

and data2.csv looks like

|ID|Name|Val1|Val2| ...

|3 |dddd|　7　|　8　| ...

|4 |eeee|　9　|　9　| ...

|5 |ffff|　7　|　5　| ...

Then, the combined tempOut.csv should look like

|ID|Name|Val1|Val2| ...

|0 |aaaa|　1　|　2　| ...

|1 |bbbb|　3　|　4　| ...

|2 |cccc|　5　|　6　| ...

|3 |dddd|　7　|　8　| ...

|4 |eeee|　9　|　9　| ...

|5 |ffff|　7　|　5　| ...

答:
You will need to keep track of the first file that exists and where you are in a file, so add variables "j" and "k" like in the code below:</p>

```<code>   Dim thisFile As String   'input file name
   Dim outFile As String    'output file name
   Dim dataRead As String   'containing data copied and pasted

   outFile = "tempOut.csv"
   Open outFile For Output As #1

   k = 0

   For i = 1 To 40
     thisFile = "C:\datafolder\data" + CStr(i) + ".csv"
     Open thisFile For Input As #2
     j = 0

     Do Until EOF(2)         'read until the end of the file
       If k = 0 Then k = i
       j = j + 1
       Line Input #2, dataRead

       If i = k Or (i > k And j > 1) Then
          Print #1, dataRead
       End If
     Loop

     Close #2
   Next i

   Close #1
</code>```

Body:
I have 40 different excel data files (data1.csv ~ data40.csv) with the same format. I am trying to generate a graph based on all the data read from those 40 files.
My idea is, create a new temporary .csv file (tempOut.csv) into which I copy and paste all data read from each file in order one by one, and in the end generate a graph using the data in that temporary file.

The problem is that, each file has the title row like (ID, name, val1, val2,,,,). When I copy data from each file, I need to remove this row, or skip this row at all and copy, and then paste it in the temporary .csv file, EXCEPT FOR the first file.

How could this be achieved using the code I wrote?
Here is my code:

Dim thisFile As String   'input file name
Dim outFile As String    'output file name
Dim dataRead As String   'containing data copied and pasted
outFile = "tempOut.csv"
Open outFile For Output As #1
For i = 1 To 40
  thisFile = "C:\datafolder\data" + CStr(i) + ".csv"
  Open thisFile For Input As #2
  Do Until EOF(2)         'read until the end of the file
    Line Input #2, dataRead
    Print #1, dataRead
  Loop
  Close #2
Next i
Close #1

This code does create a new file, and copy and paste all data from each file in order. However, each time, it copy and pastes the title row too. I have added if statement such that when i = 1, it reads everything. But I am quite not sure how to copy skipping the first row, from the 2nd file read till the last file.

Can anyone please help me with this? Thank you in advance.

Add:
For example, the data1.csv looks like

|ID|Name|Val1|Val2| ...

|0 |aaaa|　1　|　2　| ...

|1 |bbbb|　3　|　4　| ...

|2 |cccc|　5　|　6　| ...

and data2.csv looks like

|ID|Name|Val1|Val2| ...

|3 |dddd|　7　|　8　| ...

|4 |eeee|　9　|　9　| ...

|5 |ffff|　7　|　5　| ...

Then, the combined tempOut.csv should look like

|ID|Name|Val1|Val2| ...

|0 |aaaa|　1　|　2　| ...

|1 |bbbb|　3　|　4　| ...

|2 |cccc|　5　|　6　| ...

|3 |dddd|　7　|　8　| ...

|4 |eeee|　9　|　9　| ...

|5 |ffff|　7　|　5　| ...

Body:
You will need to keep track of the first file that exists and where you are in a file, so add variables "j" and "k" like in the code below:

   Dim thisFile As String   'input file name
   Dim outFile As String    'output file name
   Dim dataRead As String   'containing data copied and pasted

   outFile = "tempOut.csv"
   Open outFile For Output As #1

   k = 0

   For i = 1 To 40
     thisFile = "C:\datafolder\data" + CStr(i) + ".csv"
     Open thisFile For Input As #2
     j = 0

     Do Until EOF(2)         'read until the end of the file
       If k = 0 Then k = i
       j = j + 1
       Line Input #2, dataRead

       If i = k Or (i > k And j > 1) Then
          Print #1, dataRead
       End If
     Loop

     Close #2
   Next i

   Close #1


问:
powershell - add array to existing nested hash table
I have an array or PSCustomObject called: $results = @()

I have a nested hash table called: $allResults = @{}

$results |ft, shows this in console:

```<code>Brokering        Name             WriteCacheSize   dFreeSpace   (and more...)
---------        ----             --------------   ----------
N/A              server0001       0,004            22,83
N/A              server0002       0,004            21,86
</code>```

$allresults |ft shows this:

```<code>Name                       Value
----                       ----
server0001                     {SCOMStatus, PVSServer, RegistrationState, ServerLoad...}
server0001                     {SCOMStatus, PVSServer, RegistrationState, ServerLoad...}
</code>```

The name is in common in both $. There should be a way to add the values in $results to $allresults, but I don't know how to do it.

I want everything in the hash nested table.  How can I add the values in the $results to the $allresults. The goal is having a nested table with every value.

答: If you're trying to add the values of an array to a hashtable you can loop through the array and use $allresults.Add(<key>,<value>).

Body:
I have an array or PSCustomObject called: $results = @()

I have a nested hash table called: $allResults = @{}

$results |ft, shows this in console:

Brokering        Name             WriteCacheSize   dFreeSpace   (and more...)
---------        ----             --------------   ----------
N/A              server0001       0,004            22,83
N/A              server0002       0,004            21,86

$allresults |ft shows this:

Name                       Value
----                       ----
server0001                     {SCOMStatus, PVSServer, RegistrationState, ServerLoad...}
server0001                     {SCOMStatus, PVSServer, RegistrationState, ServerLoad...}

The name is in common in both $. There should be a way to add the values in $results to $allresults, but I don't know how to do it.

I want everything in the hash nested table.  How can I add the values in the $results to the $allresults. The goal is having a nested table with every value.


问:
How to set my .apk file to run on different screen resolution in android?
I am using a "WVGA800" for my app. I try to run it on different resolution screens. It it is not perfectly scratching in that resolution .
I read and implement issues form this link.
http://developer.android.com/guide/practices/screens_support.html
But still not result. Please let me know if any one hase a perfect solution.
Main issue are that I am fixing hight & width of Image, textsize etc. When these are displayed
to screen of "WVGA800". But when I test them on "HVGA", "QVGA" then problem arise.
I want to avoid the "if else" conditions by getting the screen resolution at Runtime. If any one hase any solution for this...let me know. Thanks in advance.
I am also wondring when there will be new devices with new screen resolutions? </p>

答:
```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.your_company.package_name"
  android:versionCode="1"
  android:versionName="1.0">
<supports-screens
  android:smallScreens="true"
  android:normalScreens="true"
  android:largeScreens="true"
  android:anyDensity="true"/>
.....
</manifest>
</code>```


问:
Curl error: Failed to connect to ipaddress port 8080
problem

```<code>  Curl error: Failed to connect to 103.16.101.52 port 8080: Connection refusedresource(4) of type (mysql result)
</code>```

code snippets works in localsystem.

it's not working prod enviornment.

php curl snippet

```<code>try {

    $runfile = 'http://103.16.101.52:8080/sendsms/bulksms?username=XXX&password=XXX&type=0&dlr=1&destination='. $row['phone_number'] . '&source=XXX&message='.$message;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $runfile);

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    $content = curl_exec ($ch);

    if(curl_exec($ch) === false)
    {
        echo 'Curl error: ' . curl_error($ch);
    }
    else
    {
        echo 'Operation completed without any errors';
    }
    var_dump($result);die;
    curl_close ($ch);

    }
    catch (\Exception $e) {

    $message = $e->getMessage();
    print_r($message);
    die;
    }
</code>```

i googled and found

```<code>   CURLE_NOT_BUILT_IN (4)

   A requested feature, protocol or option was not found built-in in
  this libcurl due to a build-time decision. This means that a feature
   or option was not enabled or explicitly disabled when libcurl was
   built and in order to get it to function you have to get a rebuilt libcurl.
</code>```

does this error belongs ipv4 or ipv6.

im using cpanel  please suggest.

Solution that worked for me

i tried with 80 port

```<code>  $runfile = 'http://103.16.101.52:80
</code>```

答: Do a telnet 103.16.101.52 8080. If you get connected them it could be a curl/php issue. If you get a connection refused message then the server is not listening on that port on the specified ip address. The way it looks from your message, you can't connect on that port because nothing listens on that port on your server (at least at the moment you have asked the question here).</p>

Body:
problem

  Curl error: Failed to connect to 103.16.101.52 port 8080: Connection refusedresource(4) of type (mysql result)

code snippets works in localsystem.

it's not working prod enviornment.

php curl snippet

try {

    $runfile = 'http://103.16.101.52:8080/sendsms/bulksms?username=XXX&password=XXX&type=0&dlr=1&destination='. $row['phone_number'] . '&source=XXX&message='.$message;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $runfile);

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    $content = curl_exec ($ch);

    if(curl_exec($ch) === false)
    {
        echo 'Curl error: ' . curl_error($ch);
    }
    else
    {
        echo 'Operation completed without any errors';
    }
    var_dump($result);die;
    curl_close ($ch);

    }
    catch (\Exception $e) {

    $message = $e->getMessage();
    print_r($message);
    die;
    }

i googled and found

   CURLE_NOT_BUILT_IN (4)

   A requested feature, protocol or option was not found built-in in
  this libcurl due to a build-time decision. This means that a feature
   or option was not enabled or explicitly disabled when libcurl was
   built and in order to get it to function you have to get a rebuilt libcurl.

does this error belongs ipv4 or ipv6.

im using cpanel  please suggest.

Solution that worked for me

i tried with 80 port

  $runfile = 'http://103.16.101.52:80


问:
Sending email dynamically to multiple recipients with message using sp_send_dbmail
Actually i am looking to send Birthday greetings to the members. The recipients list i am getting dynamically. With the below query i can send the greetings to the members.

```<code>DECLARE @emails VARCHAR(500)
DECLARE @bodycontent VARCHAR(500)
SET @emails = ''
SET @bodycontent = ''
use dnname
SELECT @emails = @emails + cm.PersonalEmail + ';' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)
DECLARE @recipList VARCHAR(500)
SET @recipList =  (select SUBSTRING(@emails, 0, LEN(@emails)))
SELECT @bodycontent = 'Happy BirthDay to'+ ' ' + + @bodycontent +
       im.FullName + '' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)
use msdb
EXEC sp_send_dbmail @profile_name='eMail Profile',
    @recipients=@recipList,
    @subject='Happy Birthday',
    @body=@bodycontent,
    @body_format = 'text'
</code>```

So, if @emails have multiple recipients, how can i send the message to each members.

```<code>DECLARE @emails VARCHAR(500)
DECLARE @bodycontent VARCHAR(500)
SET @emails = ''
SET @bodycontent = ''
use dnname
SELECT @emails = @emails + cm.PersonalEmail + ';' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)
DECLARE @recipList VARCHAR(500)
SET @recipList =  (select SUBSTRING(@emails, 0, LEN(@emails)))
SELECT @Count = @Count + Count(cm.PersonalEmail) FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)

Declare @i int
set @i = 0
while @i <= @Count
  begin
SELECT @bodycontent = 'Happy BirthDay to'+ ' ' + + @bodycontent +
       im.FullName + '' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)
use msdb
EXEC sp_send_dbmail @profile_name='eMail Profile',
   @recipients=@recipList,
   @subject='Happy Birthday',
   @body=@bodycontent,
   @body_format = 'text'
end
</code>```

So, how can i modify my query. Any help appreciated, thanks !!!

答:
Here are some observations...

You haven't declared @Count in your code anywhere. It would need to be declared as INT and set to 0

In your WHILE LOOP you aren't incrementing @Count so this loop is infinite

I would make @emails varchar(max) to avoid truncation of the recipient list

@recipList is pointless as far as I can tell... you are setting it to the substring starting at 0 and going the entire length of all the emails... this is the same of saying set @recipList = @emails

Your while loop isn't constructed logically with how you want this to work. It seems like your intent is to send a single email with all of the names who have a birthday. First, I would comma separate these names in @body. Secondly you don't need a loop for this at all. Remove the WHILE loop since all you need to do is send the email once, to the list of @recipList you have built, with the @bodycontent you are concatenating.

With that all being said... your code can be simplified to the below which should work.

```<code>use dnname

DECLARE @emails VARCHAR(max)
DECLARE @bodycontent VARCHAR(max)
DECLARE @people varchar(max)
SET @emails = ''
SET @people = ''
SET @bodycontent = ''

SELECT @emails = @emails + cm.PersonalEmail + ';' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)

SELECT @people = @people + im.FullName + ', '
       FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)

SELECT @bodycontent = 'Happy BirthDay to '+ @people

EXEC msdb.dbo.sp_send_dbmail
                           @profile_name='eMail Profile',
                           @recipients=@emails,
                           @subject='Happy Birthday',
                           @body=@bodycontent,
                           @body_format = 'text'
</code>```

IF you want to send one, personalized email, for each person... you can use a cursor

```<code>use dnname

DECLARE @emails VARCHAR(4000)
DECLARE @bodycontent VARCHAR(max)
DECLARE @people varchar(4000)
SET @emails = ''
SET @people = ''
SET @bodycontent = ''

DECLARE emailCursor CURSOR FOR

SELECT cm.PersonalEmail,im.FullName
FROM tblIndividualMst  im
inner join tblContactMst cm on cm.ContactID = im.ContactID
where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)

OPEN emailCursor
FETCH NEXT FROM emailCursor INTO  @emails, @people

WHILE @@FETCH_STATUS = 0
BEGIN

SET @bodycontent = 'Happy BirthDay to '+ @people

EXEC msdb.dbo.sp_send_dbmail
                           @profile_name='eMail Profile',
                           @recipients=@emails,
                           @subject='Happy Birthday',
                           @body=@bodycontent,
                           @body_format = 'text'

FETCH NEXT FROM emailCursor INTO  @emails, @people

END
CLOSE emailCursor
DEALLOCATE emailCursor
</code>```

Body:
Actually i am looking to send Birthday greetings to the members. The recipients list i am getting dynamically. With the below query i can send the greetings to the members.

DECLARE @emails VARCHAR(500)
DECLARE @bodycontent VARCHAR(500)
SET @emails = ''
SET @bodycontent = ''
use dnname
SELECT @emails = @emails + cm.PersonalEmail + ';' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)
DECLARE @recipList VARCHAR(500)
SET @recipList =  (select SUBSTRING(@emails, 0, LEN(@emails)))
SELECT @bodycontent = 'Happy BirthDay to'+ ' ' + + @bodycontent +
       im.FullName + '' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)
use msdb
EXEC sp_send_dbmail @profile_name='eMail Profile',
    @recipients=@recipList,
    @subject='Happy Birthday',
    @body=@bodycontent,
    @body_format = 'text'

So, if @emails have multiple recipients, how can i send the message to each members.

DECLARE @emails VARCHAR(500)
DECLARE @bodycontent VARCHAR(500)
SET @emails = ''
SET @bodycontent = ''
use dnname
SELECT @emails = @emails + cm.PersonalEmail + ';' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)
DECLARE @recipList VARCHAR(500)
SET @recipList =  (select SUBSTRING(@emails, 0, LEN(@emails)))
SELECT @Count = @Count + Count(cm.PersonalEmail) FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)

Declare @i int
set @i = 0
while @i <= @Count
  begin
SELECT @bodycontent = 'Happy BirthDay to'+ ' ' + + @bodycontent +
       im.FullName + '' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)
use msdb
EXEC sp_send_dbmail @profile_name='eMail Profile',
   @recipients=@recipList,
   @subject='Happy Birthday',
   @body=@bodycontent,
   @body_format = 'text'
end

So, how can i modify my query. Any help appreciated, thanks !!!

Body:
Here are some observations...

You haven't declared @Count in your code anywhere. It would need to be declared as INT and set to 0

In your WHILE LOOP you aren't incrementing @Count so this loop is infinite

I would make @emails varchar(max) to avoid truncation of the recipient list

@recipList is pointless as far as I can tell... you are setting it to the substring starting at 0 and going the entire length of all the emails... this is the same of saying set @recipList = @emails

Your while loop isn't constructed logically with how you want this to work. It seems like your intent is to send a single email with all of the names who have a birthday. First, I would comma separate these names in @body. Secondly you don't need a loop for this at all. Remove the WHILE loop since all you need to do is send the email once, to the list of @recipList you have built, with the @bodycontent you are concatenating.

With that all being said... your code can be simplified to the below which should work.

use dnname

DECLARE @emails VARCHAR(max)
DECLARE @bodycontent VARCHAR(max)
DECLARE @people varchar(max)
SET @emails = ''
SET @people = ''
SET @bodycontent = ''

SELECT @emails = @emails + cm.PersonalEmail + ';' FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)

SELECT @people = @people + im.FullName + ', '
       FROM tblIndividualMst  im
       inner join tblContactMst cm on cm.ContactID = im.ContactID
       where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)

SELECT @bodycontent = 'Happy BirthDay to '+ @people

EXEC msdb.dbo.sp_send_dbmail
                           @profile_name='eMail Profile',
                           @recipients=@emails,
                           @subject='Happy Birthday',
                           @body=@bodycontent,
                           @body_format = 'text'

IF you want to send one, personalized email, for each person... you can use a cursor

use dnname

DECLARE @emails VARCHAR(4000)
DECLARE @bodycontent VARCHAR(max)
DECLARE @people varchar(4000)
SET @emails = ''
SET @people = ''
SET @bodycontent = ''

DECLARE emailCursor CURSOR FOR

SELECT cm.PersonalEmail,im.FullName
FROM tblIndividualMst  im
inner join tblContactMst cm on cm.ContactID = im.ContactID
where im.GroupID = 4673 and im.DateOfBirth = CONVERT(VARCHAR(10),GETDATE(),110)

OPEN emailCursor
FETCH NEXT FROM emailCursor INTO  @emails, @people

WHILE @@FETCH_STATUS = 0
BEGIN

SET @bodycontent = 'Happy BirthDay to '+ @people

EXEC msdb.dbo.sp_send_dbmail
                           @profile_name='eMail Profile',
                           @recipients=@emails,
                           @subject='Happy Birthday',
                           @body=@bodycontent,
                           @body_format = 'text'

FETCH NEXT FROM emailCursor INTO  @emails, @people

END
CLOSE emailCursor
DEALLOCATE emailCursor


问:
How to make Table in PHP
I want to make table with this result (look Echo),  When I put it in the table it happens is all the results are not in one table but one result of one table.

```<code>foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "$ia_key($ia_value)";
                echo "<br>";
                $z++;
            }
        }
    }
</code>```

I tried with this code. But the result is not in one table.

```<code>foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "<div class='row'>";
                    echo "<div class='col-sm-12'>";
                        echo "<h4 class='m-t-0 header-title'></h4>";
                        echo "<div class='table-responsive m-b-20'>";
                            echo "<p class='text-muted font-13 m-b-30'>";
                            echo "<table id='datatable-buttons' class='table table-striped table-bordered'>";
                                 echo "<thead>";
                                    echo "<tr>";
                                        echo "<th>No.</th>";
                                        echo "<th>Nama Item</th>";
                                        echo "<th>Jumlah</th>";
                                    echo"</tr>";
                                    echo "</thead>";
                                    echo "<tbody>";
                                    $no = 0;
                                    $no++;
                                        echo "<tr>";
                                            echo "<td> $no </td>";
                                            echo "<td> $ia_key </td>";
                                            echo "<td> $ia_value </td>";
                                            $z++;
                                        echo "</tr>";
                                    echo "</tbody>";
                                echo "</tr>";
                            echo "</table>";
                        echo "</div>";
                    echo "</div>";
                echo"</div>";
            }
        }
    }
</code>```

Result of above code <== Click to view image.

答:
You need to go revisit PHP basics. It is a template language, instead of
echoing out multiple  strings you can just close the  PHP tag (?>) and
write your desired  output there directly. Then reopen when  you need to
go back to PHP code (<?php).

As for your exact problem, that's because you echo the beginning and end
of each table  inside your loop, so it happens  multiple times. Instead,
you want to  start your table and  end it outside the loop,  and use the
loop to loop over what's repeated: lines.

```<code><div class='row'>
  <div class='col-sm-12'>
    <h4 class='m-t-0 header-title'></h4>
    <div class='table-responsive m-b-20'>
      <p class='text-muted font-13 m-b-30'>
      <table id='datatable-buttons' class='table table-striped table-bordered'>
        <thead>
          <tr>
            <th>No.</th>
            <th>Nama Item</th>
            <th>Jumlah</th>
          </tr>
        </thead>
        <tbody>
<?php
    foreach ($item_array as $ia_key => $ia_value)
    {
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                $no = 0;
                $no++;
                echo "<tr>";
                echo "<td> $no </td>";
                echo "<td> $ia_key </td>";
                echo "<td> $ia_value </td>";
                $z++;
                echo "</tr>";
            }
        }
    }
?>
        </tbody>
      </table>
    </div>
  </div>
</div>
</code>```

Also, revise your logic. You're resetting $no every iteration, to then
increment it.

Title: How to make Table in PHP

Body:
I want to make table with this result (look Echo),  When I put it in the table it happens is all the results are not in one table but one result of one table.

foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "$ia_key($ia_value)";
                echo "
";
                $z++;
            }
        }
    }

I tried with this code. But the result is not in one table.

foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "
";
                    echo "
";
                        echo "

";
                        echo "
";
                            echo "
";
                            echo "
";
                                 echo "
";
                                    echo "
";
                                        echo "No.	";
                                        echo "Nama Item	";
                                        echo "Jumlah	";
                                    echo"
";
                                    echo "
";
                                    echo "
";
                                    $no = 0;
                                    $no++;
                                        echo "
";
                                            echo " $no 	";
                                            echo " $ia_key 	";
                                            echo " $ia_value 	";
                                            $z++;
                                        echo "
";
                                    echo "
";
                                echo "
";
                            echo "
";
                        echo "
";
                    echo "
";
                echo"
";
            }
        }
    }

Result of above code <== Click to view image.

Body:
You need to go revisit PHP basics. It is a template language, instead of
echoing out multiple  strings you can just close the  PHP tag (?>) and
write your desired  output there directly. Then reopen when  you need to
go back to PHP code (<?php).

As for your exact problem, that's because you echo the beginning and end
of each table  inside your loop, so it happens  multiple times. Instead,
you want to  start your table and  end it outside the loop,  and use the
loop to loop over what's repeated: lines.

<div class='row'>
  <div class='col-sm-12'>
    <h4 class='m-t-0 header-title'></h4>
    <div class='table-responsive m-b-20'>
      <p class='text-muted font-13 m-b-30'>
      <table id='datatable-buttons' class='table table-striped table-bordered'>
        <thead>
          <tr>
            <th>No.</th>
            <th>Nama Item</th>
            <th>Jumlah</th>
          </tr>
        </thead>
        <tbody>
<?php
    foreach ($item_array as $ia_key => $ia_value)
    {
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                $no = 0;
                $no++;
                echo "<tr>";
                echo "<td> $no </td>";
                echo "<td> $ia_key </td>";
                echo "<td> $ia_value </td>";
                $z++;
                echo "</tr>";
            }
        }
    }
?>
        </tbody>
      </table>
    </div>
  </div>
</div>

Also, revise your logic. You're resetting $no every iteration, to then
increment it.


问:
Error in my PDO execute function
I have the following query:

```<code>SELECT case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end
                     as cname ,cardid,card_type,isDeck,userid_from,status,cards.gibid,message ,userid_to,description,tagline,gibs.preview_thumb
                    ,case when  userid_from=userid_to then 'my card ' else 'other 'end as owner
            FROM cards LEFT JOIN gibs ON gibs.gibid=cards.gibid
                left join users on users.userid=cards.userid_from
            WHERE userid_to=? and cards.deleted='N'  and (case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'
            order by status,card_type desc,owner,cname,isDeck desc
</code>```

and array passed in execute function is :

```<code>Array
(
    [0] => 1
    [1] => rahul
)
</code>```

it is giving me error ..

```<code>Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/ryapi/Db.php on line 176

Fatal error: Uncaught exception 'PDOException' with message 'Database error [HY093]: , driver error code is ' in /var/www/ryapi/Db.php:179
Stack trace:
#0 /var/www/ryapi/Db.php(93): Db::_query('SELECT case whe...', Array)
#1 /var/www/ryapi/card.php(152): Db::getResult('SELECT case whe...', Array)
#2 /var/www/ryapi/index.php(103): Card->getcardlist('1', '', 'rahul')
#3 {main}
  thrown in /var/www/ryapi/Db.php on line 179
</code>```

why this error is coming please suggest.

答:
This is a simple error that can be fixed in your PHP. You have not included the PHP, so we can't tell.

You need to adjust the number of ? symbols in your pdo->prepare statement.

Title: Error in my PDO execute function

Body:
I have the following query:

SELECT case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end
                     as cname ,cardid,card_type,isDeck,userid_from,status,cards.gibid,message ,userid_to,description,tagline,gibs.preview_thumb
                    ,case when  userid_from=userid_to then 'my card ' else 'other 'end as owner
            FROM cards LEFT JOIN gibs ON gibs.gibid=cards.gibid
                left join users on users.userid=cards.userid_from
            WHERE userid_to=? and cards.deleted='N'  and (case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'
            order by status,card_type desc,owner,cname,isDeck desc

and array passed in execute function is :

Array
(
    [0] => 1
    [1] => rahul
)

it is giving me error ..

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/ryapi/Db.php on line 176

Fatal error: Uncaught exception 'PDOException' with message 'Database error [HY093]: , driver error code is ' in /var/www/ryapi/Db.php:179
Stack trace:
#0 /var/www/ryapi/Db.php(93): Db::_query('SELECT case whe...', Array)
#1 /var/www/ryapi/card.php(152): Db::getResult('SELECT case whe...', Array)
#2 /var/www/ryapi/index.php(103): Card->getcardlist('1', '', 'rahul')
#3 {main}
  thrown in /var/www/ryapi/Db.php on line 179

why this error is coming please suggest.


问:
How to create a selector ID from a variable
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1 <br>
<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2 <br>

<div id = "box1" style="display:none">Checkbox 1 is selected</div>
<div id = "box2" style="display:none">Checkbox 2 is selected</div></code>```

Can anyone please help me understand why the .toggle doesn't work correctly?

答:
The problem with the I condition in For is because there is no comparision value.  The easiest way for it to determine how much you have is by making an array:

```<code>var
   id = ['box1', 'box2'], //repeat til you get to 9
   checkbox = ['checkbox1', 'checkbox2'], //repeat til you get to 9
   frame = ""
;

for (i = 0; i < id.length; i++){
   frame +=
       "<div id=' " + box[i] + " '>"+
       checkbox[i] + "is selected</div>"
   ;
}

document.getElementById('demo').innerHTML = frame;
</code>```

Then your seperate script file (because it wont work in the same file!!!)

```<code>//your toggle events here
$('#alpha').toggle(function{
     $('#box1').show(0);
     $('#box2, #box3, #box4, #box5, #box6, #box7, #box8, #box9').hide(0);
});
//repeat til you get to 9
</code>```

My cloning result experience comes from the fiddle:
https://fiddle.jshell.net/NitroXAce/d1qro5g3/15/

Because I tried to make panels that do certain things but kept a 'template'.  In your example, you simply needed to clone your inputs and your display none divs.  Happy hunting!

Body:
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});

<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1

<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2

Checkbox 1 is selected

Checkbox 2 is selected

Can anyone please help me understand why the .toggle doesn't work correctly?

Body:
The problem with the I condition in For is because there is no comparision value.  The easiest way for it to determine how much you have is by making an array:

var
   id = ['box1', 'box2'], //repeat til you get to 9
   checkbox = ['checkbox1', 'checkbox2'], //repeat til you get to 9
   frame = ""
;

for (i = 0; i < id.length; i++){
   frame +=
       "<div id=' " + box[i] + " '>"+
       checkbox[i] + "is selected</div>"
   ;
}

document.getElementById('demo').innerHTML = frame;

Then your seperate script file (because it wont work in the same file!!!)

//your toggle events here
$('#alpha').toggle(function{
     $('#box1').show(0);
     $('#box2, #box3, #box4, #box5, #box6, #box7, #box8, #box9').hide(0);
});
//repeat til you get to 9

My cloning result experience comes from the fiddle:
https://fiddle.jshell.net/NitroXAce/d1qro5g3/15/

Because I tried to make panels that do certain things but kept a 'template'.  In your example, you simply needed to clone your inputs and your display none divs.  Happy hunting!


问:
Redirect for wordpress permalink
I'm trying to change the WordPress permalink structure in .htaccess from /%postname%/ to /%category%/%postname%/ any suggestions?

答:
If i'm not wrong, inside the settings on the "permalink" voice you can modify this last one.

Just remember to put the correct .htaccess inside your website:

https://codex.wordpress.org/htaccess

Usually to use correctly the permalink you have to use %postname% on the personalized structure.

Title: Redirect for wordpress permalink


问:
Blackberry eclipse debugger not reflecting code changes
I've been struggling with this for the past day. I seem to be stuck with a weird bug in Eclipse where it decides to step through and exec sections that I've entirely deleted or commented. It also chooses to ignore all the instructions that I've actually added today. I've tried removing all breakpoints, clearing my bin directory, resetting my emulator, but nothing works.

Any help is much appreciated!

Thanks,

Teja.

答:
I don't know if this is the solution to your problem but here are a few useful tips:

1.If you make changes to the code and save them while you have started the debugger i.e. have started Eclipse in Debug mode(Debug as...) the debugger won't recognize the changes. You have to recompile, repackage and then restart the debugger.

2.After making the changes to your code it isn't enough to just build the project. You also have to select the project and from the Project menu then Blackberry->Package Projects. After doing this try to start the debugger.

Hope this helps.


问:
Grey line and area in primary editor window in XCode
Does anybody know where this line and the grey area to the right of it comes from?

If it's just a bug, feel free to close this question!

答: That line is there to give you an impression on how long your lines should be. It's good practice to keep your code within a certain width, so its readable on different resolutions.</p>


问:
Recording audio mic in with Powershell
How can I record audio with the Mic In line with Powershell?

I am trying using the sound recorder, but even though I can open the program, I can't make it record and save a file.  Any help is appreciated.

Thanks

答:
I was able to get it to work by copying the .exe in the working directory and with the following code:</p>

```<code>$here = $PSScriptRoot
$path = $here+"\SoundRecorder.exe"
$filepath = $here+"\test2.wma"
$arg1 = "/FILE $filepath /DURATION 0000:00:10"
& $path $arg1
</code>```

Title: Recording audio mic in with Powershell

Body:
I was able to get it to work by copying the .exe in the working directory and with the following code:

$here = $PSScriptRoot
$path = $here+"\SoundRecorder.exe"
$filepath = $here+"\test2.wma"
$arg1 = "/FILE $filepath /DURATION 0000:00:10"
& $path $arg1


问:
Stringify behaves strangely when applied to a dictionary in Javascript
I am using a dictionary to register the statuses of a number of appliances and I would like to convert them to JSON to be archived.
This is the code I use to build the dictionary:

```<code>$scope.lastValues=[];
    for (var i in nomeImpianti) {
        var newValue={
            id: i,
                name: nomeImpianti[i],
            values:{
                value1: true,
                        value2: false,
                        value3: false
            }
        }
        $scope.lastValues[nomeImpianti[i]]=0;
    }
</code>```

Yet when I print the array it appears in the form:

[general: 0, motore 1: 0, motore 2: 0, impianto 1: 0, impianto 2:
  0...]

Instead of the form with the {} typical of javascript dictionaries.
In fact when I print is type in the console it is given as a closed 'object' while if I ask the type of something like:

```<code>var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
</code>```

it is:

Object {firstName: Array(2), lastName: Array(2)}

Consequently if I stringfy the json variable the correct string is created, while if I do it on my [] delimited structure it creates an empty.
How may I correctly handle a dictionary expressed as a {} delimited structure?

答:
The issue was simply due to how I initalized the variable. It was to be:

```<code>$scope.lastValues={};
</code>```

rather than:
    $scope.lastValues=[];

This latter form worked fine everywhere rather than when trying to stringfy it.

Body:
I am using a dictionary to register the statuses of a number of appliances and I would like to convert them to JSON to be archived.
This is the code I use to build the dictionary:

$scope.lastValues=[];
    for (var i in nomeImpianti) {
        var newValue={
            id: i,
                name: nomeImpianti[i],
            values:{
                value1: true,
                        value2: false,
                        value3: false
            }
        }
        $scope.lastValues[nomeImpianti[i]]=0;
    }

Yet when I print the array it appears in the form:

[general: 0, motore 1: 0, motore 2: 0, impianto 1: 0, impianto 2:
  0...]

Instead of the form with the {} typical of javascript dictionaries.
In fact when I print is type in the console it is given as a closed 'object' while if I ask the type of something like:

var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};

it is:

Object {firstName: Array(2), lastName: Array(2)}

Consequently if I stringfy the json variable the correct string is created, while if I do it on my [] delimited structure it creates an empty.
How may I correctly handle a dictionary expressed as a {} delimited structure?

Body:
The issue was simply due to how I initalized the variable. It was to be:

$scope.lastValues={};

rather than:
    $scope.lastValues=[];

This latter form worked fine everywhere rather than when trying to stringfy it.


问:
How to get the list of hosts listening on a particular Que in Celery?
In my project I have two ques. I would like to know list of all the workers listening to a que.
(need a pythonic way of doing this. Celery is running on a different machine and I want the details on other machine.)</p>

答:
Well if you're using rabbitmq as a broker you can do this:

```<code>sudo rabbitmqctl list_consumers
</code>```

To check a specific queue:

```<code>lpiner@host:~$ sudo rabbitmqctl list_consumers -p production |  grep queue1
queue1 <rabbit@host1-rabbitmq.2.15149.130>     None5   true    0       []
queue1 <rabbit@host1-rabbitmq.2.15256.130>     None4   true    0       []
queue1 <rabbit@host1-rabbitmq.2.21562.130>     None4   true    0       []
queue1 <rabbit@host1-rabbitmq.2.21644.130>     None4   true    0       []
queue1 <rabbit@host1-rabbitmq.2.6500.135>      None5   true    0       []
queue1 <rabbit@host2-rabbitmq.2.4028.137>      None10  true    0       []
queue1 <rabbit@host2-rabbitmq.2.4083.137>      None10  true    0       []
queue1 <rabbit@host2-rabbitmq.2.4463.137>      None9   true    0       []
queue1 <rabbit@host2-rabbitmq.2.4497.137>      None10  true    0       []
queue1 <rabbit@host2-rabbitmq.2.6508.137>      None5   true    0       []
</code>```

You can also use the celery flower UI which is pretty cool.
https://flower.readthedocs.io/en/latest/

Body:
Well if you're using rabbitmq as a broker you can do this:

sudo rabbitmqctl list_consumers

To check a specific queue:

lpiner@host:~$ sudo rabbitmqctl list_consumers -p production |  grep queue1
queue1 <rabbit@host1-rabbitmq.2.15149.130>     None5   true    0       []
queue1 <rabbit@host1-rabbitmq.2.15256.130>     None4   true    0       []
queue1 <rabbit@host1-rabbitmq.2.21562.130>     None4   true    0       []
queue1 <rabbit@host1-rabbitmq.2.21644.130>     None4   true    0       []
queue1 <rabbit@host1-rabbitmq.2.6500.135>      None5   true    0       []
queue1 <rabbit@host2-rabbitmq.2.4028.137>      None10  true    0       []
queue1 <rabbit@host2-rabbitmq.2.4083.137>      None10  true    0       []
queue1 <rabbit@host2-rabbitmq.2.4463.137>      None9   true    0       []
queue1 <rabbit@host2-rabbitmq.2.4497.137>      None10  true    0       []
queue1 <rabbit@host2-rabbitmq.2.6508.137>      None5   true    0       []

You can also use the celery flower UI which is pretty cool.
https://flower.readthedocs.io/en/latest/


问:
Aren't Python strings immutable? Then why does a + " " + b work?
My understanding was that Python strings are immutable.

I tried the following code:

```<code>a = "Dog"
b = "eats"
c = "treats"

print a, b, c
# Dog eats treats

print a + " " + b + " " + c
# Dog eats treats

print a
# Dog

a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!
</code>```

Shouldn't Python have prevented the assignment? I am probably missing something.

Any idea?

答:
You can make a numpy array immutable and use the first element:

```<code>numpyarrayname[0] = "write once"
</code>```

then:

```<code>numpyarrayname.setflags(write=False)
</code>```

or

```<code>numpyarrayname.flags.writeable = False
</code>```

Body:
My understanding was that Python strings are immutable.

I tried the following code:

a = "Dog"
b = "eats"
c = "treats"

print a, b, c
# Dog eats treats

print a + " " + b + " " + c
# Dog eats treats

print a
# Dog

a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!

Shouldn't Python have prevented the assignment? I am probably missing something.

Any idea?

Body:
You can make a numpy array immutable and use the first element:

numpyarrayname[0] = "write once"

then:

numpyarrayname.setflags(write=False)

or

numpyarrayname.flags.writeable = False


问:
VerifyError out of the blue. Help!
I'm the developer of ShellShock Live, a free online artillery game:
http://www.newgrounds.com/portal/view/564049

Everything has been running smoothly, but every once in a while for a period of 4 hours or so, hundreds of "VerifyError: Error #1026" will show up in my error log. Then, they will stop.

I looked into VerifyError and found that "The VerifyError class represents an error that occurs when a malformed or corrupted SWF file is encountered."  The SWF on Newgrounds is just small loader SWF that loads the full game SWF from another site, so there must be a problem there.  I'm stumped, because the game will run fine for days, and then just start getting these errors out of the blue, after no changes to either SWF.

ShellShock has hundreds of players online at any given moment, so I would like to fix this ASAP.  Any help would be appreciated! Thank you!

答:
I had this error in a very small project with cs3 flash9. So I was able to track this error down.

NOTE: this error is emitted incorrectly. The reason the error was emitted in my project was NOT because of a faulty swf because I do not import any swf into my project.

REASON:
I had a code line written like this:
_mc.my_counter && _mc.my_counter--;

SOLUTION:
I changed the line to this:
if(_mc.my_counter) _mc.my_counter--;

... and the verify error message was gone as fast as it appeared. Looks like this is a real as3 bug.

Title: VerifyError out of the blue. Help!


问:
Unit testing with Mocks. Test behaviour not implementation
I always had a problem when unit testing classes that calls other classes, for example I have a class that creates a new user from a phone-number then saves it to the database and sends a SMS to the number provided.

Like the code provided below.

```<code>public class UserRegistrationProcess : IUserRegistration
{
    private readonly IRepository _repository;
    private readonly ISmsService _smsService;

    public UserRegistrationProcess(IRepository repository, ISmsService smsService)
    {
        _repository = repository;
        _smsService = smsService;
    }

    public void Register(string phone)
    {
        var user = new User(phone);
        _repository.Save(user);
        _smsService.Send(phone, "Welcome", "Message!");
    }
}
</code>```

It is a really simple class but how would you go about and test it?

At the moment im using Mocks but I dont really like it

```<code>    [Test]
    public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase()
    {
        var repository = new Mock<IRepository>();
        var smsService = new Mock<ISmsService>();
        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        var phone = "07012345678";

        userRegistration.Register(phone);
        repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once());
    }

    [Test]
    public void WhenRegistreringANewUser_ItWillSendANewSms()
    {
        var repository = new Mock<IRepository>();
        var smsService = new Mock<ISmsService>();
        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        var phone = "07012345678";

        userRegistration.Register(phone);

        smsService.Verify(x => x.Send(phone, It.IsAny<string>(), It.IsAny<string>()), Times.Once());
    }
</code>```

It feels like I am testing the wrong thing here?

Any thoughts on how to make this better?

答:
In your case don't need to write

```<code>  repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once());
</code>```

because this method doesn't return a value
you can write

```<code>repository.VerifyAll();
</code>```

Also for smsService it's a good way to use Moq.

Body:
I always had a problem when unit testing classes that calls other classes, for example I have a class that creates a new user from a phone-number then saves it to the database and sends a SMS to the number provided.

Like the code provided below.

public class UserRegistrationProcess : IUserRegistration
{
    private readonly IRepository _repository;
    private readonly ISmsService _smsService;

    public UserRegistrationProcess(IRepository repository, ISmsService smsService)
    {
        _repository = repository;
        _smsService = smsService;
    }

    public void Register(string phone)
    {
        var user = new User(phone);
        _repository.Save(user);
        _smsService.Send(phone, "Welcome", "Message!");
    }
}

It is a really simple class but how would you go about and test it?

At the moment im using Mocks but I dont really like it

    [Test]
    public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase()
    {
        var repository = new Mock<IRepository>();
        var smsService = new Mock<ISmsService>();
        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        var phone = "07012345678";

        userRegistration.Register(phone);
        repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once());
    }

    [Test]
    public void WhenRegistreringANewUser_ItWillSendANewSms()
    {
        var repository = new Mock<IRepository>();
        var smsService = new Mock<ISmsService>();
        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        var phone = "07012345678";

        userRegistration.Register(phone);

        smsService.Verify(x => x.Send(phone, It.IsAny<string>(), It.IsAny<string>()), Times.Once());
    }

It feels like I am testing the wrong thing here?

Any thoughts on how to make this better?

Body:
In your case don't need to write

  repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once());

because this method doesn't return a value
you can write

repository.VerifyAll();

Also for smsService it's a good way to use Moq.


问:
How to view the source code of a .mex file
I saw online that you can just use edit rgb2gray to open up the source file, but I ran into another function in the rgb2gray.m file that I don't know how to view.

Lines 54-55 contain the following function:

```<code>if threeD
  I = images.internal.rgb2graymex(X);
</code>```

How do I view the source code for this rgb2graymex function?

答:
rgb2graymex is, as its name suggests, a .mex file. .mex files are pre-compiled files which you thus cannot view the contents of, unless you use exotic decompilers (which usually don't give a 100% result), or obtain the source code from the one who's written it, which is not going to happen with proprietary code.

Read more on MEX files on the MathWorks site.

Body:
I saw online that you can just use edit rgb2gray to open up the source file, but I ran into another function in the rgb2gray.m file that I don't know how to view.

Lines 54-55 contain the following function:

if threeD
  I = images.internal.rgb2graymex(X);

How do I view the source code for this rgb2graymex function?


问:
How to link commands between user control and main in MVVM
I have a user control which have one TextBox and one Button called View. The TextBox takes index values.

On my Main view, I have one list view which will display all lines in a file.
An ObservableCollection is Bind to this.

What I need is, when index value is entered in the TextBox and View Button is clicked(in the user control), the SelecedIndex of the ListView(in the Main) should be changed to the index value.

How can I achieve this using MVVM?

Also, Please provide the proper approach to do this if I am doing it wrong.

Here is my UserControl Code:

XAML

```<code><UserControl.DataContext>
    <VM:IndexView_VM ></VM:IndexView_VM>
</UserControl.DataContext>
<Grid Background="White">
    <TextBlock Margin="10,12,168,9" Text="Index : "/>
    <TextBox Text="{Binding Index}" x:Name="TB_Index" Margin="53,11,90,8" />
    <Button Command="{Binding View_CMD}" x:Name="BT_View" Content="View" Margin="136,11,10,8" />
</Grid>
</code>```

ViewModel

```<code>public class IndexView_VM : ViewModelBase
{
    public IndexView_VM()
    {
        View_CMD = new RelayCommand(_View_CMD);
    }

    int _Index;
    public int Index
    {
        get { return _Index; }
        set
        {
            _Index = value;
            RaisePropertyChanged();
        }
    }

    public RelayCommand View_CMD { get; set; }
    internal void _View_CMD(object Parameter)
    {
        // What to write here?
    }
}
</code>```

Here is the Main View:

XAML

```<code><UserControl.DataContext>
        <VM:MainView_VM></VM:MainView_VM>
    </UserControl.DataContext>
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="111*"/>
            <ColumnDefinition Width="100*"/>
        </Grid.ColumnDefinitions>
        <StackPanel>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
        </StackPanel>
        <ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1" >
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Data" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</code>```

View Model

```<code>public class MainView_VM : ViewModelBase
{
    public MainView_VM()
    {
        ReadFile();
    }

    public ObservableCollection<string> FileData { get; set; }

    void ReadFile()
    {
        //I will read file here.
    }
}
</code>```

答:
If you are using MvvmLight, you could for example use the Messenger class to send a message from the child view model to the parent:

IndexView_VM:

```<code>internal void _View_CMD(object Parameter)
{
    GalaSoft.MvvmLight.Messaging.Messenger.Default.Send(_Index);
}
</code>```

MainView_VM:

```<code>public class MainView_VM : ViewModelBase
{
    public MainView_VM()
    {
        ReadFile();
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<int>(this, index => Index = index);
    }

    public ObservableCollection<string> FileData { get; set; }

    int _Index;
    public int Index
    {
        get { return _Index; }
        set
        {
            _Index = value;
            RaisePropertyChanged();
        }
    }

    void ReadFile()
    {
        //I will read file here.
    }
}
</code>```

MainView:

```<code><ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1"
          SelectedIndex="{Binding Index}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Data" Width="100"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

Please refer to Laurent Bugnion's MSDN Magazine article for more information about the Messenger.

MVVM - Messenger and View Services in MVVM: https://msdn.microsoft.com/en-us/magazine/jj694937.aspx

Body:
I have a user control which have one TextBox and one Button called View. The TextBox takes index values.

On my Main view, I have one list view which will display all lines in a file.
An ObservableCollection is Bind to this.

What I need is, when index value is entered in the TextBox and View Button is clicked(in the user control), the SelecedIndex of the ListView(in the Main) should be changed to the index value.

How can I achieve this using MVVM?

Also, Please provide the proper approach to do this if I am doing it wrong.

Here is my UserControl Code:

XAML

<UserControl.DataContext>
    <VM:IndexView_VM ></VM:IndexView_VM>
</UserControl.DataContext>
<Grid Background="White">
    <TextBlock Margin="10,12,168,9" Text="Index : "/>
    <TextBox Text="{Binding Index}" x:Name="TB_Index" Margin="53,11,90,8" />
    <Button Command="{Binding View_CMD}" x:Name="BT_View" Content="View" Margin="136,11,10,8" />
</Grid>

ViewModel

public class IndexView_VM : ViewModelBase
{
    public IndexView_VM()
    {
        View_CMD = new RelayCommand(_View_CMD);
    }

    int _Index;
    public int Index
    {
        get { return _Index; }
        set
        {
            _Index = value;
            RaisePropertyChanged();
        }
    }

    public RelayCommand View_CMD { get; set; }
    internal void _View_CMD(object Parameter)
    {
        // What to write here?
    }
}

Here is the Main View:

XAML

<UserControl.DataContext>
        <VM:MainView_VM></VM:MainView_VM>
    </UserControl.DataContext>
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="111*"/>
            <ColumnDefinition Width="100*"/>
        </Grid.ColumnDefinitions>
        <StackPanel>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
        </StackPanel>
        <ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1" >
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Data" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

View Model

public class MainView_VM : ViewModelBase
{
    public MainView_VM()
    {
        ReadFile();
    }

    public ObservableCollection<string> FileData { get; set; }

    void ReadFile()
    {
        //I will read file here.
    }
}

Body:
If you are using MvvmLight, you could for example use the Messenger class to send a message from the child view model to the parent:

IndexView_VM:

internal void _View_CMD(object Parameter)
{
    GalaSoft.MvvmLight.Messaging.Messenger.Default.Send(_Index);
}

MainView_VM:

public class MainView_VM : ViewModelBase
{
    public MainView_VM()
    {
        ReadFile();
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<int>(this, index => Index = index);
    }

    public ObservableCollection<string> FileData { get; set; }

    int _Index;
    public int Index
    {
        get { return _Index; }
        set
        {
            _Index = value;
            RaisePropertyChanged();
        }
    }

    void ReadFile()
    {
        //I will read file here.
    }
}

MainView:

<ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1"
          SelectedIndex="{Binding Index}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Data" Width="100"/>
        </GridView>
    </ListView.View>
</ListView>

Please refer to Laurent Bugnion's MSDN Magazine article for more information about the Messenger.

MVVM - Messenger and View Services in MVVM: https://msdn.microsoft.com/en-us/magazine/jj694937.aspx


问:
HTML - refresh page after inactivity
I am having a touch screen with some very basic html pages. But if there is no activity for maybe 5 minutes, it should reload the main page again.

So it is not just a refresh of the site, but a load of the main page if there is no activity

just a question Where does the script know which site is the main page ?. If someone goes to "site B" - it should after some minutes without any movement move back to "site A"

答:
You would need to use JavaScript.  There is a The jQuery idletimer plugin at
http://paulirish.com/2009/jquery-idletimer-plugin/

Example:

```<code>// idleTimer() takes an optional argument that defines the idle timeout
// timeout is in milliseconds; defaults to 30000
$.idleTimer(10000);

$(document).bind("idle.idleTimer", function(){
 // function you want to fire when the user goes idle
});

$(document).bind("active.idleTimer", function(){
 // function you want to fire when the user becomes active again
});

// pass the string 'destroy' to stop the timer
$.idleTimer('destroy');
</code>```

Reference:
How to change a page location after inactivity of 5 mins

Title: HTML - refresh page after inactivity

Body:
You would need to use JavaScript.  There is a The jQuery idletimer plugin at
http://paulirish.com/2009/jquery-idletimer-plugin/

Example:

// idleTimer() takes an optional argument that defines the idle timeout
// timeout is in milliseconds; defaults to 30000
$.idleTimer(10000);

$(document).bind("idle.idleTimer", function(){
 // function you want to fire when the user goes idle
});

$(document).bind("active.idleTimer", function(){
 // function you want to fire when the user becomes active again
});

// pass the string 'destroy' to stop the timer
$.idleTimer('destroy');

Reference:
How to change a page location after inactivity of 5 mins