问:
Why 'await' requires 'async' in function definition
I'm currently learning Dart, but this is also applicable to what's going on in the JavaScript world right now, and it seems like C# also uses the same pattern.

In Dart, any function that uses await must itself be labeled asynchronous through async as follows:

```<code>import "dart:html";

main() async {
  var context = querySelector("canvas").context2D;
  var running = true;

  while (running) {
    var time = await window.animationFrame;
    ...
  }
}
</code>```

This does not make sense to me. If a function is waiting on an asynchronous function to complete, is it not then considered blocking? Why do JS and Dart require it to be labeled asynchronous? Would it not be the opposite?

To me it would make far more sense if the calling function must use the async keyword if it calls any function that also includes it in its definition. In this pattern, await would be used to convert asynchronous functions to synchronous ones.

This way would also avoid duplicate functions, since right now, libraries seem to always have func() and funcSync() or funcAsync().

答: I'm not sure what your question has to do with C# but await is a most unfortunate keyword choice in C#. await is more understandable if you read it as resume after or even yield then resume after. When execution encounters await, it suspends the current function, returning to its caller. Once the Task being waited on is done, execution resumes after the await when the caller needs the result (from an await expression of its own).

Body:
I'm currently learning Dart, but this is also applicable to what's going on in the JavaScript world right now, and it seems like C# also uses the same pattern.

In Dart, any function that uses await must itself be labeled asynchronous through async as follows:

import "dart:html";

main() async {
  var context = querySelector("canvas").context2D;
  var running = true;

  while (running) {
    var time = await window.animationFrame;
    ...
  }
}

This does not make sense to me. If a function is waiting on an asynchronous function to complete, is it not then considered blocking? Why do JS and Dart require it to be labeled asynchronous? Would it not be the opposite?

To me it would make far more sense if the calling function must use the async keyword if it calls any function that also includes it in its definition. In this pattern, await would be used to convert asynchronous functions to synchronous ones.

This way would also avoid duplicate functions, since right now, libraries seem to always have func() and funcSync() or funcAsync().


来源: stackexchange

问:
Schema changes not updating in Intellisense in SQL 2008 (SSMS)
I've notice an issue - it feels like a bug but I suspect a 'feature' - in SSMS in SQL Server 2008.

I have various tabs open, for example an alter table script in one table and a SProc that queries that table in another tab, and when I execute my Alter Table script the changes are not reflected in Intellisense in the other tab.

I can create new queries and the changes are still not reflected in Intellisense. If I open a new SSMS instance, the changes are reflected, until I make further changes, of course.

However, if you over-rule Intellisense and push ahead with your modified tables and code, everything compiles without a grumble (as expected).

Is this a bug? A feature? Is there a setting somewhere that alters this behaviour? I checked in the options but couldn't see anything

答: Well done raising the issue - I have it frequently in VS 2008 SP1 but there coding the right name still produces an error squigly until the refresh happens - and I can't get it to do so at the moment.  I suspect I need another shutdown/reload.</p>

OwnerDisplayName: CJM

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: CJM

OwnerDisplayName: Vb user


问:
Delphi Translating Strings
I'm using Delphi 2007 and I wonder how the following problem can be solved:

I have to translate AComp.Caption for example, but the string that I want to assign to the caption, often depends on some data (for example a date or a number, that gets Formatted). Therefore I have to save the data and the string in a new variable for every translation, which is really annoying.

What I want to do is something like that:

```<code>// will add the string and data to an internal list of Translator
// and will then return a DynamicString, which represents the translated value
AComp.Caption := T.NewTranslatedString("Hello %s, do you like cheese?", User)
</code>```

(Note that AComp.Caption ("Hello %s..") can be changed in different methods)

When switching to another language, you would call T.TranslateAgain() and the value of all strings will be translated and, if data given, formatted again.

Is this possible or do you know another way for solving the given problem?

Thanks in advance

Additional question:
Are strings normal objects, that I can subclass and add dynamic behaviour that changes the string itself in special cases?

答:
You can use Delphi's own translator tool. It is able to extract strings and resourcestrings from your source code and form DFM files, and gives you a graphical user interface to translate them to any language. It then creates a resource DLL for each language. The DLL containing the translated strings and DFM data. You should deploy this translation DLL with your project to the destination machine.

In your case, your strings are divided into two groups; fixed strings which do not need any further processing, and parametrized strings which need some additional data to be formatted properly. For the fixed strings, you can just type in the translation into translator tool. For parametrized strings, save each one as a resourcestring and use the resourcestring for formatting them. For example:

```<code>resourcestring
  strDoYouLikeCheese = 'Hello %s, do you like cheese?';

...

AComp.Caption := Format(strDoYouLikeCheese,[User]);
</code>```

Now you can use the translator tool or any resource editor to translate the resourcestring into your desired language without the need for changing your source code or recompiling it.

Title: Delphi Translating Strings

Body:
I'm using Delphi 2007 and I wonder how the following problem can be solved:

I have to translate AComp.Caption for example, but the string that I want to assign to the caption, often depends on some data (for example a date or a number, that gets Formatted). Therefore I have to save the data and the string in a new variable for every translation, which is really annoying.

What I want to do is something like that:

// will add the string and data to an internal list of Translator
// and will then return a DynamicString, which represents the translated value
AComp.Caption := T.NewTranslatedString("Hello %s, do you like cheese?", User)

(Note that AComp.Caption ("Hello %s..") can be changed in different methods)

When switching to another language, you would call T.TranslateAgain() and the value of all strings will be translated and, if data given, formatted again.

Is this possible or do you know another way for solving the given problem?

Thanks in advance

Additional question:
Are strings normal objects, that I can subclass and add dynamic behaviour that changes the string itself in special cases?

Body:
You can use Delphi's own translator tool. It is able to extract strings and resourcestrings from your source code and form DFM files, and gives you a graphical user interface to translate them to any language. It then creates a resource DLL for each language. The DLL containing the translated strings and DFM data. You should deploy this translation DLL with your project to the destination machine.

In your case, your strings are divided into two groups; fixed strings which do not need any further processing, and parametrized strings which need some additional data to be formatted properly. For the fixed strings, you can just type in the translation into translator tool. For parametrized strings, save each one as a resourcestring and use the resourcestring for formatting them. For example:

resourcestring
  strDoYouLikeCheese = 'Hello %s, do you like cheese?';

...

AComp.Caption := Format(strDoYouLikeCheese,[User]);

Now you can use the translator tool or any resource editor to translate the resourcestring into your desired language without the need for changing your source code or recompiling it.


问:
python pandas filter and aggregate multiple columns and write into CSV
I want to read a CSV file and count / aggregate on multiple columns

My input data is as follows

```<code>unique_identifier,date,flag1,flag2,flag3
a1,7/1/2017,FALSE,TRUE,FALSE
a2,7/1/2017,FALSE,TRUE,FALSE
a3,7/1/2017,FALSE,TRUE,FALSE
a4,7/1/2017,TRUE,FALSE,FALSE
a5,7/1/2017,FALSE,FALSE,FALSE
a6,7/2/2017,FALSE,FALSE,TRUE
a7,7/2/2017,FALSE,FALSE,TRUE
a8,7/2/2017,FALSE,TRUE,FALSE
q9,7/2/2017,FALSE,TRUE,TRUE
</code>```

Am new to pandas and so far by reading various questions here looks like I need to use one or more of set_index(), .append(), , .join(), .agg()

I have the individual results but cannot get the new results I want.

```<code>import pandas as pd

df = pd.read_csv("flagdata.csv")

print (df["date"].value_counts())

df_flag1 = df[df.flag1 == True]
df_flag1  = df_flag1["date"].value_counts()
print (df_flag1)

df_flag2 = df[df.flag2 == True]
df_flag2 = df_flag2["date"].value_counts()
print (df_flag2)

df_flag3 = df[df.flag3 == True]
df_flag3 = df_flag3["date"].value_counts()
print (df_flag3)
</code>```

I want to get a count of True Flags for each date to create a new csv file with the following result - date, total count, flag1 true count, flag2 true count, flag3 true count

```<code>date,count,flag1,flag2,flag3
7/1/2017,5,1,3,0
7/2/2017,4,0,2,3
</code>```

答:
You need to group the rows by date and count and sum the flags:</p>

```<code>result = pd.concat([df.groupby('date').count()['flag1'],
                    df.groupby('date').sum()],
                    axis=1).astype(int)
result.columns = ['count'] + result.columns[1:].tolist()
#          count  flag1  flag2  flag3
#date
#7/1/2017      5      1      3      0
#7/2/2017      4      0      2      3

result.to_csv('output.csv')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to read a CSV file and count / aggregate on multiple columns

My input data is as follows

unique_identifier,date,flag1,flag2,flag3
a1,7/1/2017,FALSE,TRUE,FALSE
a2,7/1/2017,FALSE,TRUE,FALSE
a3,7/1/2017,FALSE,TRUE,FALSE
a4,7/1/2017,TRUE,FALSE,FALSE
a5,7/1/2017,FALSE,FALSE,FALSE
a6,7/2/2017,FALSE,FALSE,TRUE
a7,7/2/2017,FALSE,FALSE,TRUE
a8,7/2/2017,FALSE,TRUE,FALSE
q9,7/2/2017,FALSE,TRUE,TRUE

Am new to pandas and so far by reading various questions here looks like I need to use one or more of set_index(), .append(), , .join(), .agg()

I have the individual results but cannot get the new results I want.

import pandas as pd

df = pd.read_csv("flagdata.csv")

print (df["date"].value_counts())

df_flag1 = df[df.flag1 == True]
df_flag1  = df_flag1["date"].value_counts()
print (df_flag1)

df_flag2 = df[df.flag2 == True]
df_flag2 = df_flag2["date"].value_counts()
print (df_flag2)

df_flag3 = df[df.flag3 == True]
df_flag3 = df_flag3["date"].value_counts()
print (df_flag3)

I want to get a count of True Flags for each date to create a new csv file with the following result - date, total count, flag1 true count, flag2 true count, flag3 true count

date,count,flag1,flag2,flag3
7/1/2017,5,1,3,0
7/2/2017,4,0,2,3

Body:
You need to group the rows by date and count and sum the flags:

result = pd.concat([df.groupby('date').count()['flag1'],
                    df.groupby('date').sum()],
                    axis=1).astype(int)
result.columns = ['count'] + result.columns[1:].tolist()
#          count  flag1  flag2  flag3
#date
#7/1/2017      5      1      3      0
#7/2/2017      4      0      2      3

result.to_csv('output.csv')


问:
What is Best way for Replace with More Performance Using C?
I want to write good function with utf8 support for Better Performance.

I did in-depth research and found the following Replace() candidates:

```<code>char* replace(char* orig, char* rep, char* with)
{
  //33-34
    char* result; // the return string
    char* ins;    // the next insert point
    char* tmp;    // varies
    size_t len_rep;  // length of rep
    size_t len_with; // length of with
    size_t len_front; // distance between rep and end of last rep
    int count;    // number of replacements
    /* char* strstr(char const* s1, char const* s2);
    retourne un pointeur vers la première occurrence de s2 dans s1
    (ou NULL si s2 n’est pas incluse dans s1). */
    if (!orig)
        return NULL;
    if (!rep || !(len_rep = strlen(rep)))
        return NULL;
    if (!(ins = strstr(orig, rep)))
        return NULL;
    if (!with)
        with = "";
    len_with = strlen(with);
    /*  {   initialisation;
            while (condition) {
                Instructions
                mise_à_jour;
        } }*/
    // compte le nombre d'occurences de la chaîne à remplacer
    for (count = 0; (tmp = strstr(ins, rep)); ++count) {
        ins = tmp + len_rep;
    }
    // allocation de mémoire pour la nouvelle chaîne
    tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
    if (!result)
        return NULL;
    /* char* strcpy(char* dest, char const* src);
    copie la chaîne src dans la chaîne dest. Retourne dest.
    Attention ! aucune vérification de taille n’est effectuée ! */

    /* char* strncpy(char* dest, char const* src, size_t n);
    copie les n premiers caractères de src dans dest. Retourne dest.
    Attention ! n’ajoute pas le '\0' à la fin si src contient plus de n
    caractères !*/
    // from here on,
    //    tmp points to the end of the result string
    //    ins points to the next occurrence of rep in orig
    //    orig points to the remainder of orig after "end of rep"
    while (count--) { // count évaluée, puis incrémentée
    // donc ici tant que count est > 0
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;
}

char* replace8(char *str, char *old,char *new)
{
  //1.2 :||||||||||
  int i, count = 0;
  int newlen = strlen(new);
  int oldlen = strlen(old);
  for (i = 0; str[i]; ++i)
    if (strstr(&str[i], old) == &str[i])
      ++count, i += oldlen - 1;
  char *ret = (char *) calloc(i + 1 + count * (newlen - oldlen), sizeof(char));
  if (!ret) return "";
  i = 0;
  while (*str)
    if (strstr(str, old) == str)
      strcpy(&ret[i], new),
      i += newlen,
      str += oldlen;
    else
      ret[i++] = *str++;
  ret[i] = '\0';
  return ret;
}

char *replace7(char *orig, char *rep, char *with)
{
  //33-34-35
    char *result; // the return string
    char *ins;    // the next insert point
    char *tmp;    // varies
    int len_rep;  // length of rep
    int len_with; // length of with
    int len_front; // distance between rep and end of last rep
    int count;    // number of replacements
    if (!orig)
    {
        return NULL;
    }
    if (!rep)
    {
        rep = "";
    }
    len_rep = strlen(rep);
    if (!with)
    {
        with = "";
    }
    len_with = strlen(with);

    ins = orig;
    for (count = 0; tmp = strstr(ins, rep); ++count)
    {
        ins = tmp + len_rep;
    }
    // first time through the loop, all the variable are set correctly
    // from here on,
    //    tmp points to the end of the result string
    //    ins points to the next occurrence of rep in orig
    //    orig points to the remainder of orig after "end of rep"
    tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
    if (!result)
    {
        return NULL;
    }
    while (count--)
    {
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;
}

char *replace6(char *st, char *orig, char *repl)
{
  //17-18
  static char buffer[4000];
  char *ch;
  if (!(ch = strstr(st, orig)))
   return st;
  strncpy(buffer, st, ch-st);
  buffer[ch-st] = 0;
  sprintf(buffer+(ch-st), "%s%s", repl, ch+strlen(orig));
  return buffer;
}

char* replace3(char* s, char* term, char* new_term)
{
  //error
    char *nw = NULL, *pos;
    char *cur = s;
    while(pos = strstr(cur, term))
    {
        nw = (char*)realloc(nw, pos - cur + strlen(new_term));
        strncat(nw, cur, pos-cur);
        strcat(nw, new_term);
        cur = pos + strlen(term);
    }
    strcat(nw, cur);
    free(s);
    return nw;
}

char *replace2(char *original,char *pattern,char *replacement)
{
  //34-37
  size_t replen = strlen(replacement);
  size_t patlen = strlen(pattern);
  size_t orilen = strlen(original);
  size_t patcnt = 0;
  char * oriptr;
  char * patloc;
  // find how many times the pattern occurs in the original string
  for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
  {
    patcnt++;
  }
  {
    // allocate memory for the new string
    size_t retlen = orilen + patcnt * (replen - patlen);
    char * const returned = (char *) malloc( sizeof(char) * (retlen + 1) );
    if (returned != NULL)
    {
      // copy the original string,
      // replacing all the instances of the pattern
      char * retptr = returned;
      for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
      {
        size_t skplen = patloc - oriptr;
        // copy the section until the occurence of the pattern
        strncpy(retptr, oriptr, skplen);
        retptr += skplen;
        // copy the replacement
        strncpy(retptr, replacement, replen);
        retptr += replen;
      }
      // copy the rest of the string.
      strcpy(retptr, oriptr);
    }
    return returned;
  }
}

char *replace4(char *string, char *oldpiece, char *newpiece)
{
  //20-21
   int str_index, newstr_index, oldpiece_index, end,
   new_len, old_len, cpy_len;
   char *c;
   static char newstring[10000];
   if ((c = (char *) strstr(string, oldpiece)) == NULL)
      return string;
   new_len        = strlen(newpiece);
   old_len        = strlen(oldpiece);
   //str            = strlen(string);
   end            = strlen(string) - old_len;
   //int count;
   //for (count = 0; (strstr(oldpiece, newpiece)); ++count){}
   //newstring = malloc(str + (old_len - new_len) * count + 1);

   oldpiece_index = c - string;
   newstr_index = 0;
   str_index = 0;
   while(str_index <= end && c != NULL)
   {
      /* Copy characters from the left of matched pattern occurence */
      cpy_len = oldpiece_index-str_index;
      strncpy(newstring+newstr_index, string+str_index, cpy_len);
      newstr_index += cpy_len;
      str_index    += cpy_len;
      /* Copy replacement characters instead of matched pattern */
      ///*newstring=realloc(newstring,sizeof(newstring)+new_len+old_len+end+newstr_index);
      strcpy(newstring+newstr_index, newpiece);
      newstr_index += new_len;
      str_index    += old_len;
      /* Check for another pattern match */
      if((c = (char *) strstr(string+str_index, oldpiece)) != NULL)
         oldpiece_index = c - string;
   }
   /* Copy remaining characters from the right of last matched pattern */
   strcpy(newstring+newstr_index,
  string+str_index);
  return newstring;
}

char *replace5(char *orig, char *rep, char *with)
{
  //32-33-35
  char *result;
  char *ins;
  char *tmp;
  int len_rep;
  int len_with;
  int len_front;
  int count;
  if (!orig)
      return NULL;
  if (!rep)
      rep = "";
  len_rep = strlen(rep);
  if (!with)
      with = "";
  len_with = strlen(with);
  ins = orig;
  for (count = 0; (tmp = strstr(ins, rep)); ++count) {
      ins = tmp + len_rep;
  }
  tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
  if (!result)
      return NULL;
  while (count--) {
      ins = strstr(orig, rep);
      len_front = ins - orig;
      tmp = strncpy(tmp, orig, len_front) + len_front;
      tmp = strcpy(tmp, with) + len_with;
      orig += len_front + len_rep;
  }
  strcpy(tmp, orig);
  return result;
}
</code>```

replace4() and replace6() is fast from other, but not malloc,realloc.

Replace() Performance Tests

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <assert.h>
#include <stdint.h>
#include <sys/stat.h>
#include <stdarg.h>
char *temp;
int main()
{
  for(int current=1;current<=80000;current++)
  {
    temp=/*replace6*//*replace3*/replace4("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890","0","black");
    //printf("%s",temp);
  }
  return 0;
}
</code>```

How can I make a better replace() function?

Can I add malloc,realloc to replace4() or replace6() ?

答:
Very like none of your presented solutions is the fastest you can write for a balanced performance comparison.

First of all there are a couple of points regarding function 4 and 6:

they are not re-entrant, since they use a function-static buffer

obviously they don't work above a certain input-size

if you do not need re-entrant functions they provide the fastest memory allocation, because they cost nothing after the first call

if you do not copy the result the next call will overwrite it, although the pointer will remain valid, probably leading to strange bugs

function 6 furthermore only seems to replace one occurence

Function 3 will very likely perform worse than the others, because it will allocate memory more than once, with the possible exception of it being faster in case the buffer is already large enough for the result and might do nothing.

For the remaining functions, I note that they follow this structural pattern:

scan over the input to count the number of pattern occurrences

allocate sufficient memory for the output

copy input to output while replacing the character you want to substitute

as a side-note: they seem to do different checks on the input, and I have not checked which ones check all common corner cases, but function 8 e.g. does no NULL-checks at all, which may be the right thing in case you trust your inputs, or it is just flat out ub. You would not want to sacrifice correctness.

It is probably easier at this point to divide and conquer and solve these independently, because the memory allocation is likely going to account for a substantial part of the cost of a call. Thus it is unclear, if you can gain anything, by e.g. iterating over parts of the string doing a replace on cache-sized chunks of the input and estimating the total size using a heuristic after the first block. Using a heuristic for the allocation may however be OK, but you will have to balance costly re-allocations/copies against wasting memory.

Regarding 1. I would say that you cannot avoid a full-length scan if you actually want to know the exact amount of memory you need, and from personal experience and SO I would say strstr is typically very fast. I would expect low returns from optimizing here.

Part 3. is similar in this regard, as using the c std-lib copy functions is probably going to result in the compiler using some hand-crafted assembly that destroys everything you can write.

The second step however can be optimized well in my opinion:

First of all note that it is possible to do an inplace substring-replace if the replacement is no longer than the sequence to replace

Second, a caller might pass in a buffer that is larger than the string it contains, in which case the input-buffer may already be sufficiently large

Third, a caller might have alternative means (e.g. a memory pool) that allows him to do a faster allocation, if you allow him to pass in the output buffer

That means that if you provide a call that allows the caller to pass in the buffer, you may end up faster.

You can therefore implement 1. as a function which counts the number of occurrences of a pattern in a string (very likely quite useful on its own), 2. can be done by the user, and 3. can be a function that assumes it receives a sufficiently large output buffer. If you feel like you want the convenience of doing one call, you can just use these functions internally in a 4th helper, although you would probably want to at least check the size of the input and work in-place in case you can.

Regarding your tests, you are currently doing just one check which covers a VERY simple case. If you want to test the performance of a call in a meaningful way you should consider at least the following:

Look at the dimensions that influence the performance of the algorithm such as:

size of the input-string

size of the sequence to replace

size of the sequence to replace with

check especially how performance changes when crossing L1/L2 cache limits and page-size multiples

Do a couple of iterations before the timing to warm up (branch-predict etc.)

Operate on random sequences simply ensuring their dimensional properties to prevent impacting the caching behavior, because you operate on the same 100000 times

Collect enough samples to eliminate the impact of outliers (I think you are fine on that part with 80k iterations)

Keep measurements for the different dimensions separate initially, look at them independent, only then fuse them to get an overall picture

Ultimately, know that you can look at the assembly and try to improve it, if you REALLY know what you do. Also, if you can rule out certain cases, because you know you work in a special subspace of the general problem domain, that is frequently where you can gain most by doing a special solution just for your case.

Body:
I want to write good function with utf8 support for Better Performance.

I did in-depth research and found the following Replace() candidates:

char* replace(char* orig, char* rep, char* with)
{
  //33-34
    char* result; // the return string
    char* ins;    // the next insert point
    char* tmp;    // varies
    size_t len_rep;  // length of rep
    size_t len_with; // length of with
    size_t len_front; // distance between rep and end of last rep
    int count;    // number of replacements
    /* char* strstr(char const* s1, char const* s2);
    retourne un pointeur vers la première occurrence de s2 dans s1
    (ou NULL si s2 n’est pas incluse dans s1). */
    if (!orig)
        return NULL;
    if (!rep || !(len_rep = strlen(rep)))
        return NULL;
    if (!(ins = strstr(orig, rep)))
        return NULL;
    if (!with)
        with = "";
    len_with = strlen(with);
    /*  {   initialisation;
            while (condition) {
                Instructions
                mise_à_jour;
        } }*/
    // compte le nombre d'occurences de la chaîne à remplacer
    for (count = 0; (tmp = strstr(ins, rep)); ++count) {
        ins = tmp + len_rep;
    }
    // allocation de mémoire pour la nouvelle chaîne
    tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
    if (!result)
        return NULL;
    /* char* strcpy(char* dest, char const* src);
    copie la chaîne src dans la chaîne dest. Retourne dest.
    Attention ! aucune vérification de taille n’est effectuée ! */

    /* char* strncpy(char* dest, char const* src, size_t n);
    copie les n premiers caractères de src dans dest. Retourne dest.
    Attention ! n’ajoute pas le '\0' à la fin si src contient plus de n
    caractères !*/
    // from here on,
    //    tmp points to the end of the result string
    //    ins points to the next occurrence of rep in orig
    //    orig points to the remainder of orig after "end of rep"
    while (count--) { // count évaluée, puis incrémentée
    // donc ici tant que count est > 0
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;
}

char* replace8(char *str, char *old,char *new)
{
  //1.2 :||||||||||
  int i, count = 0;
  int newlen = strlen(new);
  int oldlen = strlen(old);
  for (i = 0; str[i]; ++i)
    if (strstr(&str[i], old) == &str[i])
      ++count, i += oldlen - 1;
  char *ret = (char *) calloc(i + 1 + count * (newlen - oldlen), sizeof(char));
  if (!ret) return "";
  i = 0;
  while (*str)
    if (strstr(str, old) == str)
      strcpy(&ret[i], new),
      i += newlen,
      str += oldlen;
    else
      ret[i++] = *str++;
  ret[i] = '\0';
  return ret;
}

char *replace7(char *orig, char *rep, char *with)
{
  //33-34-35
    char *result; // the return string
    char *ins;    // the next insert point
    char *tmp;    // varies
    int len_rep;  // length of rep
    int len_with; // length of with
    int len_front; // distance between rep and end of last rep
    int count;    // number of replacements
    if (!orig)
    {
        return NULL;
    }
    if (!rep)
    {
        rep = "";
    }
    len_rep = strlen(rep);
    if (!with)
    {
        with = "";
    }
    len_with = strlen(with);

    ins = orig;
    for (count = 0; tmp = strstr(ins, rep); ++count)
    {
        ins = tmp + len_rep;
    }
    // first time through the loop, all the variable are set correctly
    // from here on,
    //    tmp points to the end of the result string
    //    ins points to the next occurrence of rep in orig
    //    orig points to the remainder of orig after "end of rep"
    tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
    if (!result)
    {
        return NULL;
    }
    while (count--)
    {
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;
}

char *replace6(char *st, char *orig, char *repl)
{
  //17-18
  static char buffer[4000];
  char *ch;
  if (!(ch = strstr(st, orig)))
   return st;
  strncpy(buffer, st, ch-st);
  buffer[ch-st] = 0;
  sprintf(buffer+(ch-st), "%s%s", repl, ch+strlen(orig));
  return buffer;
}

char* replace3(char* s, char* term, char* new_term)
{
  //error
    char *nw = NULL, *pos;
    char *cur = s;
    while(pos = strstr(cur, term))
    {
        nw = (char*)realloc(nw, pos - cur + strlen(new_term));
        strncat(nw, cur, pos-cur);
        strcat(nw, new_term);
        cur = pos + strlen(term);
    }
    strcat(nw, cur);
    free(s);
    return nw;
}

char *replace2(char *original,char *pattern,char *replacement)
{
  //34-37
  size_t replen = strlen(replacement);
  size_t patlen = strlen(pattern);
  size_t orilen = strlen(original);
  size_t patcnt = 0;
  char * oriptr;
  char * patloc;
  // find how many times the pattern occurs in the original string
  for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
  {
    patcnt++;
  }
  {
    // allocate memory for the new string
    size_t retlen = orilen + patcnt * (replen - patlen);
    char * const returned = (char *) malloc( sizeof(char) * (retlen + 1) );
    if (returned != NULL)
    {
      // copy the original string,
      // replacing all the instances of the pattern
      char * retptr = returned;
      for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
      {
        size_t skplen = patloc - oriptr;
        // copy the section until the occurence of the pattern
        strncpy(retptr, oriptr, skplen);
        retptr += skplen;
        // copy the replacement
        strncpy(retptr, replacement, replen);
        retptr += replen;
      }
      // copy the rest of the string.
      strcpy(retptr, oriptr);
    }
    return returned;
  }
}

char *replace4(char *string, char *oldpiece, char *newpiece)
{
  //20-21
   int str_index, newstr_index, oldpiece_index, end,
   new_len, old_len, cpy_len;
   char *c;
   static char newstring[10000];
   if ((c = (char *) strstr(string, oldpiece)) == NULL)
      return string;
   new_len        = strlen(newpiece);
   old_len        = strlen(oldpiece);
   //str            = strlen(string);
   end            = strlen(string) - old_len;
   //int count;
   //for (count = 0; (strstr(oldpiece, newpiece)); ++count){}
   //newstring = malloc(str + (old_len - new_len) * count + 1);

   oldpiece_index = c - string;
   newstr_index = 0;
   str_index = 0;
   while(str_index <= end && c != NULL)
   {
      /* Copy characters from the left of matched pattern occurence */
      cpy_len = oldpiece_index-str_index;
      strncpy(newstring+newstr_index, string+str_index, cpy_len);
      newstr_index += cpy_len;
      str_index    += cpy_len;
      /* Copy replacement characters instead of matched pattern */
      ///*newstring=realloc(newstring,sizeof(newstring)+new_len+old_len+end+newstr_index);
      strcpy(newstring+newstr_index, newpiece);
      newstr_index += new_len;
      str_index    += old_len;
      /* Check for another pattern match */
      if((c = (char *) strstr(string+str_index, oldpiece)) != NULL)
         oldpiece_index = c - string;
   }
   /* Copy remaining characters from the right of last matched pattern */
   strcpy(newstring+newstr_index,
  string+str_index);
  return newstring;
}

char *replace5(char *orig, char *rep, char *with)
{
  //32-33-35
  char *result;
  char *ins;
  char *tmp;
  int len_rep;
  int len_with;
  int len_front;
  int count;
  if (!orig)
      return NULL;
  if (!rep)
      rep = "";
  len_rep = strlen(rep);
  if (!with)
      with = "";
  len_with = strlen(with);
  ins = orig;
  for (count = 0; (tmp = strstr(ins, rep)); ++count) {
      ins = tmp + len_rep;
  }
  tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
  if (!result)
      return NULL;
  while (count--) {
      ins = strstr(orig, rep);
      len_front = ins - orig;
      tmp = strncpy(tmp, orig, len_front) + len_front;
      tmp = strcpy(tmp, with) + len_with;
      orig += len_front + len_rep;
  }
  strcpy(tmp, orig);
  return result;
}

replace4() and replace6() is fast from other, but not malloc,realloc.

Replace() Performance Tests

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <assert.h>
#include <stdint.h>
#include <sys/stat.h>
#include <stdarg.h>
char *temp;
int main()
{
  for(int current=1;current<=80000;current++)
  {
    temp=/*replace6*//*replace3*/replace4("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890","0","black");
    //printf("%s",temp);
  }
  return 0;
}

How can I make a better replace() function?

Can I add malloc,realloc to replace4() or replace6() ?


问:
Is There A Way To Merge Joi Schemas?
Is there any way to merge two joi schemas into a single schema?

Schema 1

```<code>{
  alpha: Joi.number().required(),
  beta: Joi.string().required(),
  chalie: Joi.object({
    xray: Joi.number().required(),
  }).required()
}
</code>```

Schema 1

```<code>{
  delta: Joi.string().required(),
  echo: Joi.number().required(),
  charlie: Joi.object({
    zulu: Joi.string().required(),
  }).required()
}
</code>```

Merged Schema:

```<code>{
  alpha: Joi.number().required(),
  beta: Joi.string().required(),
  chalie: Joi.object({
    xray: Joi.number().required(),
    zulu: Joi.string().required(),
  }).required()
  delta: Joi.string().required(),
  echo: Joi.number().required(),
}
</code>```

Without nested objects it's easily done with Object.assign, but even a deep object merge won't work with the nested objects because the nested object is a function call.

答:
Using plain javascript objects was not an option for me. I tried using the .keys method to extend but it overwrites existing keys (for charlie in this case).

The solution I settled on was using .reach:
Example:

```<code>const Joi = require('joi');
const originalSchema = Joi.object({
  a: {
    deep: {
      b: Joi.string()
    }
  },
  c: Joi.string()
});
const extendedSchema = Joi.object({
  a: {
    deep: Joi
      .reach(originalSchema, 'a.deep')
      .keys({ anotherB: Joi.string() })
  },
  c: Joi.reach(originalSchema, 'c')
});

// No errors
extendedSchema.validate({ a: { deep: { b: 'hi', anotherB: 'hi' } }, c: 'wow' })
</code>```

Title: Is There A Way To Merge Joi Schemas?

Body:
Is there any way to merge two joi schemas into a single schema?

Schema 1

{
  alpha: Joi.number().required(),
  beta: Joi.string().required(),
  chalie: Joi.object({
    xray: Joi.number().required(),
  }).required()
}

Schema 1

{
  delta: Joi.string().required(),
  echo: Joi.number().required(),
  charlie: Joi.object({
    zulu: Joi.string().required(),
  }).required()
}

Merged Schema:

{
  alpha: Joi.number().required(),
  beta: Joi.string().required(),
  chalie: Joi.object({
    xray: Joi.number().required(),
    zulu: Joi.string().required(),
  }).required()
  delta: Joi.string().required(),
  echo: Joi.number().required(),
}

Without nested objects it's easily done with Object.assign, but even a deep object merge won't work with the nested objects because the nested object is a function call.

Body:
Using plain javascript objects was not an option for me. I tried using the .keys method to extend but it overwrites existing keys (for charlie in this case).

The solution I settled on was using .reach:
Example:

const Joi = require('joi');
const originalSchema = Joi.object({
  a: {
    deep: {
      b: Joi.string()
    }
  },
  c: Joi.string()
});
const extendedSchema = Joi.object({
  a: {
    deep: Joi
      .reach(originalSchema, 'a.deep')
      .keys({ anotherB: Joi.string() })
  },
  c: Joi.reach(originalSchema, 'c')
});

// No errors
extendedSchema.validate({ a: { deep: { b: 'hi', anotherB: 'hi' } }, c: 'wow' })


问:
Get last known location with Google Service API
I am learning getting location with Google Service API. But I am getting confused since I saw people use two ways to get location:

1.

```<code>FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
Location lastKnownLocation = fusedLocationProviderApi.getLastLocation(googleApiClient);
</code>```

2.

```<code>FusedLocationProviderClient mFusedLocationClient =  LocationServices.getFusedLocationProviderClient(this);
...
Task<Location> locationTask = mFusedLocationClient.getLastLocation();
        locationTask.addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location
                if (location != null) {
                    mLastKnownLocation = location;
                }
            }
        });
</code>```

Could someone please explain to me when to use which one & what are the differences between these two approaches to get last known location?

答:
Both getLastLocation methods point us same documentation content. But using the new FusedLocationProviderClient is simpler than FusedLocationProviderApi, because we don't deal with google api client and it's callback methods. It handles play services connection for us automatically. Just it

FusedLocationProviderClient methods return Task(even getting last known location), IMHO this is due to handling play services things internally.

Body:
I am learning getting location with Google Service API. But I am getting confused since I saw people use two ways to get location:

1.

FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
Location lastKnownLocation = fusedLocationProviderApi.getLastLocation(googleApiClient);

2.

FusedLocationProviderClient mFusedLocationClient =  LocationServices.getFusedLocationProviderClient(this);
...
Task<Location> locationTask = mFusedLocationClient.getLastLocation();
        locationTask.addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location
                if (location != null) {
                    mLastKnownLocation = location;
                }
            }
        });

Could someone please explain to me when to use which one & what are the differences between these two approaches to get last known location?


问:
In ghci, how to remove an existing binding?
I am getting a "binding shadows the existing binding" error similar to the one from this question.

```<code>Prelude Api.Facility Control.Monad.IO.Class> let t = getBadgesNot 1 (Nothing) (Just 1)

<interactive>:55:5: warning: [-Wname-shadowing]
    This binding for ‘t’ shadows the existing binding
      defined at <interactive>:39:5
</code>```

I defined the existing binding earlier in the session, and am now trying to redefine it. Is there a way to remove the existing binding so that I can redefine t?

I notice that in other circumstances ghci does not error when redefining an existing binding. For example

```<code>Prelude> let t = 1
Prelude> let t = 2
Prelude> let t = "there"
</code>```

Why does ghci error when redefining an existing binding in some cases and not in others?

答:
Is there a way to remove the existing binding so that I can redefine t?

No, you cannot remove the existing binding. However, you can redefine t at any time, no problem.

Why does ghci error when redefining an existing binding in some cases and not in others?

Because you ran ghci with different warning/error settings; e.g. by passing -Wname-shadowing on the command line (perhaps because you ran ghci through cabal or stack, and the associated project specifies this option in its .cabal file). N.B. -Wname-shadowing should not prevent you from redefining t unless combined with -Werror to turn the mere warning into a full-blown error.

The behavior also appears to differ depending on whether you use let or not; this is probably a bug:

```<code>% ghci -Wname-shadowing -Werror
> let t=3
> let t=4
<interactive>:3:5: warning: [-Wname-shadowing]
    This binding for ‘t’ shadows the existing binding
      defined at <interactive>:1:5

<no location info>: error:
Failing due to -Werror.
> t
3
> t=4
> t
4
</code>```

Body:
I am getting a "binding shadows the existing binding" error similar to the one from this question.

Prelude Api.Facility Control.Monad.IO.Class> let t = getBadgesNot 1 (Nothing) (Just 1)

<interactive>:55:5: warning: [-Wname-shadowing]
    This binding for ‘t’ shadows the existing binding
      defined at <interactive>:39:5

I defined the existing binding earlier in the session, and am now trying to redefine it. Is there a way to remove the existing binding so that I can redefine t?

I notice that in other circumstances ghci does not error when redefining an existing binding. For example

Prelude> let t = 1
Prelude> let t = 2
Prelude> let t = "there"

Why does ghci error when redefining an existing binding in some cases and not in others?

Body:
Is there a way to remove the existing binding so that I can redefine t?

No, you cannot remove the existing binding. However, you can redefine t at any time, no problem.

Why does ghci error when redefining an existing binding in some cases and not in others?

Because you ran ghci with different warning/error settings; e.g. by passing -Wname-shadowing on the command line (perhaps because you ran ghci through cabal or stack, and the associated project specifies this option in its .cabal file). N.B. -Wname-shadowing should not prevent you from redefining t unless combined with -Werror to turn the mere warning into a full-blown error.

The behavior also appears to differ depending on whether you use let or not; this is probably a bug:

% ghci -Wname-shadowing -Werror
> let t=3
> let t=4
<interactive>:3:5: warning: [-Wname-shadowing]
    This binding for ‘t’ shadows the existing binding
      defined at <interactive>:1:5

<no location info>: error:
Failing due to -Werror.
> t
3
> t=4
> t
4


问:
Result variable assignment from a code block?
coming from Scala to learn C# and I cant quite figure out how to do this in C#. Perhaps it's not supported? I got used to the neat idea of encapsulating small code block calculations within the larger code especially for variable initialization. Insights appreciated, perhaps there's a trick to mimic this. thank you!</p>

```<code>var calc =        //invalid example wont compile
            {
                int x = 3; //x will not escape scope
            //do something, etc.
                return x; //assigned to calc as init
            }
</code>```

答:
Not sure if this is what you are after but you probably should be looking at lamba expressions:</p>

```<code>var calc =  () =>
        {
            int x = 3; //x will not escape scope
        //do something, etc.
            return x; //assigned to calc as init
        }
</code>```

Body:
coming from Scala to learn C# and I cant quite figure out how to do this in C#. Perhaps it's not supported? I got used to the neat idea of encapsulating small code block calculations within the larger code especially for variable initialization. Insights appreciated, perhaps there's a trick to mimic this. thank you!

var calc =        //invalid example wont compile
            {
                int x = 3; //x will not escape scope
            //do something, etc.
                return x; //assigned to calc as init
            }

Body:
Not sure if this is what you are after but you probably should be looking at lamba expressions:

var calc =  () =>
        {
            int x = 3; //x will not escape scope
        //do something, etc.
            return x; //assigned to calc as init
        }


问:
Excel component with charts for Classic ASP
I was using a company called ActiveXLS to save native XLS files with charts from Classic ASP but they seem to have closed down.

Can anyone recommend an alternative classic asp excel component I can use?

CSV or HTML (with XLS content type) export is not sufficient for what I need.

答:
You can access the MS Excel DOM using Classic ASP.  There are definite limitations of this approach for a web based environment but I have used it for low volumes.

Here's some sample code to illustrate:

```<code>Set oApp = Server.CreateObject("Excel.Application")

Set oBook = oApp.Workbooks.Add
Set oSheet = oBook.ActiveSheet
Set oRange = oApp.ActiveCell

' Create the header fields
oRange.Cells(1,1) = "Column 1"
oRange.Cells(1,2) = "Column 2"

oSheet.Range(oSheet.Cells(1,1), oSheet.Cells(i,j)).Select
oApp.Selection.Columns.AutoFit
oSheet.Cells(1,1).Select

oBook.SaveAs "filename.xls"
oBook.Close
oApp.Quit

Set oApp = Nothing
</code>```

This does require Excel to be installed on the server that builds these files.

Body:
You can access the MS Excel DOM using Classic ASP.  There are definite limitations of this approach for a web based environment but I have used it for low volumes.

Here's some sample code to illustrate:

Set oApp = Server.CreateObject("Excel.Application")

Set oBook = oApp.Workbooks.Add
Set oSheet = oBook.ActiveSheet
Set oRange = oApp.ActiveCell

' Create the header fields
oRange.Cells(1,1) = "Column 1"
oRange.Cells(1,2) = "Column 2"

oSheet.Range(oSheet.Cells(1,1), oSheet.Cells(i,j)).Select
oApp.Selection.Columns.AutoFit
oSheet.Cells(1,1).Select

oBook.SaveAs "filename.xls"
oBook.Close
oApp.Quit

Set oApp = Nothing

This does require Excel to be installed on the server that builds these files.


问:
How to update different value in MySQL with PHP
I have one problem which I don't know how to resloved.

I want update MySQL with different value for all "ID" which I have in MySQL.

I use PHP for this and this is my code:

```<code>//First ID check

$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=62");

while($date = mysqli_fetch_array($result))
{
  $date['subscription_end'];
  $date['today_date'];

  if ($date['subscription_end'] <= $date['today_date']) {
    $update = "UPDATE users_manager SET status='of' WHERE id=62";
  } else {
    $update = "UPDATE users_manager SET status='on' WHERE id=62";
  }
}

//Second ID check
$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=50");

while($date = mysqli_fetch_array($result))
{
  $date['subscription_end'];
  $date['today_date'];

  if ($date['subscription_end'] <= $date['today_date']) {
    $update = "UPDATE users_manager SET status='off' WHERE id=50";
  } else {
    $update = "UPDATE users_manager SET status='on' WHERE id=50";
  }
}
</code>```

When I add new user and that user have new ID example 55 then I must again put one line of code for check new user.

Can you tell me how I can check all of this and new and old users all the time?

答:
Try this, Everything is documented .. If you diden't get anything ask me.</p>

```<code>/**
 * UserId:  This variable holds the userId,
 *          You have to bring it from database and referenced to this variable.
*/
$userId = 10;
// This variable represents the status column in the 'user_manager' Table.
$status = null;

$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM
users_manager WHERE id={$userId}");

while($date = mysqli_fetch_array($result))
{
    $date['subscription_end'];
    $date['today_date'];

    $status = ($date['subscription_end'] <= $date['today_date']) ? 'off' : 'on';

    $update = "UPDATE users_manager SET status={$status} WHERE id={$userId}";

}
</code>```

Body:
I have one problem which I don't know how to resloved.

I want update MySQL with different value for all "ID" which I have in MySQL.

I use PHP for this and this is my code:

//First ID check

$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=62");

while($date = mysqli_fetch_array($result))
{
  $date['subscription_end'];
  $date['today_date'];

  if ($date['subscription_end'] <= $date['today_date']) {
    $update = "UPDATE users_manager SET status='of' WHERE id=62";
  } else {
    $update = "UPDATE users_manager SET status='on' WHERE id=62";
  }
}

//Second ID check
$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM users_manager WHERE id=50");

while($date = mysqli_fetch_array($result))
{
  $date['subscription_end'];
  $date['today_date'];

  if ($date['subscription_end'] <= $date['today_date']) {
    $update = "UPDATE users_manager SET status='off' WHERE id=50";
  } else {
    $update = "UPDATE users_manager SET status='on' WHERE id=50";
  }
}

When I add new user and that user have new ID example 55 then I must again put one line of code for check new user.

Can you tell me how I can check all of this and new and old users all the time?

Body:
Try this, Everything is documented .. If you diden't get anything ask me.

/**
 * UserId:  This variable holds the userId,
 *          You have to bring it from database and referenced to this variable.
*/
$userId = 10;
// This variable represents the status column in the 'user_manager' Table.
$status = null;

$result = mysqli_query($conn,"SELECT subscription_end, today_date FROM
users_manager WHERE id={$userId}");

while($date = mysqli_fetch_array($result))
{
    $date['subscription_end'];
    $date['today_date'];

    $status = ($date['subscription_end'] <= $date['today_date']) ? 'off' : 'on';

    $update = "UPDATE users_manager SET status={$status} WHERE id={$userId}";

}


问:
Indexing ones into a matrix of zeros without loops
I'm fairly new to MATLAB and I need some help with this problem.

the problem is to write a function that creates an (n-n) square matrix of zeros with ones on the reverse diagonal
I tried this code:

```<code>function s=reverse_diag(n)
    s=zeros(n);
    i=1;j=n;
    while i<=n && j>=1
        s(i,j)=1;
        i=i+1;
        j=j-1;
    end
</code>```

but I want another way for solving it without using loops  or diag and eye commands.

Thanks in advance

答:
The easiest and most obvious way to achieve this without loops would be to use

```<code>s=fliplr(eye(n))
</code>```

since you stated that you don't want to use eye (for whatever reason), you could also work with sub2ind-command. It would look like this:

```<code>s=zeros(n);
s(sub2ind(size(s),1:size(s,1),size(s,2):-1:1))=1
</code>```

Body:
I'm fairly new to MATLAB and I need some help with this problem.

the problem is to write a function that creates an (n-n) square matrix of zeros with ones on the reverse diagonal
I tried this code:

function s=reverse_diag(n)
    s=zeros(n);
    i=1;j=n;
    while i<=n && j>=1
        s(i,j)=1;
        i=i+1;
        j=j-1;
    end

but I want another way for solving it without using loops  or diag and eye commands.

Thanks in advance

Body:
The easiest and most obvious way to achieve this without loops would be to use

s=fliplr(eye(n))

since you stated that you don't want to use eye (for whatever reason), you could also work with sub2ind-command. It would look like this:

s=zeros(n);
s(sub2ind(size(s),1:size(s,1),size(s,2):-1:1))=1


答:
I am not sure about Scala concept but AFAIK you can't do like that in c#. Instead, you can use inbuilt return type delegate called Func in following way :

```<code>Func<int>  calc = () => {
  int x = 3; //x will not escape scope
            //do something, etc.
                return x; //assigned to calc as init
 };
</code>```

Now, you can invoke above delegate by calc().

Title: Result variable assignment from a code block?

Body:
I am not sure about Scala concept but AFAIK you can't do like that in c#. Instead, you can use inbuilt return type delegate called Func in following way :

Func<int>  calc = () => {
  int x = 3; //x will not escape scope
            //do something, etc.
                return x; //assigned to calc as init
 };

Now, you can invoke above delegate by calc().


问:
How to make this list stay at the bottom of the page?
Want this to be at the bottom of my page. No blank space beneath it. I'm a little confused as the normal CSS to make text stay at the bottom wont work here.

    .footer li{
      display:inline;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <footer>
    <div class="footer">
    <ul style="float:left;list-style-type:none;">
          <li>Advertising</li>
          <li>Business</li>
          <li>About</li>
       </ul>

       <ul style="float:right;list-style-type:none;">
          <li>Privacy</li>
          <li>Terms</li>
          <li>Settings</li>
       </ul>
    </div>
    </footer></code>```

答:
This should do it. Fix the footer using position: fixed; and set bottom: 0px; to fix it to the bottom of the page.

.footer {
  position: fixed;
  bottom: 0px;
  width:90%;
}

.footer li{
  display:inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
    <p>Some text here</p>
    <footer>
    <div class="footer">
    <ul style="float:left; list-style-type:none;">
          <li>Advertising</li>
          <li>Business</li>
          <li>About</li>
       </ul>

       <ul style="float:right;list-style-type:none;">
          <li>Privacy</li>
          <li>Terms</li>
          <li>Settings</li>
       </ul>
    </div>
    </footer></code>```

Body:
Want this to be at the bottom of my page. No blank space beneath it. I'm a little confused as the normal CSS to make text stay at the bottom wont work here.

    .footer li{
      display:inline;
    }

Advertising

Business

About

Privacy

Terms

Settings

Body:
This should do it. Fix the footer using position: fixed; and set bottom: 0px; to fix it to the bottom of the page.

.footer {
  position: fixed;
  bottom: 0px;
  width:90%;
}

.footer li{
  display:inline;
}

    <p>Some text here</p>
    <footer>
    <div class="footer">
    <ul style="float:left; list-style-type:none;">
          <li>Advertising</li>
          <li>Business</li>
          <li>About</li>
       </ul>

       <ul style="float:right;list-style-type:none;">
          <li>Privacy</li>
          <li>Terms</li>
          <li>Settings</li>
       </ul>
    </div>
    </footer>


问:
how to validate my users login information
I have an html form where the user is requested to Enter his name and password

```<code><html>
<body>

<formaction="welcome.php"method="post">
Name: <inputtype="text"name="name"><br>
Password: <inputtype="text"name="pass.   word"><br>
<input type="create">
</form>

</body>
</html>
</code>```

and from the code above you will see I see a php page where the informations are sent to (form handler /form processor)

now I created another page for login in to the account created

```<code><html>
<body>

<form>
Name: <inputtype="text"name="name"><br>
    Password: <inputtype="text"name="password"><br>
<input type="Login">
</form>

</body>
</html>
</code>```

what I want is for the login page to go and check the welcome page (form handler /form processor) where the registered informations were sent to, to know if the account/user exists if yes open to the homepage.html but if no reset the page

but I don't know where to go from here someone please help me

答:
Using PHP, you need to implement sessions.

Try this at the top of both php files:

```<code><?php
session_start();
</code>```

Then, once you've verified that the user has authority to login you can do something like.

```<code>$_SESSION['loggedin'] = true;
</code>```

Then you can access that session variable from any file that you enabled sessions on.

Body:
I have an html form where the user is requested to Enter his name and password

<formaction="welcome.php"method="post">
Name: <inputtype="text"name="name">

Password: <inputtype="text"name="pass.   word">

<input type="create">
</form>

and from the code above you will see I see a php page where the informations are sent to (form handler /form processor)

now I created another page for login in to the account created

<form>
Name: <inputtype="text"name="name">

    Password: <inputtype="text"name="password">

<input type="Login">
</form>

what I want is for the login page to go and check the welcome page (form handler /form processor) where the registered informations were sent to, to know if the account/user exists if yes open to the homepage.html but if no reset the page

but I don't know where to go from here someone please help me

Body:
Using PHP, you need to implement sessions.

Try this at the top of both php files:

<?php
session_start();

Then, once you've verified that the user has authority to login you can do something like.

$_SESSION['loggedin'] = true;

Then you can access that session variable from any file that you enabled sessions on.


问:
Update state when user press back button in React Native
I use react-navigation for manage routes. This is my Home component:

```<code>class HomeScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: {
            firstname: 'John',
            avatar: 'john-profile.png',
            location: 'Canada',
         }
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   render() {
      return (
         <View>
            <Image src="{this.state.userProfile.avatar}" />
            <Text>Firstname: {this.state.userProfile.firstname}</Text>
            <Text>Location: {this.state.userProfile.location}</Text>
         </View>
      );
   }
}
</code>```

And this is the Profile screen:

```<code>class ProfileScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: null,
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   save() {

      var userSavedProfile = this.state.userProfile;

      userSavedProfile.firstname = "Peter";
      userSavedProfile.avatar = "peter-avatar.png";
      userSavedProfile.location = "EEUU";

      this.setState({userProfile: userSavedProfile});

      AsyncStorage.setItem('userProfile',     JSON.stringify(this.state.userProfile), () => {});

   }

   render() {
      return (
         <View>
            <Button title="Save" onPress={() => this.save()}  />
         </View>
      );
   }
}
</code>```

When I save the new user information and I press back button in header (react-navigation) the user profile is old, firstname = John, etc... How update state from Home when user press back button and refresh data?

答: I think that your application would need a state manager, where you could store your user information and access it anywhere in the app. You should take a look at Redux. It would fit your needs and the info in your Home screen would automatically update.</p>

Body:
I use react-navigation for manage routes. This is my Home component:

class HomeScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: {
            firstname: 'John',
            avatar: 'john-profile.png',
            location: 'Canada',
         }
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   render() {
      return (
         <View>
            <Image src="{this.state.userProfile.avatar}" />
            <Text>Firstname: {this.state.userProfile.firstname}</Text>
            <Text>Location: {this.state.userProfile.location}</Text>
         </View>
      );
   }
}

And this is the Profile screen:

class ProfileScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: null,
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   save() {

      var userSavedProfile = this.state.userProfile;

      userSavedProfile.firstname = "Peter";
      userSavedProfile.avatar = "peter-avatar.png";
      userSavedProfile.location = "EEUU";

      this.setState({userProfile: userSavedProfile});

      AsyncStorage.setItem('userProfile',     JSON.stringify(this.state.userProfile), () => {});

   }

   render() {
      return (
         <View>
            <Button title="Save" onPress={() => this.save()}  />
         </View>
      );
   }
}

When I save the new user information and I press back button in header (react-navigation) the user profile is old, firstname = John, etc... How update state from Home when user press back button and refresh data?


答:
In Android blog-spot google had posted one topic on location access.

Reduce friction with the new Location APIs

In that google are saying that not to use GoogleApiClient.

In the link they have details explanation.

Now the code works, but it's not ideal for a few reasons:

It would be hard to refactor into shared classes if, for instance,
you wanted to access Location Services in multiple activities.

The app connects optimistically in onCreate even if Location Services
are not needed until later (for example, after user input).

It does not handle the case where the app fails to connect to Google
Play services.

There is a lot of boilerplate connection logic before getting started
with location updates.

A better developer experience

The new LocationServices APIs are much simpler and will make your code less error prone. The connection logic is handled automatically, and you only need to attach a single completion listener:

Title: Get last known location with Google Service API


问:
How to store regex or search terms in Postgres database and evaluate in Rails Query?
I am having trouble with a DB query in a Rails app. I want to store various search terms (say 100 of them) and then evaluate against a value dynamically. All the examples of SIMILAR TO or ~ (regex) in Postgres I can find use a fixed string within the query, while I want to look the query up from a row.

Example:

```<code>Table: Post
column term varchar(256)
(plus regular id, Rails stuff etc)

input = "Foo bar"
Post.where("term ~* ?", input)
</code>```

So term is VARCHAR column name containing the data of at least one row with the value:

```<code>^foo*$
</code>```

Unless I put an exact match (e.g. "Foo bar" in term) this never returns a result.

I would also like to ideally use expressions like

```<code>(^foo.*$|^second.*$)
</code>```

i.e. multiple search terms as well, so it would match with 'Foo Bar' or 'Search Example'.

I think this is to do with Ruby or ActiveRecord stripping down something? Or I'm on the wrong track and can't use regex or SIMILAR TO with row data values like this?

Alternative suggestions on how to do this also appreciated.

答:
The Postgres regular expression match operators have the regex on the right and the string on the left. See the examples: https://www.postgresql.org/docs/9.3/static/functions-matching.html#FUNCTIONS-POSIX-TABLE

But in your query you're treating term as the string and the 'Foo bar' as the regex (you've swapped them). That's why the only term that matches is the exact match. Try:

```<code>Post.where("? ~* term", input)
</code>```

Body:
I am having trouble with a DB query in a Rails app. I want to store various search terms (say 100 of them) and then evaluate against a value dynamically. All the examples of SIMILAR TO or ~ (regex) in Postgres I can find use a fixed string within the query, while I want to look the query up from a row.

Example:

Table: Post
column term varchar(256)
(plus regular id, Rails stuff etc)

input = "Foo bar"
Post.where("term ~* ?", input)

So term is VARCHAR column name containing the data of at least one row with the value:

^foo*$

Unless I put an exact match (e.g. "Foo bar" in term) this never returns a result.

I would also like to ideally use expressions like

(^foo.*$|^second.*$)

i.e. multiple search terms as well, so it would match with 'Foo Bar' or 'Search Example'.

I think this is to do with Ruby or ActiveRecord stripping down something? Or I'm on the wrong track and can't use regex or SIMILAR TO with row data values like this?

Alternative suggestions on how to do this also appreciated.

Body:
The Postgres regular expression match operators have the regex on the right and the string on the left. See the examples: https://www.postgresql.org/docs/9.3/static/functions-matching.html#FUNCTIONS-POSIX-TABLE

But in your query you're treating term as the string and the 'Foo bar' as the regex (you've swapped them). That's why the only term that matches is the exact match. Try:

Post.where("? ~* term", input)


问:
laravel framework : is it safe to move index.php from public folder to the project root?
i know the public folder is there for a reason , but i have to upload a laravel project on a shared hosting and i dont have access to server to change the host root to public_html/public so it have to load from public_html

so i've moved index.php and htaccss from public to root and it works fine , but now anyone can directly access project files models / controller / etc.... im not sure if it's harmful but i know its not super safe !

so is it safe to do this ?  any other option beside getting a vps ?

pleas note im just a programmer and it's not my decision where to upload the project so pleas dont talk about how cheap and easy is to get a vps these days !

答:
1 - put all the project folders in separate folder like laravel

2 - move the laravel folder before public_html so it wont be accessible

3 - move all the files from public folder into the project root (public_html) then delete public folder

4 - edit index.php add ../laravel to the path


问:
Can I control the state of the Speaker Icon with Delphi code

Is it possible to control (Enable/Disable) the Speaker Icon in Delphi Code.

Is there a registry entry for this?

Many Thanks...

答:
While it might be possible to "hide" the icon by changing a undocumented registry value, the user can unhide it again in the tray icon options so this is not really a permanent solution.

If you insist on ignoring your users desire to mute their machine you can unmute the volume programmatically.

On Windows XP/2003 and older you will have to use the old mixer API. This API is not fun to deal with and you have to remember to unmute both the Wave and master volume lines. See this and this for inspiration.

Vista and later has a new COM based API that should be less painful to deal with. Create a instance of IMMDeviceEnumerator and enumerate the render endpoints (or use GetDefaultAudioEndpoint) and call IAudioEndpointVolume::SetMute on the device endpoint. This example should be pretty close, just translate it to Delphi. Volume can also be controlled per application so you might need to deal with that as well if your users are clever.

Larry Ostermans blog is also a great source for help and details about this new API.

Note: As a workaround for your unmuting, the user can simply set the volume really low to get rid of your sound. There is really no way for you to know if the sound is audible at a low volume level and setting it higher just because you can would be very evil and could really hurt somebody with headphones etc.


问:
Conditionally Change a List Item Attribute with Javascript
I'm a super beginner with javascript so forgive me if this is pretty basic, but I've several hours searching for a solution and can't figure out what I'm doing wrong. Basically, I'd like to hide a single list item identified by the id="change" items if a particular condition is met. However, it doesn't seem like the javascript code below is doing anything as the "Hide Me" list item continues to appear.</p>

```<code><script>
      var x = 1;
      if(x == 1) {
      document.getElementById("change").style.display = "none";
      }
</script>

<style>
    .default{display: block;}
</style>

<ul>
    <li class="default">Show Me</li>
    <li id="change" class="default">Hide Me</li>
</ul>
</code>```

答:
Move the

```

Body:
I'm a super beginner with javascript so forgive me if this is pretty basic, but I've several hours searching for a solution and can't figure out what I'm doing wrong. Basically, I'd like to hide a single list item identified by the id="change" items if a particular condition is met. However, it doesn't seem like the javascript code below is doing anything as the "Hide Me" list item continues to appear.

Show Me

Hide Me

Body:
Move the <script> to the bottom and it should work. Reason being, you are trying to manipulate a DOM element that has not yet been rendered.

It is standard practice to include all scripts/script files at the bottom of the page <body> to prevent this issue:

<body>
    <style>
        .default{display: block;}
    </style>

    <ul>
        <li class="default">Show Me</li>
        <li id="change" class="default">Hide Me</li>
    </ul>

    <script>
        var x = 1;
        if(x == 1) {
            document.getElementById("change").style.display = "none";
        }
    </script>
</body>


问:
How i upload multiple image's and get it in laravel 5.3?
How i upload multiple image's and get it in view with laravel 5.3 ?

My Controller function is:

```<code>public function newOffer(Request $request){
    $validate_marge['img'] = 'required|image|mimes:png,jpg,jpeg';
    $validator = Validator::make($request->all(), $validate_marge);
    if ($validator->fails()){
        return back()->withInput()->withErrors($validator);
    }else{
        $post = new Post();
        if (Input::hasFile('img')){
            $file = Input::file('img');
            $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
            $post->img = $file->getClientOriginalName();
        }
    }
    $post->title = Input::get('title');
    $post->category_id = Input::get('category_id');
    $post->second_title = Input::get('second_title');
    $post->description = Input::get('description');
    $post->location = Input::get('location');
    $post->price = Input::get('price');
    $post->save();
    return back();
}
</code>```

and is HTML form is:

```<code><form class="form-horizontal" method="post" action="{{ url('newOffer') }}"
  enctype="multipart/form-data">
{{ csrf_field() }} <div class="form-group">
    <label class="col-md-4 control-label">Select IMG's</label>
    <div class="col-md-6">
        <input type="file" class="form-control" id="image"
               name="images[]"
               required
               data-validation-required-message="Please choose image" multiple>
        <p class="help-block">{{$errors->first('images')}}</p>
    </div>
</div> <input type="submit" value="Add" class="btn btn-primary" style="width: 100%"></form>
</code>```

what i do in Controller to do it and how i preview in post??
Thank You all

答:
Change

```<code> if (Input::hasFile('img')){
        $file = Input::file('img');
        $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
        $post->img = $file->getClientOriginalName();
    }
</code>```

to

```<code>        if (Input::hasFile('img')){
                $files = Input::file('img');
                foreach ($files as $file){
                $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
                }
                    $post->img = $file->getClientOriginalName();
                    $post->title = Input::get('title');
                    $post->category_id = Input::get('category_id');
                    $post->second_title = Input::get('second_title');
                    $post->description = Input::get('description');
                    $post->location = Input::get('location');
                    $post->price = Input::get('price');
                    $post->save();

            }
 return back();
</code>```

you just need to loop through your uploaded files

Body:
How i upload multiple image's and get it in view with laravel 5.3 ?

My Controller function is:

public function newOffer(Request $request){
    $validate_marge['img'] = 'required|image|mimes:png,jpg,jpeg';
    $validator = Validator::make($request->all(), $validate_marge);
    if ($validator->fails()){
        return back()->withInput()->withErrors($validator);
    }else{
        $post = new Post();
        if (Input::hasFile('img')){
            $file = Input::file('img');
            $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
            $post->img = $file->getClientOriginalName();
        }
    }
    $post->title = Input::get('title');
    $post->category_id = Input::get('category_id');
    $post->second_title = Input::get('second_title');
    $post->description = Input::get('description');
    $post->location = Input::get('location');
    $post->price = Input::get('price');
    $post->save();
    return back();
}

and is HTML form is:

<form class="form-horizontal" method="post" action="{{ url('newOffer') }}"
  enctype="multipart/form-data">
{{ csrf_field() }}

    Select IMG's

        <input type="file" class="form-control" id="image"
               name="images[]"
               required
               data-validation-required-message="Please choose image" multiple>

{{$errors->first('images')}}

 <input type="submit" value="Add" class="btn btn-primary" style="width: 100%"></form>

what i do in Controller to do it and how i preview in post??
Thank You all

Body:
Change

 if (Input::hasFile('img')){
        $file = Input::file('img');
        $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
        $post->img = $file->getClientOriginalName();
    }

to

        if (Input::hasFile('img')){
                $files = Input::file('img');
                foreach ($files as $file){
                $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
                }
                    $post->img = $file->getClientOriginalName();
                    $post->title = Input::get('title');
                    $post->category_id = Input::get('category_id');
                    $post->second_title = Input::get('second_title');
                    $post->description = Input::get('description');
                    $post->location = Input::get('location');
                    $post->price = Input::get('price');
                    $post->save();

            }
 return back();

you just need to loop through your uploaded files


问:
Listening to DOM events (specific attributes)
I need to get data when a specific attribute is added .
I have read this post : Is there a JavaScript/jQuery DOM change listener?

```<code>  var observer = new MutationObserver(function (mutations, observer) {
    // fired when a mutation occurs
     $.each(mutations, function(index, mutation) {

      var post = $(mutation.target).find('div[class^="ContentWrapper"]');

     });
  });
  observer.observe(document, {
    subtree: true,
    attributes: true

  });
</code>```

There is a problem with this approach because there are to many events and the extension is very slow,is there an option to filter the mutations,by specific attribute?

答:
Use attributeFilter in the MutationObserverInit options. Set it to an array of attributes that you want to listen for like so:

```<code>var attributeSpecificObserver=new MutationObserver(function_you_want_observing);
attributeSpecificObserver.observe( element_you_want_to_observe, {
    attributeFilter: ['id', 'class', 'style', 'etc'],
} );
</code>```

Source: Mozilla Developer Network (MDN).

Body:
I need to get data when a specific attribute is added .
I have read this post : Is there a JavaScript/jQuery DOM change listener?

  var observer = new MutationObserver(function (mutations, observer) {
    // fired when a mutation occurs
     $.each(mutations, function(index, mutation) {

      var post = $(mutation.target).find('div[class^="ContentWrapper"]');

     });
  });
  observer.observe(document, {
    subtree: true,
    attributes: true

  });

There is a problem with this approach because there are to many events and the extension is very slow,is there an option to filter the mutations,by specific attribute?

Body:
Use attributeFilter in the MutationObserverInit options. Set it to an array of attributes that you want to listen for like so:

var attributeSpecificObserver=new MutationObserver(function_you_want_observing);
attributeSpecificObserver.observe( element_you_want_to_observe, {
    attributeFilter: ['id', 'class', 'style', 'etc'],
} );

Source: Mozilla Developer Network (MDN).

ContentLicense: CC BY-SA 4.0


问:
Reading apache connection timeout from PHP
I'm having some trouble and searched for the solution in the $_SERVER and $_SESSION variables, but couldn't find it. However, in the phpinfo() i found Timeouts Connection: 300 - Keep-Alive: 15.

Asuming that is what i am searching for (the number of seconds of inactivity before apache closes the connection), is there any other way of reading it?

Thanks.

答:
See the apache_response_headers function, and also the accompanying comments.

This works for me:

```<code><?php

flush();
$apache_headers = apache_response_headers();
//echo '```' . print_r($apache_headers, true) . '```';
preg_match('/timeout=(\d+)/', $apache_headers['Keep-Alive'], $matches);
echo $matches[1];

?>
</code>```

Body:
See the apache_response_headers function, and also the accompanying comments.

This works for me:

<?php

flush();
$apache_headers = apache_response_headers();
//echo '<pre>' . print_r($apache_headers, true) . '</pre>';
preg_match('/timeout=(\d+)/', $apache_headers['Keep-Alive'], $matches);
echo $matches[1];

?>


问:
Why 'await' requires 'async' in function definition
I'm currently learning Dart, but this is also applicable to what's going on in the JavaScript world right now, and it seems like C# also uses the same pattern.

In Dart, any function that uses await must itself be labeled asynchronous through async as follows:

```<code>import "dart:html";

main() async {
  var context = querySelector("canvas").context2D;
  var running = true;

  while (running) {
    var time = await window.animationFrame;
    ...
  }
}
</code>```

This does not make sense to me. If a function is waiting on an asynchronous function to complete, is it not then considered blocking? Why do JS and Dart require it to be labeled asynchronous? Would it not be the opposite?

To me it would make far more sense if the calling function must use the async keyword if it calls any function that also includes it in its definition. In this pattern, await would be used to convert asynchronous functions to synchronous ones.

This way would also avoid duplicate functions, since right now, libraries seem to always have func() and funcSync() or funcAsync().

答:
This is a fundamental misunderstanding of what's going on "under-the-hood", I'm assuming the javascript async/await implementation mirrors (at least conceptually) that of the .NET world (which originated in F#).

Essentially:

A "unit of work" "token" of sorts (in C# a Task in JS a Promise) represents a completion of a task with an option of returning a value.

An "asynchronous" method is marked with async, to indicate to the compiler/interpreter/runtime whatever, that this method will return said token, and will likely consume some as well.

The thingamajig running it all, will (in C#'s case), rewrite the code on the sly to essentially do the following:

Start async method

Do standard normal code

Encounter "token" providing method

Call it, grab token

Setup a place the code can jump back to later

Is the token complete? If so, carry on, If not, set a callback to have the runtime come back to this place when it does

In this expanded context, the keywords make sense:

async(hronous) - A method that does some task that can take an indeterminate amount of time, that can be waited upon.

await - Indicates that instead of just grabbing the token from the async method and doing nothing with it, that you actually want to set up all this ceremony around listening out for when the work is done, and carrying on afterwards.

tl;dr

Just think of async and await as invisible callbacks, async indicates when something can be listened out for, and await is what actually does the listening.

Body:
I'm currently learning Dart, but this is also applicable to what's going on in the JavaScript world right now, and it seems like C# also uses the same pattern.

In Dart, any function that uses await must itself be labeled asynchronous through async as follows:

import "dart:html";

main() async {
  var context = querySelector("canvas").context2D;
  var running = true;

  while (running) {
    var time = await window.animationFrame;
    ...
  }
}

This does not make sense to me. If a function is waiting on an asynchronous function to complete, is it not then considered blocking? Why do JS and Dart require it to be labeled asynchronous? Would it not be the opposite?

To me it would make far more sense if the calling function must use the async keyword if it calls any function that also includes it in its definition. In this pattern, await would be used to convert asynchronous functions to synchronous ones.

This way would also avoid duplicate functions, since right now, libraries seem to always have func() and funcSync() or funcAsync().


问:
Disable picker video functionality Swift 3
Image picker is working great! However I had like to disable the video option so the user can only take photos?
Any inputs and suggestions will be highly appreciated.</p>

答:
You need to set the mediaType to be kUTTypeImage only. Check this out.

When you use an image picker controller to capture or choose still
  images (by including only the  kUTTypeImage  type in the  mediaTypes
  array)


问:
Form Validation event.preventdefault not working
I am new to Javascript & Jquery. I am currently working on college project, I have a form input control for new password change and I want to avoid submitting the form if the use have not entered anything. I am not sure if I have chained the method well or if it is a correct to match the value from the two input fields.
I know there is a validation plugin but I want to try work things out before that.

Any help or suggestion will be appreciated

Here is the code

```<code><form id="accmanager" name="accmanager" action="view-acc.php" method="POST">
    <h1>Account Management</h1>
    <p>
      <ul type="none">
        <li><input type="radio" name="optaccmanager" checked="checked" id="viewaccinfo" /> View Account Information</li>
        <li><input type="radio" name="optaccmanager" id="addacc" /> Add Account</li>
        <li><input type="radio" name="optaccmanager" id="tochangepass" /> Change Password
         <ul id="changepass" type="none" style="display: none">
            <li><input type="text" name="newpassword" id="newpassword" size="23" title="Enter new password" /></li>
            <li><input type="text" name="confirmpassword" id="confirmpassword" size="23" title="Re-type new password" /></li>
        </ul>
        </li>
    </ul>
    <input id="submitbtn" type="submit" value="View Account" style="display: inline-block;position: absolute;left: 5em;top:20em;" />
</form>
</code>```

and the script code

```<code><script>
    //form validation section
    $(document).ready(function(){
        var changepass = $("#changepass"),
            addacc = $("#addacc"),
            viewaccinfo = $("#viewaccinfo"),
            tochangepass = $("#tochangepass");

            addacc.on("click",function(event){
              changepass.css("display","none");
              $("#submitbtn").attr("value","Add Account");
            });

            viewaccinfo.on("click",function(event){
                changepass.css("display","none");
                $("#submitbtn").attr("value","View Account");
            });

            tochangepass.on("click",function(event){
                changepass.css("display","inline");
                $("#submitbtn").attr("value","Change Password");
            });

            $("form").submit(function(event){
                var newpassword = $("#newpassword"),
                    confirmpassword = $("#confirmpassword");

                if ((newpassword.val == null) || (confirmpassword.val == null)) {
                    event.preventDefault;
                    newpassword.attr("title","Please enter new password");
                }
            });
   });
</code>```

答:
Try to change this:

```<code>if ((newpassword.val == null) || (confirmpassword.val == null)) {
   event.preventDefault;
   newpassword.attr("title","Please enter new password");
}
</code>```

To:

```<code>if ((newpassword.val().length == 0) || (confirmpassword.val().length == 0)){
   event.preventDefault();
   newpassword.attr("title","Please enter new password");
   return false;
}
</code>```

Body:
I am new to Javascript & Jquery. I am currently working on college project, I have a form input control for new password change and I want to avoid submitting the form if the use have not entered anything. I am not sure if I have chained the method well or if it is a correct to match the value from the two input fields.
I know there is a validation plugin but I want to try work things out before that.

Any help or suggestion will be appreciated

Here is the code

<form id="accmanager" name="accmanager" action="view-acc.php" method="POST">

Account Management

<input type="radio" name="optaccmanager" checked="checked" id="viewaccinfo" /> View Account Information

<input type="radio" name="optaccmanager" id="addacc" /> Add Account

<input type="radio" name="optaccmanager" id="tochangepass" /> Change Password

<input type="text" name="newpassword" id="newpassword" size="23" title="Enter new password" />

<input type="text" name="confirmpassword" id="confirmpassword" size="23" title="Re-type new password" />

    <input id="submitbtn" type="submit" value="View Account" style="display: inline-block;position: absolute;left: 5em;top:20em;" />
</form>

and the script code

Body:
Try to change this:

if ((newpassword.val == null) || (confirmpassword.val == null)) {
   event.preventDefault;
   newpassword.attr("title","Please enter new password");
}

To:

if ((newpassword.val().length == 0) || (confirmpassword.val().length == 0)){
   event.preventDefault();
   newpassword.attr("title","Please enter new password");
   return false;
}


问:
How to get URL params and make them hidden values
I'm a noob when it comes to this. I'm simply trying to allow a customer to first fill out a form, save their information for the next page, save their information again for the 3rd page, and when the customer is done filling out the 3rd page to POST it to our CRM.

I've read through many different strategies on getting the URL parameters, but I don't understand how to make them hidden input values.

Ex: http://crackerjackpromo.wjserver800.com/ START QUOTE ...

Thanks and happy 4th!

答:
Something like this?

```<code><form method="POST" action="/submit-form">
  <!-- your form fields... -->

  <input name="hidden_param" id="some_input" type="hidden" />
  <input type="submit" value="Submit" />
</form>

<script>
var someValue = 'some value' // you got it from the params
document.getElementById('some_input').value = someValue;
</script>
</code>```

hidden_param will be part of the POST data, which you can read on the server..

Body:
Something like this?

<form method="POST" action="/submit-form">
  <!-- your form fields... -->

  <input name="hidden_param" id="some_input" type="hidden" />
  <input type="submit" value="Submit" />
</form>

<script>
var someValue = 'some value' // you got it from the params
document.getElementById('some_input').value = someValue;
</script>

hidden_param will be part of the POST data, which you can read on the server..