问:
Solution for SpecificationError: nested renamer is not supported while agg() along with groupby()
```<code>def stack_plot(data, xtick, col2='project_is_approved', col3='total'):
    ind = np.arange(data.shape[0])

    plt.figure(figsize=(20,5))
    p1 = plt.bar(ind, data[col3].values)
    p2 = plt.bar(ind, data[col2].values)

    plt.ylabel('Projects')
    plt.title('Number of projects aproved vs rejected')
    plt.xticks(ind, list(data[xtick].values))
    plt.legend((p1[0], p2[0]), ('total', 'accepted'))
    plt.show()

def univariate_barplots(data, col1, col2='project_is_approved', top=False):
    # Count number of zeros in dataframe python: https://stackoverflow.com/a/51540521/4084039
    temp = pd.DataFrame(project_data.groupby(col1)[col2].agg(lambda x: x.eq(1).sum())).reset_index()

    # Pandas dataframe grouby count: https://stackoverflow.com/a/19385591/4084039
    temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']

    temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

    temp.sort_values(by=['total'],inplace=True, ascending=False)

    if top:
        temp = temp[0:top]

    stack_plot(temp, xtick=col1, col2=col2, col3='total')
    print(temp.head(5))
    print("="*50)
    print(temp.tail(5))

univariate_barplots(project_data, 'school_state', 'project_is_approved', False)
</code>```

Error:

```<code>SpecificationError                        Traceback (most recent call last)
<ipython-input-21-2cace8f16608> in <module>()
----> 1 univariate_barplots(project_data, 'school_state', 'project_is_approved', False)

<ipython-input-20-856fcc83737b> in univariate_barplots(data, col1, col2, top)
      4
      5     # Pandas dataframe grouby count: https://stackoverflow.com/a/19385591/4084039
----> 6     temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']
      7     print (temp['total'].head(2))
      8     temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

~\AppData\Roaming\Python\Python36\site-packages\pandas\core\groupby\generic.py in aggregate(self, func, *args, **kwargs)
    251             # but not the class list / tuple itself.
    252             func = _maybe_mangle_lambdas(func)
--> 253             ret = self._aggregate_multiple_funcs(func)
    254             if relabeling:
    255                 ret.columns = columns

~\AppData\Roaming\Python\Python36\site-packages\pandas\core\groupby\generic.py in _aggregate_multiple_funcs(self, arg)
    292             # GH 15931
    293             if isinstance(self._selected_obj, Series):
--> 294                 raise SpecificationError("nested renamer is not supported")
    295
    296             columns = list(arg.keys())

SpecificationError: **nested renamer is not supported**
</code>```

答:
change

```<code>temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']

temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']
</code>```

to

```<code>temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg(total='count')).reset_index()['total']
temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg(Avg='mean')).reset_index()['Avg']
</code>```

reason: in new pandas version named aggregation is the recommended replacement for the deprecated “dict-of-dicts” approach to naming the output of column-specific aggregations (Deprecate groupby.agg() with a dictionary when renaming).

source: https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.25.0.html

Body:
def stack_plot(data, xtick, col2='project_is_approved', col3='total'):
    ind = np.arange(data.shape[0])

    plt.figure(figsize=(20,5))
    p1 = plt.bar(ind, data[col3].values)
    p2 = plt.bar(ind, data[col2].values)

    plt.ylabel('Projects')
    plt.title('Number of projects aproved vs rejected')
    plt.xticks(ind, list(data[xtick].values))
    plt.legend((p1[0], p2[0]), ('total', 'accepted'))
    plt.show()

def univariate_barplots(data, col1, col2='project_is_approved', top=False):
    # Count number of zeros in dataframe python: https://stackoverflow.com/a/51540521/4084039
    temp = pd.DataFrame(project_data.groupby(col1)[col2].agg(lambda x: x.eq(1).sum())).reset_index()

    # Pandas dataframe grouby count: https://stackoverflow.com/a/19385591/4084039
    temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']

    temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

    temp.sort_values(by=['total'],inplace=True, ascending=False)

    if top:
        temp = temp[0:top]

    stack_plot(temp, xtick=col1, col2=col2, col3='total')
    print(temp.head(5))
    print("="*50)
    print(temp.tail(5))

univariate_barplots(project_data, 'school_state', 'project_is_approved', False)

Error:

SpecificationError                        Traceback (most recent call last)
<ipython-input-21-2cace8f16608> in <module>()
----> 1 univariate_barplots(project_data, 'school_state', 'project_is_approved', False)

<ipython-input-20-856fcc83737b> in univariate_barplots(data, col1, col2, top)
      4
      5     # Pandas dataframe grouby count: https://stackoverflow.com/a/19385591/4084039
----> 6     temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']
      7     print (temp['total'].head(2))
      8     temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

~\AppData\Roaming\Python\Python36\site-packages\pandas\core\groupby\generic.py in aggregate(self, func, *args, **kwargs)
    251             # but not the class list / tuple itself.
    252             func = _maybe_mangle_lambdas(func)
--> 253             ret = self._aggregate_multiple_funcs(func)
    254             if relabeling:
    255                 ret.columns = columns

~\AppData\Roaming\Python\Python36\site-packages\pandas\core\groupby\generic.py in _aggregate_multiple_funcs(self, arg)
    292             # GH 15931
    293             if isinstance(self._selected_obj, Series):
--> 294                 raise SpecificationError("nested renamer is not supported")
    295
    296             columns = list(arg.keys())

SpecificationError: **nested renamer is not supported**

Body:
change

temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']

temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

to

temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg(total='count')).reset_index()['total']
temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg(Avg='mean')).reset_index()['Avg']

reason: in new pandas version named aggregation is the recommended replacement for the deprecated “dict-of-dicts” approach to naming the output of column-specific aggregations (Deprecate groupby.agg() with a dictionary when renaming).

source: https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.25.0.html


来源: stackexchange

问:
indexOf running within Map function relying on Variable (array) from parent function (Google Apps Script)
I'm new to Google Apps Script/Javascript and I'm in the midst of working on the second iteration of my original code in order to make it faster. My first code made a lot of gets and sets to the underlying Google Sheet, while now I'm trying to do everything in arrays before setting the revised values. The current block of code I'm stuck on is my attempt to run an indexOf while running a map function.

The below script is about to run through every row of an array full of timesheet data and make
various amendments to the columns and calculate new column values.

```<code>var = amendedTimesheetData = timesheetdata.map(function(item){
    item.splice(2, 0, item[0] + " " + item[1]);
    item.splice(4, 0, item[0].slice(0, 2) + item[1].slice(0, 2) + date(item[3]));
    item.splice(0, 2);
    item.splice(3, 0, "Open");
    item.splice(4, 0, accountingCode); //SEE ISSUE BELOW

    return item
  })
}
</code>```

The accounting code variable relies on having performed a Javascript version of a vlookup based on a value in one of the array columns. The looked-up value exists in another array pulled from a different tab in the sheet. I know the code to perform the lookup looks like this:

```<code>  var timeTrackingCode = item[6]; //this is the location in the mapped array of the value to be looked up
  var timeTrackingCodeRow = codeMappingData.map(function(r){ return r[0]; }).indexOf(timeTrackingCode);
  var accountingCode = codeMappingData[timeTrackingCodeRow][1]
</code>```

The formula in the code above relies on the codeMappingData variable which was made earlier in the parent function before the map function started running.

```<code>  var codeMappingSheet = ss.getSheetByName('CodeMapping');
  var codeMappingRange = codeMappingSheet.getDataRange();
  var codeMappingData = codeMappingRange.getValues();
</code>```

The Question: How do I reference the codeMappingData array while in the map function?

Other options to get around this would be to run a For loop separate from the map, but while trying to learn all the possibilities I'm stuck on trying to understand how I could pass the variable through and achieve all of the column manipulations in as little code as possible. Any guidance on how I could achieve the variable pass through, or tips on how the code could be more efficient would all be very valuable. I've only copied a bit of the code, so it might lack context, but I think the question is clear.

Note that I've assumed that it would be ill-advised to establish the codeMappingData variable within the Map function because then every time it iterates through a row it would be performing a get from the sheet? If I'm incorrect in assuming this, then perhaps the simplest approach is to establish the variable within the map.

Thank you,

答:
You can use the thisArg parameter as described in the Array.prototype.map() documentation. Just add it after your closing curly bracket and refer to it as this within your map function, not codeMappingData.

```<code>var timeTrackingCodeRow = codeMappingData.map(function(r) {
  Logger.log(this[0]); // logs the first element of codeMappingData
  return r[0];
}, codeMappingData).indexOf(timeTrackingCode);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Google Apps Script/Javascript and I'm in the midst of working on the second iteration of my original code in order to make it faster. My first code made a lot of gets and sets to the underlying Google Sheet, while now I'm trying to do everything in arrays before setting the revised values. The current block of code I'm stuck on is my attempt to run an indexOf while running a map function.

The below script is about to run through every row of an array full of timesheet data and make
various amendments to the columns and calculate new column values.

var = amendedTimesheetData = timesheetdata.map(function(item){
    item.splice(2, 0, item[0] + " " + item[1]);
    item.splice(4, 0, item[0].slice(0, 2) + item[1].slice(0, 2) + date(item[3]));
    item.splice(0, 2);
    item.splice(3, 0, "Open");
    item.splice(4, 0, accountingCode); //SEE ISSUE BELOW

    return item
  })
}

The accounting code variable relies on having performed a Javascript version of a vlookup based on a value in one of the array columns. The looked-up value exists in another array pulled from a different tab in the sheet. I know the code to perform the lookup looks like this:

  var timeTrackingCode = item[6]; //this is the location in the mapped array of the value to be looked up
  var timeTrackingCodeRow = codeMappingData.map(function(r){ return r[0]; }).indexOf(timeTrackingCode);
  var accountingCode = codeMappingData[timeTrackingCodeRow][1]

The formula in the code above relies on the codeMappingData variable which was made earlier in the parent function before the map function started running.

  var codeMappingSheet = ss.getSheetByName('CodeMapping');
  var codeMappingRange = codeMappingSheet.getDataRange();
  var codeMappingData = codeMappingRange.getValues();

The Question: How do I reference the codeMappingData array while in the map function?

Other options to get around this would be to run a For loop separate from the map, but while trying to learn all the possibilities I'm stuck on trying to understand how I could pass the variable through and achieve all of the column manipulations in as little code as possible. Any guidance on how I could achieve the variable pass through, or tips on how the code could be more efficient would all be very valuable. I've only copied a bit of the code, so it might lack context, but I think the question is clear.

Note that I've assumed that it would be ill-advised to establish the codeMappingData variable within the Map function because then every time it iterates through a row it would be performing a get from the sheet? If I'm incorrect in assuming this, then perhaps the simplest approach is to establish the variable within the map.

Thank you,

Body:
You can use the thisArg parameter as described in the Array.prototype.map() documentation. Just add it after your closing curly bracket and refer to it as this within your map function, not codeMappingData.

var timeTrackingCodeRow = codeMappingData.map(function(r) {
  Logger.log(this[0]); // logs the first element of codeMappingData
  return r[0];
}, codeMappingData).indexOf(timeTrackingCode);


问:
Plus and minus button (Javascript)
I have tried out the add and minus button.

The thing i am trying to do is if i have selected 10 bus tickets, then how do i write a javascript function to limit the maximum of the input. For instance, if adult is increment by 1, then the maximum input for the child will be changed into 9.

Here is my code

function myFunction() {
  var adult = document.getElementByID("adult").value;
  var child = document.getElementByID("child").value;
  var maxAdult = document.getElementByID("adult").max;
  var maxChild = document.getElementByID("child").max;
  if (adult + 1) {
    maxChild = -1;
  }
  if (adult + 1) {
    maxAdult = -1;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div class="input-group" style="width: 150px;margin: 20px;">
  <span class="input-group-btn"> <!--  This is for adult tickets -->
  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
    <span class="glyphicon glyphicon-minus"></span>
  </button>
  </span>
  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">
  <span class="input-group-btn">
  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
    <span class="glyphicon glyphicon-plus"></span>
  </button>
  </span>
</div>
<div class="input-group" style="width: 150px;margin: 20px;">
  <span class="input-group-btn"> <!-- This is for child tickets -->
  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
    <span class="glyphicon glyphicon-minus"></span>
  </button>
  </span>
  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">
  <span class="input-group-btn">
  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
    <span class="glyphicon glyphicon-plus"></span>
  </button>
  </span>
</div></code>```

答:
You snippet has some errors for example child input has same id. but easiest way to make dynamic max be attache event on adult input

<input type="number" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="5" onchange="document.getElementById('child').max = 10 - e.target.value">
```

Title: Plus and minus button (Javascript)

Body:
I have tried out the add and minus button.

The thing i am trying to do is if i have selected 10 bus tickets, then how do i write a javascript function to limit the maximum of the input. For instance, if adult is increment by 1, then the maximum input for the child will be changed into 9.

Here is my code

function myFunction() {
  var adult = document.getElementByID("adult").value;
  var child = document.getElementByID("child").value;
  var maxAdult = document.getElementByID("adult").max;
  var maxChild = document.getElementByID("child").max;
  if (adult + 1) {
    maxChild = -1;
  }
  if (adult + 1) {
    maxAdult = -1;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">

  </button>

  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">

  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">

  </button>

  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">

  </button>

  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">

  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">

  </button>


问:
How to catch 'permission-denied' after updateEmail in firebase
I have a problem with permissions after using firebase updateEmail for a user.

Many of my collections roles have a 'read' like:

```<code>if request.auth != null && request.auth.token.email_verified == true;
</code>```

to only let in those users who have confirmed their e-mail during registration.

The problem is when logged in user changes his email. The interceptor reacts with "Missing or insufficient permissions. I would like somehow to log out the user immediately, right after changing the password, so that the interceptor will not be able to react. Can I react somehow before interceptor? Any idea? Or maybe some role update will be better?

UpdateEmail (https://firebase.google.com/docs/auth/web/manage-users) returns the promise and I can't log out of the user in then/catch

答:
It seems that there are some options that could help you logout the user, based on changes or updates in the database. I would recommend you to take a look at the following links, to get more information about it.

On the official documentation Manage User Sessions, as per the following phrase, it confirms that it works with change of emails.

A major account change is detected for the user. This includes events like password or email address updates.

Besides that, there is this other question in the Community, with some other options on how to achieve it: Best way to implement logout in Firebase v3.0.1+? Firebase.unauth is removed after update

Let me know if the information helped you!

Body:
I have a problem with permissions after using firebase updateEmail for a user.

Many of my collections roles have a 'read' like:

if request.auth != null && request.auth.token.email_verified == true;

to only let in those users who have confirmed their e-mail during registration.

The problem is when logged in user changes his email. The interceptor reacts with "Missing or insufficient permissions. I would like somehow to log out the user immediately, right after changing the password, so that the interceptor will not be able to react. Can I react somehow before interceptor? Any idea? Or maybe some role update will be better?

UpdateEmail (https://firebase.google.com/docs/auth/web/manage-users) returns the promise and I can't log out of the user in then/catch


问:
What are the differences between html preload and prefetch?
Preload and prefetch are both used to request resources in advance so that later resource loading can be quick. It seems that I can interchange the two

<link rel="preload" href="foo.js" as="script">

<link rel="prefetch" href="foo.js">

without noticing anything difference.

What are their differences?

答:
rel="preload" loads a resource early for the current document before the body is parsed, potentially saving overall loading time.

As a hint with a lower priority, rel="prefetch" caches a resource for the next navigation after the current document has been loaded.


问:
Multithreaded program calculating prime numbers errors
Here is my program that uses 4 threads to calculate all prime numbers up to 10,000,000.  I'm getting some errors and I'm not sure why, after following what my instructor has taught us I think I'm confusing myself the more I look at it.  I'm new to programming and especially multithreaded ones at that.

```<code>#include <stdio.h>
#include <math.h>
#include <pthread.h>  // required for threads usage
#define MAX_N 100000000
#define MAX_THREADS 4

int nthreads,  // number of threads (not counting main())
    n,  // range to check for primeness
    prime[MAX_N+1],  // in the end, prime[i] = 1 if i prime, else 0
    nextbase;  // next sieve multiplier to be used
pthread_mutex_t nextbaselock = PTHREAD_MUTEX_INITIALIZER;
pthread_t id[MAX_THREADS];

void crossout(int k)
{  int i;
   for (i = 3; i*k <= n; i += 2)  {
      prime[i*k] = 0;
   }
}

void *worker(int tn)  // tn is the thread number (0,1,...)
{  int lim,base,
       work = 0;  // amount of work done by this thread
   lim = sqrt(n);
   do  {
      pthread_mutex_lock(&nextbaselock);
      base = nextbase;
      nextbase += 2;
      // unlock the lock
      pthread_mutex_unlock(&nextbaselock);
      if (base <= lim)  {
         // don't bother crossing out if base known composite
         if (prime[base])  {
            crossout(base);
            work++;  // log work done by this thread
         }
      }
      else return work;
   } while (1);
}

main(int argc, char **argv)
{  int nprimes,  // number of primes found
       i,work;
   n = atoi(argv[1]);
   nthreads = atoi(argv[2]);
   // mark all even numbers nonprime, and the rest "prime until
   // shown otherwise"
   for (i = 3; i <= n; i++)  {
      if (i%2 == 0) prime[i] = 0;
      else prime[i] = 1;
   }
    nextbase = 3;
   // get threads started
   for (i = 0; i < nthreads; i++)  {
      pthread_create(&id[i],NULL,worker,i);
   }

   // wait for all done
    for (i = 0; i < nthreads; i++)  {
      pthread_join(id[i],&work);
      printf("%d values of base done\n",work);
       }

   // results
    nprimes = 1;
   for (i = 3; i <= n; i++)
      if (prime[i])  {
         nprimes++;
      }
   printf("the number of primes found was %d\n",nprimes);
}
</code>```

The errors I'm getting are as follows:

```<code>test.cpp: In function ‘void* worker(int)’:
test.cpp:39:19: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
   else return work;
               ^~~~
test.cpp: In function ‘int main(int, char**)’:
test.cpp:57:42: error: invalid conversion from ‘void* (*)(int)’ to ‘void* (*)(void*)’ [-fpermissive]
   pthread_create(&id[i],NULL,worker,i);
                                      ^
In file included from touch.cpp:3:0:
/usr/include/pthread.h:234:12: note:   initializing argument 3 of ‘int pthread_create(pthread_t*,
const pthread_attr_t*, void* (*)(void*), void*)’
 extern int pthread_create (pthread_t *__restrict __newthread,
        ^~~~~~~~~~~~~~
test.cpp:57:42: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
       pthread_create(&id[i],NULL,worker,i);
                                      ^
 In file included from touch.cpp:3:0:
 /usr/include/pthread.h:234:12: note:   initializing argument 4 of ‘int pthread_create(pthread_t*,
 const pthread_attr_t*, void* (*)(void*), void*)’
 extern int pthread_create (pthread_t *__restrict __newthread,
        ^~~~~~~~~~~~~~
test.cpp:62:31: error: cannot convert ‘int*’ to ‘void**’ for argument ‘2’ to ‘int
pthread_join(pthread_t, void**)’
       pthread_join(id[i],&work);
</code>```

Any help would be much appreciated!

答:
The main problem is that a pointer is not compatible with a non-pointer value (as told by e.g. invalid conversion from ‘int’ to ‘void*’).

There are a few different solutions to this problem. One of the simpler is to use structures and arrays to pass data to the threads and to "return" data from the threads.

Such a structure could, for your case, look something like

```<code>struct thread_data
{
    int tn;
    int work;
};
</code>```

In your main function you then create an array of such structures and initialize it:

```<code>struct thread_data work_data[nthreads];
for (int i = 0; i < nthreads; ++i)
{
    work_data[i].tn = i;
    work_data[i].work = 0;
}
</code>```

And pass pointers to this structure when you create your threads:

```<code>for (int i = 0; i < nthreads; ++i)
{
    pthread_create(&id[i], NULL, worker, &work_data[i]);
}
</code>```

Inside the threads you need to convert the passed void * pointer to the correct pointer type:

```<code>void *worker(void *data_pointer)
{
    struct thread_data *data = (struct thread_data *) data_pointer;

    // Now instead of `tn` use `data->tn`
    // And instead of the old `work` variable, use `data->work`

    // ... Code to do the stuff...

    return NULL;  // The result is passed back through the `data` structure
}
</code>```

Finally back in the main function you simply not care about the threads return value, and instead use the work value from the corresponding structure:

```<code>for (int i = 0; i < nthreads; ++i)
{
    pthread_join(id[i], NULL);
    printf("%d values of base done\n", work_data[i].work);
}
</code>```

Body:
Here is my program that uses 4 threads to calculate all prime numbers up to 10,000,000.  I'm getting some errors and I'm not sure why, after following what my instructor has taught us I think I'm confusing myself the more I look at it.  I'm new to programming and especially multithreaded ones at that.

#include <stdio.h>
#include <math.h>
#include <pthread.h>  // required for threads usage
#define MAX_N 100000000
#define MAX_THREADS 4

int nthreads,  // number of threads (not counting main())
    n,  // range to check for primeness
    prime[MAX_N+1],  // in the end, prime[i] = 1 if i prime, else 0
    nextbase;  // next sieve multiplier to be used
pthread_mutex_t nextbaselock = PTHREAD_MUTEX_INITIALIZER;
pthread_t id[MAX_THREADS];

void crossout(int k)
{  int i;
   for (i = 3; i*k <= n; i += 2)  {
      prime[i*k] = 0;
   }
}

void *worker(int tn)  // tn is the thread number (0,1,...)
{  int lim,base,
       work = 0;  // amount of work done by this thread
   lim = sqrt(n);
   do  {
      pthread_mutex_lock(&nextbaselock);
      base = nextbase;
      nextbase += 2;
      // unlock the lock
      pthread_mutex_unlock(&nextbaselock);
      if (base <= lim)  {
         // don't bother crossing out if base known composite
         if (prime[base])  {
            crossout(base);
            work++;  // log work done by this thread
         }
      }
      else return work;
   } while (1);
}

main(int argc, char **argv)
{  int nprimes,  // number of primes found
       i,work;
   n = atoi(argv[1]);
   nthreads = atoi(argv[2]);
   // mark all even numbers nonprime, and the rest "prime until
   // shown otherwise"
   for (i = 3; i <= n; i++)  {
      if (i%2 == 0) prime[i] = 0;
      else prime[i] = 1;
   }
    nextbase = 3;
   // get threads started
   for (i = 0; i < nthreads; i++)  {
      pthread_create(&id[i],NULL,worker,i);
   }

   // wait for all done
    for (i = 0; i < nthreads; i++)  {
      pthread_join(id[i],&work);
      printf("%d values of base done\n",work);
       }

   // results
    nprimes = 1;
   for (i = 3; i <= n; i++)
      if (prime[i])  {
         nprimes++;
      }
   printf("the number of primes found was %d\n",nprimes);
}

The errors I'm getting are as follows:

test.cpp: In function ‘void* worker(int)’:
test.cpp:39:19: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
   else return work;
               ^~~~
test.cpp: In function ‘int main(int, char**)’:
test.cpp:57:42: error: invalid conversion from ‘void* (*)(int)’ to ‘void* (*)(void*)’ [-fpermissive]
   pthread_create(&id[i],NULL,worker,i);
                                      ^
In file included from touch.cpp:3:0:
/usr/include/pthread.h:234:12: note:   initializing argument 3 of ‘int pthread_create(pthread_t*,
const pthread_attr_t*, void* (*)(void*), void*)’
 extern int pthread_create (pthread_t *__restrict __newthread,
        ^~~~~~~~~~~~~~
test.cpp:57:42: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
       pthread_create(&id[i],NULL,worker,i);
                                      ^
 In file included from touch.cpp:3:0:
 /usr/include/pthread.h:234:12: note:   initializing argument 4 of ‘int pthread_create(pthread_t*,
 const pthread_attr_t*, void* (*)(void*), void*)’
 extern int pthread_create (pthread_t *__restrict __newthread,
        ^~~~~~~~~~~~~~
test.cpp:62:31: error: cannot convert ‘int*’ to ‘void**’ for argument ‘2’ to ‘int
pthread_join(pthread_t, void**)’
       pthread_join(id[i],&work);

Any help would be much appreciated!

Body:
The main problem is that a pointer is not compatible with a non-pointer value (as told by e.g. invalid conversion from ‘int’ to ‘void*’).

There are a few different solutions to this problem. One of the simpler is to use structures and arrays to pass data to the threads and to "return" data from the threads.

Such a structure could, for your case, look something like

struct thread_data
{
    int tn;
    int work;
};

In your main function you then create an array of such structures and initialize it:

struct thread_data work_data[nthreads];
for (int i = 0; i < nthreads; ++i)
{
    work_data[i].tn = i;
    work_data[i].work = 0;
}

And pass pointers to this structure when you create your threads:

for (int i = 0; i < nthreads; ++i)
{
    pthread_create(&id[i], NULL, worker, &work_data[i]);
}

Inside the threads you need to convert the passed void * pointer to the correct pointer type:

void *worker(void *data_pointer)
{
    struct thread_data *data = (struct thread_data *) data_pointer;

    // Now instead of `tn` use `data->tn`
    // And instead of the old `work` variable, use `data->work`

    // ... Code to do the stuff...

    return NULL;  // The result is passed back through the `data` structure
}

Finally back in the main function you simply not care about the threads return value, and instead use the work value from the corresponding structure:

for (int i = 0; i < nthreads; ++i)
{
    pthread_join(id[i], NULL);
    printf("%d values of base done\n", work_data[i].work);
}


问:
Request new access token and continue last request
I'm using Angular / Typescript. The application communicates with an API, an access_token is stored in storage.

On every request the interceptor checks if the access_token is still valid.

When the access_token is expired, the application needs to refresh the access_token with the refresh_token and continue with the last request (with the new access_token)

The problem
I cannot get to clone the original request (with the expired token) and execute it.
The call to request the new access_token is interfering with the interceptor.
What is the best way to:

Request the new token.

Set the new token.

Resume the call that had the expired token and clone to run successful?

The interceptor:

```<code>    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        if (!this.isRefreshing) {
            if (this.authenticationService.checkLoginState()) {
                // Check if access_token is valid.
                this.currentUser = JSON.parse(localStorage.getItem('auth'));
                if (new Date(this.currentUser.access_token_expires) > new Date()) {
                    // Access token is valid, clone request and continue.
                    request = request.clone({
                        setHeaders: {
                            Authorization: `Bearer ${this.currentUser.access_token}`
                        }
                    });
                    return next.handle(request);
                } else {
                    // Token is not valid, request new token with reLogin().
                    this.reLogin().then(any => {
                        // New token has been set, now run old request with new token.
                        return next.handle(request);
                    }, error => {
                        this.authenticationService.logout();
                    });
                }
            }
        } else {
            return next.handle(request);
        }
    }
</code>```

reLogin:

```<code>    reLogin() {
        return new Promise(function (resolve, reject) {
            this.isRefreshing = true;
            // Check if refresh token is valid
            if (new Date(this.currentUser.refresh_token_expires) > new Date()) {
                this.authenticationService.loginWithRefreshToken(this.currentUser.refresh_token).subscribe(data => {
                    // Using refresh_token was successful
                    this.currentUser = JSON.parse(localStorage.getItem('auth'));
                    this.isRefreshing = false;
                    resolve();
                }, error => {
                    console.error(error);
                    reject();
                });

        });
    }
</code>```

答:
A first remark would be to create a new const for the request when cloning it and not assigned it to the old one.
The problem I think is when you are calling reLogin and expecting that in then you have access to a new request with the updated token. But you are still in the context of the old request. So you should probably return the access_token from the reLogin and set it on a clone of the request before proceeding with it.

Body:
I'm using Angular / Typescript. The application communicates with an API, an access_token is stored in storage.

On every request the interceptor checks if the access_token is still valid.

When the access_token is expired, the application needs to refresh the access_token with the refresh_token and continue with the last request (with the new access_token)

The problem
I cannot get to clone the original request (with the expired token) and execute it.
The call to request the new access_token is interfering with the interceptor.
What is the best way to:

Request the new token.

Set the new token.

Resume the call that had the expired token and clone to run successful?

The interceptor:

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        if (!this.isRefreshing) {
            if (this.authenticationService.checkLoginState()) {
                // Check if access_token is valid.
                this.currentUser = JSON.parse(localStorage.getItem('auth'));
                if (new Date(this.currentUser.access_token_expires) > new Date()) {
                    // Access token is valid, clone request and continue.
                    request = request.clone({
                        setHeaders: {
                            Authorization: `Bearer ${this.currentUser.access_token}`
                        }
                    });
                    return next.handle(request);
                } else {
                    // Token is not valid, request new token with reLogin().
                    this.reLogin().then(any => {
                        // New token has been set, now run old request with new token.
                        return next.handle(request);
                    }, error => {
                        this.authenticationService.logout();
                    });
                }
            }
        } else {
            return next.handle(request);
        }
    }

reLogin:

    reLogin() {
        return new Promise(function (resolve, reject) {
            this.isRefreshing = true;
            // Check if refresh token is valid
            if (new Date(this.currentUser.refresh_token_expires) > new Date()) {
                this.authenticationService.loginWithRefreshToken(this.currentUser.refresh_token).subscribe(data => {
                    // Using refresh_token was successful
                    this.currentUser = JSON.parse(localStorage.getItem('auth'));
                    this.isRefreshing = false;
                    resolve();
                }, error => {
                    console.error(error);
                    reject();
                });

        });
    }


问:
Azure DevOps Boards - display query result on a board
how to develop the extension to display query result on a board? Such thing is not possible in the Azure Devops unfortunatelly. I've found two extensions on the marketplace which are doing what I need:

AA Query Board

Query based boards

but this extensions are not updated for a long time and I couldn't contact the authors (I need to change few things in order to be able to use it internally in my company).

I've found also this topic Add tabs on query result pages, so it looks like it's quite easy to add new tab to the query result menu, but I have no idea and I can't find any info how to get data (work items) from query result to display them?

Rest of the extension is just to display this data in grid, so that would be also quite easy, but getting this query result data is blocking me.

答:
Eventually I managed to contact the author of the "AA Query Board" extension and it turns out that he has a public repository on GitHub with the source code of the extension, so basically everyone can lookup how it's done or base on it.

Link to the repository: https://github.com/staticnz/aa_query_board


问:
how to get the url parameters and set it as the default value of a text box onload
URL

```<code>http://localhost:8082/EPHI2/SearchOrg.html?orgName=Appollo
</code>```

I have to extract the parameter from this url and set it as the default value of a text box onload of the page.

My HTML page is as follows.

SearchOrg.html

```<code>    <!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style>
.topnav {
  overflow: hidden;
  background-color: #FCFEEA;
}

.topnav a {
  float: left;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #CBF894;
  color: black;
}

.topnav a.active {
  background-color: #4CAF50;
  color: white;
}
</style>
</head>
<body>
<div class="topnav">
        <a href="landing.html">Home</a>
        <a href="search.html">Search Patient</a>
        <a href="manage_policy.html">Manage Policy</a>
        <a href="#" class="xactive">Search Organization</a>
    </div>
    <br>
    <br>
    <br>
    <br>
    <form style="padding: 10px 400px;" name="searchOrganization" action="viewOrganization" method="post">
        <input type="text" name="searchOrg" id="searchOrg" class="form-control"
            placeholder="Search the organization" /> <br>          <input
            type="submit" class="btn btn-primary" id="Search" value="Search" /> <input
            type="button" class="btn btn-primary" id="ok" value="OK" /> <input
            type="reset" class="btn btn-primary" id="clear" value="Clear" />
    </form>
</body>
</html>
</code>```

I have to set the default value of the textbox "searchOrg" as the value of the url parameter "orgName".

答:
here is complete code just copy it, thanks</p>

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style>
.topnav {
 overflow: hidden;
 background-color: #FCFEEA;
}

.topnav a {
 float: left;
 color: black;
 text-align: center;
 padding: 14px 16px;
 text-decoration: none;
 font-size: 17px;
 }

.topnav a:hover {
 background-color: #CBF894;
 color: black;
 }

.topnav a.active {
 background-color: #4CAF50;
 color: white;
 }
</style>
</head>
<body>
<div class="topnav">
    <a href="landing.html">Home</a>
    <a href="search.html">Search Patient</a>
    <a href="manage_policy.html">Manage Policy</a>
    <a href="#" class="xactive">Search Organization</a>
</div>
<br>
<br>
<br>
<br>
<form style="padding: 10px 400px;" name="searchOrganization" action="viewOrganization" method="post">
    <input type="text" name="searchOrg" id="searchOrg" class="form-control"
        placeholder="Search the organization" /> <br>          <input
        type="submit" class="btn btn-primary" id="Search" value="Search" /> <input
        type="button" class="btn btn-primary" id="ok" value="OK" /> <input
        type="reset" class="btn btn-primary" id="clear" value="Clear" />
</form>

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( window ).on( "load", function() {
function getParameterByName( name,href )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}

var url      = window.location.href;
$('#searchOrg').val(getParameterByName("orgName", url));
});

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

Body:
URL

http://localhost:8082/EPHI2/SearchOrg.html?orgName=Appollo

I have to extract the parameter from this url and set it as the default value of a text box onload of the page.

My HTML page is as follows.

SearchOrg.html

    <!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">

        Home
        Search Patient
        Manage Policy
        Search Organization

    <form style="padding: 10px 400px;" name="searchOrganization" action="viewOrganization" method="post">
        <input type="text" name="searchOrg" id="searchOrg" class="form-control"
            placeholder="Search the organization" />
          <input
            type="submit" class="btn btn-primary" id="Search" value="Search" /> <input
            type="button" class="btn btn-primary" id="ok" value="OK" /> <input
            type="reset" class="btn btn-primary" id="clear" value="Clear" />
    </form>

I have to set the default value of the textbox "searchOrg" as the value of the url parameter "orgName".

Body:
here is complete code just copy it, thanks

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style>
.topnav {
 overflow: hidden;
 background-color: #FCFEEA;
}

.topnav a {
 float: left;
 color: black;
 text-align: center;
 padding: 14px 16px;
 text-decoration: none;
 font-size: 17px;
 }

.topnav a:hover {
 background-color: #CBF894;
 color: black;
 }

.topnav a.active {
 background-color: #4CAF50;
 color: white;
 }
</style>
</head>
<body>
<div class="topnav">
    <a href="landing.html">Home</a>
    <a href="search.html">Search Patient</a>
    <a href="manage_policy.html">Manage Policy</a>
    <a href="#" class="xactive">Search Organization</a>
</div>
<br>
<br>
<br>
<br>
<form style="padding: 10px 400px;" name="searchOrganization" action="viewOrganization" method="post">
    <input type="text" name="searchOrg" id="searchOrg" class="form-control"
        placeholder="Search the organization" /> <br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;<input
        type="submit" class="btn btn-primary" id="Search" value="Search" /> <input
        type="button" class="btn btn-primary" id="ok" value="OK" /> <input
        type="reset" class="btn btn-primary" id="clear" value="Clear" />
</form>

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( window ).on( "load", function() {
function getParameterByName( name,href )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}

var url      = window.location.href;
$('#searchOrg').val(getParameterByName("orgName", url));
});

</script>
</body>
</html>


问:
change the color (change it to gray) of the navbar's selected tab
```<code><!-- Navbar -->
<nav class="navbar navbar-expand-sm bg-primary navbar-dark">
  <a class="navbar-brand" href="<?php echo base_url('Controller_dashboard'); ?>"><strong>StuFAP MS</strong></a>
  <ul class="navbar-nav ml-auto">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
      <span class="navbar-toggler-icon"></span>
    </button>
  </ul>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <!-- Super Admin Navbar -->
      <?php if($_SESSION['Type']==1){ ?>
        <li class="nav-item active">
        <!--<a class="nav-link" href="<?php //echo base_url('Controller_document'); ?>" style="color:white;">Document</a>-->
          <a class="nav-link" href="<?php echo base_url('Controller_dashboard'); ?>"><strong>Home</strong></a>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="<?php echo base_url('Controller_applicants'); ?>">
            <strong>Students</strong>
            <span id="badge_superadmin" class="badge badge-danger d-none"></span>
          </a>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="<?php echo base_url('Controller_ranking'); ?>"><strong>Ranking</strong></a>
        </li>
        <li class="nav-item dropdown active">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <strong>Manage</strong>
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <a class="dropdown-item" href="<?php echo base_url('Controller_awardees'); ?>"><strong>Awardees</strong></a>
          </div>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="#"><strong>Payments</strong></a>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="#"><strong>Reports</strong></a>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="<?php echo base_url('Controller_users'); ?>"><strong>Users</strong></a>
        </li>
      <?php } ?>
      <!-- Admin Navbar -->
      <?php if($_SESSION['Type']==2){ ?>
        <li class="nav-item active">
        <!--<a class="nav-link" href="<?php //echo base_url('Controller_document'); ?>" style="color:white;">Document</a>-->
          <a class="nav-link" href="<?php echo base_url('Controller_dashboard'); ?>"><strong>Home</strong></a>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="<?php echo base_url('Controller_applicants'); ?>">
            <strong>Students</strong>
            <span  id="badge_admin" class="badge badge-danger d-none"></span>
          </a>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="<?php echo base_url('Controller_ranking'); ?>"><strong>Ranking</strong></a>
        </li>
        <li class="nav-item dropdown active">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <strong>Manage</strong>
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <a class="dropdown-item" href="<?php echo base_url('Controller_awardees'); ?>"><strong>Awardees</strong></a>
          </div>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="#"><strong>Payments</strong></a>
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="#"><strong>Reports</strong></a>
        </li>
      <?php } ?>
    </ul>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item dropdown active">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          <strong><?php echo $_SESSION['Username'] ?></strong>
        </a>
        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="<?php echo base_url('Controller_profile'); ?>"><strong>Profile</strong></a>
          <a class="dropdown-item" href="<?php echo base_url('Controller_dashboard/remove_credentials'); ?>"><strong>Logout</strong></a>
        </div>
      </li>
    </ul>
  </div>
</nav>
<!-- Navbar -->
</code>```

Considering the following code fragment, how can I make the selected tab/module noticeable when it is the current module being used? Someone please help me in creating a way to change the color (change it to gray) of the selected tab. Thanks in advance.
***My codes are still not final that's why it still hasn't been optimized.

答:
I'm not sure if I fully understand your question. What exactly do you mean by 'selected tab/module'? One nav item? The whole nav bar?

Generally the easiest way to manipulate the presentation of an element is to add a class using PHP or Javascript, something like "is-active" etc. To that class you bind your desired CSS-styles like

```<code>.is-active {
  color: grey;
  background-color: white;
  …
}
</code>```

My problem with the above code is that almost all of the list items have an "active"-class. So what does "active" mean in this context? Active in the meaning of "being selected"? Or just being "not inactive" …?

Body:
  <a class="navbar-brand" href="<?php echo base_url('Controller_dashboard'); ?>">StuFAP MS

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

    </button>

      <?php if($_SESSION['Type']==1){ ?>

          <a class="nav-link" href="<?php echo base_url('Controller_dashboard'); ?>">Home

          <a class="nav-link" href="<?php echo base_url('Controller_applicants'); ?>">
            Students

          <a class="nav-link" href="<?php echo base_url('Controller_ranking'); ?>">Ranking

            Manage

            <a class="dropdown-item" href="<?php echo base_url('Controller_awardees'); ?>">Awardees

          Payments

          Reports

          <a class="nav-link" href="<?php echo base_url('Controller_users'); ?>">Users

      <?php } ?>

      <?php if($_SESSION['Type']==2){ ?>

          <a class="nav-link" href="<?php echo base_url('Controller_dashboard'); ?>">Home

          <a class="nav-link" href="<?php echo base_url('Controller_applicants'); ?>">
            Students

          <a class="nav-link" href="<?php echo base_url('Controller_ranking'); ?>">Ranking

            Manage

            <a class="dropdown-item" href="<?php echo base_url('Controller_awardees'); ?>">Awardees

          Payments

          Reports

      <?php } ?>

          <?php echo $_SESSION['Username'] ?>

          <a class="dropdown-item" href="<?php echo base_url('Controller_profile'); ?>">Profile
          <a class="dropdown-item" href="<?php echo base_url('Controller_dashboard/remove_credentials'); ?>">Logout

Considering the following code fragment, how can I make the selected tab/module noticeable when it is the current module being used? Someone please help me in creating a way to change the color (change it to gray) of the selected tab. Thanks in advance.
***My codes are still not final that's why it still hasn't been optimized.

Body:
I'm not sure if I fully understand your question. What exactly do you mean by 'selected tab/module'? One nav item? The whole nav bar?

Generally the easiest way to manipulate the presentation of an element is to add a class using PHP or Javascript, something like "is-active" etc. To that class you bind your desired CSS-styles like

.is-active {
  color: grey;
  background-color: white;
  …
}

My problem with the above code is that almost all of the list items have an "active"-class. So what does "active" mean in this context? Active in the meaning of "being selected"? Or just being "not inactive" …?


问:
Then code of an axios.get not completed and error catched
I'm trying to understand the flow of following code using console.log traces:

```<code>function fetchTsValues() {

    console.log("fetchTsValues");

    axios.get(urlValues)
        .then(result => valuesToChannel(result.data))
        .catch(() => setError('Impossible to get TS values'));
}

useEffect(() => {
    fetchTsValues();
}, []);

function valuesToChannel(TSDetailAPI) {

    console.log(TSDetailAPI);
    console.log("valuesToChannel");

    const updatedChannels = {...channels};
    console.log("updatedChannels - 1", updatedChannels);
    updatedChannels[TSDetailAPI.name].series = buildSeries(TSDetailAPI.values);

    console.log("updatedChannels - 2", updatedChannels);
    setChannels(updatedChannels);
    setIsLoading(false);
}

console.log("error", error);
</code>```

The traces are following ones:

```<code>fetchTsValues
valuesToChannel
updatedChannels - 1 {demo-temperature-1: {…}}
error Impossible to get TS values
</code>```

What I don't understand is why I start to run valuesToChannel initial instructions before being stopped by the catch of fetchTsValues axios.get. The get runs correctly with a 200 return status code.

I could understand to finish the then and then if the promise is not delivered to move to the catch. But here the code is not even ending the then clause. What am I doing wrong or not understanding?

Note: this code is part of a wider react context. But I think that I have properly figured out a reduced context.

答:
Thanks to Charlie, I was able to fix my error.

I learnt that using Try...catch is efficient to detect error thrown in unexpected areas of code!

Body:
I'm trying to understand the flow of following code using console.log traces:

function fetchTsValues() {

    console.log("fetchTsValues");

    axios.get(urlValues)
        .then(result => valuesToChannel(result.data))
        .catch(() => setError('Impossible to get TS values'));
}

useEffect(() => {
    fetchTsValues();
}, []);

function valuesToChannel(TSDetailAPI) {

    console.log(TSDetailAPI);
    console.log("valuesToChannel");

    const updatedChannels = {...channels};
    console.log("updatedChannels - 1", updatedChannels);
    updatedChannels[TSDetailAPI.name].series = buildSeries(TSDetailAPI.values);

    console.log("updatedChannels - 2", updatedChannels);
    setChannels(updatedChannels);
    setIsLoading(false);
}

console.log("error", error);

The traces are following ones:

fetchTsValues
valuesToChannel
updatedChannels - 1 {demo-temperature-1: {…}}
error Impossible to get TS values

What I don't understand is why I start to run valuesToChannel initial instructions before being stopped by the catch of fetchTsValues axios.get. The get runs correctly with a 200 return status code.

I could understand to finish the then and then if the promise is not delivered to move to the catch. But here the code is not even ending the then clause. What am I doing wrong or not understanding?

Note: this code is part of a wider react context. But I think that I have properly figured out a reduced context.


问:
Why the streams are not seen as string on client side
I have made a simple server and client program where the server reads the data from file and send to the client through TCP socket But the data I am getting is in object and not a simple string ?

So why I cant see the data as plaintext as it is in my data.txt file.

Explanation with example would be appreciated.

Here is my code :-

SERVER CODE

const fs = require('fs');
const net = require('net');

const readableData = fs.createReadStream('data.txt', 'utf8');

const server = net.createServer(socket => {
    socket.on('data', chunk => {
        console.log(chunk.toString());
        socket.write(JSON.stringify(readableData));
    });

    socket.on('end', () => {
        console.log("done");
    })

    socket.on('close', () => {
        console.log("closed")
    })
});

server.listen(3000);
```

<p><strong>CLIENT CODE</strong></p>

<pre class="lang-js prettyprint-override"><code>const fs = require('fs');
const net = require('net');

const client = new net.Socket();

client.connect('3000', () => {
    console.log("connected");
    client.write("Server please send the data");
});

client.on('data', chunk => {
    console.log("Data recieved:" + chunk.toString());
});

client.on('finish', () => {
    console.log("Work completed");
})

client.on('close', () => {
    console.log("connection closed");
})
</code>```

And here is my data.txt file which has simple data

Hello client how are you ?

And the output I'm getting is here :-

Data recieved:{"_readableState":{"objectMode":false,"highWaterMark":65536,"buffer":{"head":{"data":"Hello client how are you ?","next":null},"tail":{"data":"Hello client how are you ?","next":null},"length":1},"length":26,"pipes":null,"pipesCount":0,"flowing":null,"ended":true,"endEmitted":false,"reading":false,"sync":false,"needReadable":false,"emittedReadable":false,"readableListening":false,"resumeScheduled":false,"paused":true,"emitClose":false,"autoDestroy":false,"destroyed":false,"defaultEncoding":"utf8","awaitDrain":0,"readingMore":false,"decoder":{"encoding":"utf8"},"encoding":"utf8"},"readable":true,"_events":{},"_eventsCount":1,"path":"data.txt","fd":35,"flags":"r","mode":438,"end":null,"autoClose":true,"bytesRead":26,"closed":false}

The question why I won't be able to see the data as plaintext on client side as it is in data.txt file.

答:
Your variable readableData contains a node.js stream object.  That's what that variable is.  It's only of use in the current node.js instance so it doesn't do anything useful to try to send that stream object to the client.

If you want to get all the data from that 'data.txt' file, you have several choices.

You can just read the whole file into a local variable with fs.readFile() and then send all that data with socket.write().

You can create a new stream attached to the file for each new incoming request and then  as the data comes in on the readStream, you can send it out on the socket (this is often referred to as piping one stream into another).  If you use higher level server constructs such as an http server, they make piping real easy.

Option #1 would look like this:

```<code>const server = net.createServer(socket => {
    socket.on('data', chunk => {
        console.log(chunk.toString());
        fs.readFile('data.txt', 'utf8', (err, data) => {
            if (err) {
                 // insert error handling here
                 console.log(err);
            } else {
                 socket.write(data);
            }
        });
    });

    socket.on('end', () => {
        console.log("done");
    })

    socket.on('close', () => {
        console.log("closed")
    })
});
</code>```

FYI, you should also know that socket.on('data', chunk => {...}) can give you any size chunk of data.  TCP streams do not make any guarantees about delivering the exact same chunks of data in the same pieces that they were originally sent in.  They will come in order, but if you sent three 1k chunks from the other end, they might arrive as three separate 1k chunks, they might arrive as one 3k chunk or they might arrive as a whole bunch of much smaller chunks.  How they arrive will often depend upon what intermediate transports and routers they had to travel over and if there were any recoverable issues along that transmission.  For example, data sent over a satellite internet connection will probably arrive in small chunks because the needs of the transport broke it up into smaller pieces.

This means that reading any data over a plain TCP connection generally needs some sort of protocol so that the reader knows when they've gotten a full, meaningful chunk that they can process.  If the data is plain text, it might be as simple a protocol as every message ends with a line feed character.  But, if the data is more complex, then the protocol may need to be more complex.

Body:
I have made a simple server and client program where the server reads the data from file and send to the client through TCP socket But the data I am getting is in object and not a simple string ?

So why I cant see the data as plaintext as it is in my data.txt file.

Explanation with example would be appreciated.

Here is my code :-

SERVER CODE

const fs = require('fs');
const net = require('net');

const readableData = fs.createReadStream('data.txt', 'utf8');

const server = net.createServer(socket => {
    socket.on('data', chunk => {
        console.log(chunk.toString());
        socket.write(JSON.stringify(readableData));
    });

    socket.on('end', () => {
        console.log("done");
    })

    socket.on('close', () => {
        console.log("closed")
    })
});

server.listen(3000);

CLIENT CODE

const fs = require('fs');
const net = require('net');

const client = new net.Socket();

client.connect('3000', () => {
    console.log("connected");
    client.write("Server please send the data");
});

client.on('data', chunk => {
    console.log("Data recieved:" + chunk.toString());
});

client.on('finish', () => {
    console.log("Work completed");
})

client.on('close', () => {
    console.log("connection closed");
})

And here is my data.txt file which has simple data

Hello client how are you ?

And the output I'm getting is here :-

Data recieved:{"_readableState":{"objectMode":false,"highWaterMark":65536,"buffer":{"head":{"data":"Hello client how are you ?","next":null},"tail":{"data":"Hello client how are you ?","next":null},"length":1},"length":26,"pipes":null,"pipesCount":0,"flowing":null,"ended":true,"endEmitted":false,"reading":false,"sync":false,"needReadable":false,"emittedReadable":false,"readableListening":false,"resumeScheduled":false,"paused":true,"emitClose":false,"autoDestroy":false,"destroyed":false,"defaultEncoding":"utf8","awaitDrain":0,"readingMore":false,"decoder":{"encoding":"utf8"},"encoding":"utf8"},"readable":true,"_events":{},"_eventsCount":1,"path":"data.txt","fd":35,"flags":"r","mode":438,"end":null,"autoClose":true,"bytesRead":26,"closed":false}

The question why I won't be able to see the data as plaintext on client side as it is in data.txt file.

Body:
Your variable readableData contains a node.js stream object.  That's what that variable is.  It's only of use in the current node.js instance so it doesn't do anything useful to try to send that stream object to the client.

If you want to get all the data from that 'data.txt' file, you have several choices.

You can just read the whole file into a local variable with fs.readFile() and then send all that data with socket.write().

You can create a new stream attached to the file for each new incoming request and then  as the data comes in on the readStream, you can send it out on the socket (this is often referred to as piping one stream into another).  If you use higher level server constructs such as an http server, they make piping real easy.

Option #1 would look like this:

const server = net.createServer(socket => {
    socket.on('data', chunk => {
        console.log(chunk.toString());
        fs.readFile('data.txt', 'utf8', (err, data) => {
            if (err) {
                 // insert error handling here
                 console.log(err);
            } else {
                 socket.write(data);
            }
        });
    });

    socket.on('end', () => {
        console.log("done");
    })

    socket.on('close', () => {
        console.log("closed")
    })
});

FYI, you should also know that socket.on('data', chunk => {...}) can give you any size chunk of data.  TCP streams do not make any guarantees about delivering the exact same chunks of data in the same pieces that they were originally sent in.  They will come in order, but if you sent three 1k chunks from the other end, they might arrive as three separate 1k chunks, they might arrive as one 3k chunk or they might arrive as a whole bunch of much smaller chunks.  How they arrive will often depend upon what intermediate transports and routers they had to travel over and if there were any recoverable issues along that transmission.  For example, data sent over a satellite internet connection will probably arrive in small chunks because the needs of the transport broke it up into smaller pieces.

This means that reading any data over a plain TCP connection generally needs some sort of protocol so that the reader knows when they've gotten a full, meaningful chunk that they can process.  If the data is plain text, it might be as simple a protocol as every message ends with a line feed character.  But, if the data is more complex, then the protocol may need to be more complex.


问:
.NetCore 3.1 API having issues using Asp.NetCore.Odata for REST API
The main thing I want to do is I want my AspNet.Core 3.1 API to support Odata. The main thing is WebApi exposes Dto object which internally maps to entity object. I have implemented changes however keep getting 404 error. The changes I did were:

Install AspNetCore.OData 7.3.

Added changes to Startup.cs

public class Startup
    {
    public void ConfigureServices(IServiceCollection services)
       services.AddOData();
       services.AddMvc(options => options.EnableEndpointRouting = false);

```<code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
   IEdmModel model = GetEdmModel();
   app.UseMvc(builder =>
   {
            builder.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
            builder.MapODataServiceRoute("odata", "odata", model);
   });

public static IEdmModel GetEdmModel()
    {
        if (_edmModel == null)
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<CustomerDto>("CustomerDtos");
            _edmModel = builder.GetEdmModel();
        }
        return _edmModel;
    }
</code>```

}
- CustomersController changes

```<code>public class CustomersController : ControllerBase
{
    public ICustomerRepository _customers;
    public CustomersController(DbContext context)/
    {
        _customers = new CustomerRepository(context);
    }

    [HttpGet]
    [EnableQuery]
    public async Task<ActionResult<IEnumerable<CustomerDto>>> Get()
    {
        return Ok((await _customers.GetCustomers()).Select(c=>CustomerDto.MapToCustomerDto(c)));
    }
}
</code>```

However this constantly gives 404 error odata/customers

答:
If you use url/odata/customers, customers refers to an entity set named Customers. The controller name is always derived from the entity set at the root of the OData path.

Refer to https://learn.microsoft.com/en-us/odata/webapi/built-in-routing-conventions#built-in-routing-conventions-1

Solutions:

One way is keeping EntitySet name but modifying controller name

(CustomersController->CustomerDtosController ):

```<code>public class CustomerDtosController : ControllerBase
</code>```

Url:  /odata/customerDtos

Another way is keeping controller name but modifying EntitySet name:

```<code>builder.EntitySet<CustomerDto>("Customers");
</code>```

Url: odata/customers

Body:
The main thing I want to do is I want my AspNet.Core 3.1 API to support Odata. The main thing is WebApi exposes Dto object which internally maps to entity object. I have implemented changes however keep getting 404 error. The changes I did were:

Install AspNetCore.OData 7.3.

Added changes to Startup.cs

public class Startup
    {
    public void ConfigureServices(IServiceCollection services)
       services.AddOData();
       services.AddMvc(options => options.EnableEndpointRouting = false);

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
   IEdmModel model = GetEdmModel();
   app.UseMvc(builder =>
   {
            builder.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
            builder.MapODataServiceRoute("odata", "odata", model);
   });

public static IEdmModel GetEdmModel()
    {
        if (_edmModel == null)
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<CustomerDto>("CustomerDtos");
            _edmModel = builder.GetEdmModel();
        }
        return _edmModel;
    }

}
- CustomersController changes

public class CustomersController : ControllerBase
{
    public ICustomerRepository _customers;
    public CustomersController(DbContext context)/
    {
        _customers = new CustomerRepository(context);
    }

    [HttpGet]
    [EnableQuery]
    public async Task<ActionResult<IEnumerable<CustomerDto>>> Get()
    {
        return Ok((await _customers.GetCustomers()).Select(c=>CustomerDto.MapToCustomerDto(c)));
    }
}

However this constantly gives 404 error odata/customers

Body:
If you use url/odata/customers, customers refers to an entity set named Customers. The controller name is always derived from the entity set at the root of the OData path.

Refer to https://learn.microsoft.com/en-us/odata/webapi/built-in-routing-conventions#built-in-routing-conventions-1

Solutions:

One way is keeping EntitySet name but modifying controller name

(CustomersController->CustomerDtosController ):

public class CustomerDtosController : ControllerBase

Url:  /odata/customerDtos

Another way is keeping controller name but modifying EntitySet name:

builder.EntitySet<CustomerDto>("Customers");

Url: odata/customers


问:
Connect To Wifi Android Q
I'm trying to connect to wifi with below code

```<code> val specifier = WifiNetworkSpecifier.Builder()
        .setSsid(machineID).build()

    val networkRequest = NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .setNetworkSpecifier(specifier)
        .build()

    val connectivityManager = context.applicationContext
        .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?

    connectivityManager?.requestNetwork(networkRequest,object:ConnectivityManager.NetworkCallback(){
        override fun onUnavailable() {
            callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
        }

        override fun onAvailable(network: Network) {
            val wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)

            if (wifiInfo.isConnected)
                callback.onWifiConnected("${getWifiManager()?.connectionInfo?.ipAddress!!}")
            else
                callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
        }
    })
</code>```

But I'm always getting runtime error in this line

```<code>val specifier = WifiNetworkSpecifier.Builder()
</code>```

The error is something as below :

```<code>2019-09-25 13:49:00.718 28556-28556/com.aloha.asiaiot E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aloha.asiaiot, PID: 28556
java.lang.NoClassDefFoundError: Failed resolution of: Landroid/net/wifi/WifiNetworkSpecifier$Builder;
    at com.aloha.asiaiot.common.util.wifi.WifiConnectionManager.connectToWifi(WifiConnectionManager.kt:77)
    at com.aloha.asiaiot.connectivity.devicescan.data.DeviceScanNetworkRepository.connectToWifi(DeviceScanNetworkRepository.kt:48)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanRepository.connectToWifi(DeviceScanRepository.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanUseCase.connectToWifi(DeviceScanUseCase.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.viewmodel.DeviceScanViewModel.connectToWifi(DeviceScanViewModel.kt:41)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.connectToGateway(DeviceScanFragment.kt:139)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.access$connectToGateway(DeviceScanFragment.kt:29)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment$onActivityCreated$3.onClick(DeviceScanFragment.kt:72)
    at android.view.View.performClick(View.java:7339)
    at android.widget.TextView.performClick(TextView.java:14221)
    at android.view.View.performClickInternal(View.java:7305)
    at android.view.View.access$3200(View.java:846)
    at android.view.View$PerformClick.run(View.java:27787)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7058)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "android.net.wifi.WifiNetworkSpecifier$Builder" on path: DexPathList[[zip file "/data/app/com.aloha.asiaiot-k57tcS1ybEKsaCIu13TJnw==/base.apk"],nativeLibraryDirectories=[/data/app/com.aloha.asiaiot-k57tcS1ybEKsaCIu13TJnw==/lib/arm64, /system/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.aloha.asiaiot.common.util.wifi.WifiConnectionManager.connectToWifi(WifiConnectionManager.kt:77)
    at com.aloha.asiaiot.connectivity.devicescan.data.DeviceScanNetworkRepository.connectToWifi(DeviceScanNetworkRepository.kt:48)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanRepository.connectToWifi(DeviceScanRepository.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanUseCase.connectToWifi(DeviceScanUseCase.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.viewmodel.DeviceScanViewModel.connectToWifi(DeviceScanViewModel.kt:41)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.connectToGateway(DeviceScanFragment.kt:139)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.access$connectToGateway(DeviceScanFragment.kt:29)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment$onActivityCreated$3.onClick(DeviceScanFragment.kt:72)
    at android.view.View.performClick(View.java:7339)
    at android.widget.TextView.performClick(TextView.java:14221)
    at android.view.View.performClickInternal(View.java:7305)
    at android.view.View.access$3200(View.java:846)
    at android.view.View$PerformClick.run(View.java:27787)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7058)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
</code>```

2019-09-25 13:49:00.747 28556-28556/com.aloha.asiaiot

I tried also with below code for solving lower SDK :

```<code> if (Build.VERSION.SDK_INT< Build.VERSION_CODES.Q) {
        val wifiConfiguration = WifiConfiguration()
    wifiConfiguration.SSID = String.format("\"%s\"", machineID)
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED
    wifiConfiguration.priority = 40

    val wifiManager = getWifiManager()
    val netID = wifiManager?.addNetwork(wifiConfiguration)!!

    wifiManager.disconnect()
    wifiManager.enableNetwork(netID,true)
    wifiManager.reconnect()

    if (isWifiConnected(machineID))
        callback.onWifiConnected("${wifiManager.dhcpInfo.ipAddress}")
    else
        callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
    }
</code>```

and below my isWifiConnected :

```<code>private fun isWifiConnected (machineID: String) : Boolean{
    if (getWifiManager()?.isWifiEnabled!!) {
        val wifiInfo = getWifiManager()?.connectionInfo
        if (wifiInfo?.ssid==machineID)
            return true
    }

    return false
}
</code>```

But in this part I always getting false :

```<code>    wifiManager.disconnect()
    wifiManager.enableNetwork(netID,true)
    wifiManager.reconnect()
</code>```

An as per documentation it says :

This method was deprecated in API level 29.
  a) See WifiNetworkSpecifier.Builder#build() for new mechanism to trigger connection to a Wi-Fi network. b) See addNetworkSuggestions(java.util.List), removeNetworkSuggestions(java.util.List) for new API to add Wi-Fi networks for consideration when auto-connecting to wifi. Compatibility Note: For applications targeting Build.VERSION_CODES.Q or above, this API will always return false.

I'm testing in real device with OS version 9. But code running fine in emulator. Kindly advise what is possible cause. Thank you for any kind help.

答:
This is my code :

```<code>val wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager?
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        try {
            val wifiConfig = WifiConfiguration()
            wifiConfig.SSID = "\"" + yourSsid + "\""
            wifiConfig.preSharedKey = "\"" + password + "\""
            val netId = wifiManager!!.addNetwork(wifiConfig)
            wifiManager.disconnect()
            wifiManager.enableNetwork(netId, true)
            wifiManager.reconnect()
            if (isWifiConnected("\"" + deviceId + "\"")) {
                doSomethingHere()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    } else {
        val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
                .setSsid( yourSsid!! )
                .setWpa2Passphrase(password)
                .build()

        val networkRequest = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .setNetworkSpecifier(wifiNetworkSpecifier)
                .build()

        connectivityManager = Boron.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?

        networkCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onUnavailable() {
                super.onUnavailable()
            }

            override fun onLosing(network: Network, maxMsToLive: Int) {
                super.onLosing(network, maxMsToLive)

            }

            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                connectivityManager?.bindProcessToNetwork(network)
            }

            override fun onLost(network: Network) {
                super.onLost(network)

            }
        }
        connectivityManager?.requestNetwork(networkRequest,networkCallback)
    }
</code>```

Then in onDestroy
    connectivityManager?.unregisterNetworkCallback(networkCallback)

Permissions needed :

```<code> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-feature android:name="android.permission.WRITE_SETTINGS"
    android:required="false"/>
</code>```

Title: Connect To Wifi Android Q

Body:
I'm trying to connect to wifi with below code

 val specifier = WifiNetworkSpecifier.Builder()
        .setSsid(machineID).build()

    val networkRequest = NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .setNetworkSpecifier(specifier)
        .build()

    val connectivityManager = context.applicationContext
        .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?

    connectivityManager?.requestNetwork(networkRequest,object:ConnectivityManager.NetworkCallback(){
        override fun onUnavailable() {
            callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
        }

        override fun onAvailable(network: Network) {
            val wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)

            if (wifiInfo.isConnected)
                callback.onWifiConnected("${getWifiManager()?.connectionInfo?.ipAddress!!}")
            else
                callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
        }
    })

But I'm always getting runtime error in this line

val specifier = WifiNetworkSpecifier.Builder()

The error is something as below :

2019-09-25 13:49:00.718 28556-28556/com.aloha.asiaiot E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aloha.asiaiot, PID: 28556
java.lang.NoClassDefFoundError: Failed resolution of: Landroid/net/wifi/WifiNetworkSpecifier$Builder;
    at com.aloha.asiaiot.common.util.wifi.WifiConnectionManager.connectToWifi(WifiConnectionManager.kt:77)
    at com.aloha.asiaiot.connectivity.devicescan.data.DeviceScanNetworkRepository.connectToWifi(DeviceScanNetworkRepository.kt:48)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanRepository.connectToWifi(DeviceScanRepository.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanUseCase.connectToWifi(DeviceScanUseCase.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.viewmodel.DeviceScanViewModel.connectToWifi(DeviceScanViewModel.kt:41)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.connectToGateway(DeviceScanFragment.kt:139)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.access$connectToGateway(DeviceScanFragment.kt:29)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment$onActivityCreated$3.onClick(DeviceScanFragment.kt:72)
    at android.view.View.performClick(View.java:7339)
    at android.widget.TextView.performClick(TextView.java:14221)
    at android.view.View.performClickInternal(View.java:7305)
    at android.view.View.access$3200(View.java:846)
    at android.view.View$PerformClick.run(View.java:27787)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7058)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "android.net.wifi.WifiNetworkSpecifier$Builder" on path: DexPathList[[zip file "/data/app/com.aloha.asiaiot-k57tcS1ybEKsaCIu13TJnw==/base.apk"],nativeLibraryDirectories=[/data/app/com.aloha.asiaiot-k57tcS1ybEKsaCIu13TJnw==/lib/arm64, /system/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.aloha.asiaiot.common.util.wifi.WifiConnectionManager.connectToWifi(WifiConnectionManager.kt:77)
    at com.aloha.asiaiot.connectivity.devicescan.data.DeviceScanNetworkRepository.connectToWifi(DeviceScanNetworkRepository.kt:48)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanRepository.connectToWifi(DeviceScanRepository.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanUseCase.connectToWifi(DeviceScanUseCase.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.viewmodel.DeviceScanViewModel.connectToWifi(DeviceScanViewModel.kt:41)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.connectToGateway(DeviceScanFragment.kt:139)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.access$connectToGateway(DeviceScanFragment.kt:29)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment$onActivityCreated$3.onClick(DeviceScanFragment.kt:72)
    at android.view.View.performClick(View.java:7339)
    at android.widget.TextView.performClick(TextView.java:14221)
    at android.view.View.performClickInternal(View.java:7305)
    at android.view.View.access$3200(View.java:846)
    at android.view.View$PerformClick.run(View.java:27787)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7058)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

2019-09-25 13:49:00.747 28556-28556/com.aloha.asiaiot

I tried also with below code for solving lower SDK :

 if (Build.VERSION.SDK_INT< Build.VERSION_CODES.Q) {
        val wifiConfiguration = WifiConfiguration()
    wifiConfiguration.SSID = String.format("\"%s\"", machineID)
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED
    wifiConfiguration.priority = 40

    val wifiManager = getWifiManager()
    val netID = wifiManager?.addNetwork(wifiConfiguration)!!

    wifiManager.disconnect()
    wifiManager.enableNetwork(netID,true)
    wifiManager.reconnect()

    if (isWifiConnected(machineID))
        callback.onWifiConnected("${wifiManager.dhcpInfo.ipAddress}")
    else
        callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
    }

and below my isWifiConnected :

private fun isWifiConnected (machineID: String) : Boolean{
    if (getWifiManager()?.isWifiEnabled!!) {
        val wifiInfo = getWifiManager()?.connectionInfo
        if (wifiInfo?.ssid==machineID)
            return true
    }

    return false
}

But in this part I always getting false :

    wifiManager.disconnect()
    wifiManager.enableNetwork(netID,true)
    wifiManager.reconnect()

An as per documentation it says :

This method was deprecated in API level 29.
  a) See WifiNetworkSpecifier.Builder#build() for new mechanism to trigger connection to a Wi-Fi network. b) See addNetworkSuggestions(java.util.List), removeNetworkSuggestions(java.util.List) for new API to add Wi-Fi networks for consideration when auto-connecting to wifi. Compatibility Note: For applications targeting Build.VERSION_CODES.Q or above, this API will always return false.

I'm testing in real device with OS version 9. But code running fine in emulator. Kindly advise what is possible cause. Thank you for any kind help.

Body:
This is my code :

val wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager?
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        try {
            val wifiConfig = WifiConfiguration()
            wifiConfig.SSID = "\"" + yourSsid + "\""
            wifiConfig.preSharedKey = "\"" + password + "\""
            val netId = wifiManager!!.addNetwork(wifiConfig)
            wifiManager.disconnect()
            wifiManager.enableNetwork(netId, true)
            wifiManager.reconnect()
            if (isWifiConnected("\"" + deviceId + "\"")) {
                doSomethingHere()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    } else {
        val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
                .setSsid( yourSsid!! )
                .setWpa2Passphrase(password)
                .build()

        val networkRequest = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .setNetworkSpecifier(wifiNetworkSpecifier)
                .build()

        connectivityManager = Boron.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?

        networkCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onUnavailable() {
                super.onUnavailable()
            }

            override fun onLosing(network: Network, maxMsToLive: Int) {
                super.onLosing(network, maxMsToLive)

            }

            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                connectivityManager?.bindProcessToNetwork(network)
            }

            override fun onLost(network: Network) {
                super.onLost(network)

            }
        }
        connectivityManager?.requestNetwork(networkRequest,networkCallback)
    }

Then in onDestroy
    connectivityManager?.unregisterNetworkCallback(networkCallback)

Permissions needed :

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-feature android:name="android.permission.WRITE_SETTINGS"
    android:required="false"/>


问:
Headless chrome browser disconnected. This problem may appear when a browser hangs or is closed, or due to network
Version of testcafe - 1.7.0 and 1.7.1 (most recent)
Version of chrome - 78.0.3904.108
Running env - Linux

Running it via Jenkins
This test job was running absolutely fine for the last 4 months till last week but then started getting browser disconnected error.

Jenkins testcafe command - testcafe -c 3 chromium:headless --headless --no-sandbox --disable-background-networking --disable-default-apps --disable-extensions --disable-gpu --disable-sync --disable-translate --hide-scrollbars --metrics-recording-only --mute-audio --no-first-run --safebrowsing-disable-auto-update {*.js,**/*.js} -e --fixture-meta ${params.TestType}=true --env=${params.TestEnv}"

Please note - When I run tests on my local or via docker, they run well.

DockerFile

```<code>FROM testcafe/testcafe
USER root
RUN npm install
RUN npm install minimist
</code>```

答: We had similar issue and fixed it by replacing chrome:headless with firefox:headless.

Body:
Version of testcafe - 1.7.0 and 1.7.1 (most recent)
Version of chrome - 78.0.3904.108
Running env - Linux

Running it via Jenkins
This test job was running absolutely fine for the last 4 months till last week but then started getting browser disconnected error.

Jenkins testcafe command - testcafe -c 3 chromium:headless --headless --no-sandbox --disable-background-networking --disable-default-apps --disable-extensions --disable-gpu --disable-sync --disable-translate --hide-scrollbars --metrics-recording-only --mute-audio --no-first-run --safebrowsing-disable-auto-update {*.js,**/*.js} -e --fixture-meta ${params.TestType}=true --env=${params.TestEnv}"

Please note - When I run tests on my local or via docker, they run well.

DockerFile

FROM testcafe/testcafe
USER root
RUN npm install
RUN npm install minimist


问:
Flutter Audio with Circle Progress
I need to create a screen that plays back mp4 audio files, with play, pause, stop controls and shows progress via a circle progress indictor. Does anyone know if a package exists for this, or combination of packages?
So what I am trying to create would be similar to the following:

答: I made a clone of the Circular Progress Indicator using the documentation described by pskink in the comments enter link description here . Many thanks and gratitude to him for helping with this.</p>

Title: Flutter Audio with Circle Progress


问:
replace literal value by variable in for loop
I have this code that works as expected. "db" is MongoClient object.

```<code>collections = {
    "cmrb": cmrb,
    "rbss": rbss,
    "ndrb": ndrb,
    "nder": nder,
    "rbph": rbph,
    "rb90": rb90,
    "rbphne": rbphne,
    "dirb": dirb,
}

c=db.cmrb
c.insert_one(collections['cmrb'])
</code>```

But when I replace the collection name with variable i using for loop, all the entries gets added to collection "i" and not to "cmrb", "rbss" etc.

```<code>for i in collections.keys():
    c = db.i
    c.insert_one(collections[i])
</code>```

What is wrong with the code mentioned above? How do I replace the literal "i"?

答:
try this:

```<code>for i in collections.keys():
    c = db[i]
    c.insert_one(collections[i])
</code>```

the i in db.i does not refer to the i in the for loop. db.i will simply create (in first iteration) or get(in other iterations) a database/collection named i. From the docs:

db[collection_name] || db.collection_name Get the collection_name Collection of Database db.

Body:
I have this code that works as expected. "db" is MongoClient object.

collections = {
    "cmrb": cmrb,
    "rbss": rbss,
    "ndrb": ndrb,
    "nder": nder,
    "rbph": rbph,
    "rb90": rb90,
    "rbphne": rbphne,
    "dirb": dirb,
}

c=db.cmrb
c.insert_one(collections['cmrb'])

But when I replace the collection name with variable i using for loop, all the entries gets added to collection "i" and not to "cmrb", "rbss" etc.

for i in collections.keys():
    c = db.i
    c.insert_one(collections[i])

What is wrong with the code mentioned above? How do I replace the literal "i"?

Body:
try this:

for i in collections.keys():
    c = db[i]
    c.insert_one(collections[i])

the i in db.i does not refer to the i in the for loop. db.i will simply create (in first iteration) or get(in other iterations) a database/collection named i. From the docs:

db[collection_name] || db.collection_name Get the collection_name Collection of Database db.