问:
How to skip one of the dependency file to not include while creating target library
I want to create a library skipping one of the dependency file not to include while creating the same.

Eg:-

```<code>liba.so: a.o b.o c.o test.psm
        <command for creating liba.so, which includes all its dependencies.>
</code>```

Here when there is a change is any of its dependencies i have to create liba.so file. But .so file should include only .o files and not test.psm file.

It will throw the error when we try to create .so file with non-object file.

Please help me how can we achieve this using GNUmake.

答:
The best way to solve the problem is to avoid it.  I see absolutely no reason to rebuild a library that exists already and whose prerequisites have not changed since it was last built. If for some bizarre reason one wants to ensure that the library's timestamp is not earlier than that of some associated documentation file, then the best alternatives would run along the lines of creating a separate process around maintaining or distributing that file. For example,

touch a corresponding source file whenever the documentation file is changed; or

build the documentation from the corresponding source, such as via a Doxygen or a similar tool, so that it is a built artifact that shares the same prerequisites as the library; or

manage timestamps as part of the installation / distribution process instead of the build process.  For instance, make a copy, without timestamp preservation, before installing or distributing the built files, so that all the files in the copy are timestamped as of the copying.

But if you must obey the dictates of a pointy-haired boss who will not accept pushback, then the answer to the actual question is that make does not have any special variable or operator for designating subsets of rules' prerequisite lists, but you nevertheless have plenty of options for writing the recipe appropriately.  This then becomes about the details of of the rule's recipe.

If one starts with

```<code>liba.so: a.o b.o c.o
        $(archiver_command) $(archiver_options) a.o b.o c.o
</code>```

then one can add test.psm to the prerequisite list without any other changes.

Suppose one starts with a rule of this form, however:

```<code>liba.so: a.o b.o c.o
        $(archiver_command) $(archiver_options) $^
</code>```

.  The recipe uses the automatic variable $^ to refer to the (whole) list of prerequisites, so if one adds test.psm as a new prerequisite then it would be included, too, which you do not want.  You have multiple options here, among them

Use shell code in the recipe to process the prerequisite list and remove the last element.  This is a bit nasty.

Rewrite the recipe in the previous form, with an explicit list of objects in the recipe instead of a variable.  This carries an added maintenance burden, however.

Designate the real prerequisites via a user-defined variable, and use that in the recipe, too.  This may be particularly natural in view of the fact that it is common for there already to be just such a variable.

The last alternative would be my recommendation.  Specifically, it would look something like this:

```<code>A_OBJS = a.o b.o c.o

# ...

liba.so: $(A_OBJS) test.psm
        $(archiver_command) $(archiver_options) $(A_OBJS)
</code>```

Body:
I want to create a library skipping one of the dependency file not to include while creating the same.

Eg:-

liba.so: a.o b.o c.o test.psm
        <command for creating liba.so, which includes all its dependencies.>

Here when there is a change is any of its dependencies i have to create liba.so file. But .so file should include only .o files and not test.psm file.

It will throw the error when we try to create .so file with non-object file.

Please help me how can we achieve this using GNUmake.

Body:
The best way to solve the problem is to avoid it.  I see absolutely no reason to rebuild a library that exists already and whose prerequisites have not changed since it was last built. If for some bizarre reason one wants to ensure that the library's timestamp is not earlier than that of some associated documentation file, then the best alternatives would run along the lines of creating a separate process around maintaining or distributing that file. For example,

touch a corresponding source file whenever the documentation file is changed; or

build the documentation from the corresponding source, such as via a Doxygen or a similar tool, so that it is a built artifact that shares the same prerequisites as the library; or

manage timestamps as part of the installation / distribution process instead of the build process.  For instance, make a copy, without timestamp preservation, before installing or distributing the built files, so that all the files in the copy are timestamped as of the copying.

But if you must obey the dictates of a pointy-haired boss who will not accept pushback, then the answer to the actual question is that make does not have any special variable or operator for designating subsets of rules' prerequisite lists, but you nevertheless have plenty of options for writing the recipe appropriately.  This then becomes about the details of of the rule's recipe.

If one starts with

liba.so: a.o b.o c.o
        $(archiver_command) $(archiver_options) a.o b.o c.o

then one can add test.psm to the prerequisite list without any other changes.

Suppose one starts with a rule of this form, however:

liba.so: a.o b.o c.o
        $(archiver_command) $(archiver_options) $^

.  The recipe uses the automatic variable $^ to refer to the (whole) list of prerequisites, so if one adds test.psm as a new prerequisite then it would be included, too, which you do not want.  You have multiple options here, among them

Use shell code in the recipe to process the prerequisite list and remove the last element.  This is a bit nasty.

Rewrite the recipe in the previous form, with an explicit list of objects in the recipe instead of a variable.  This carries an added maintenance burden, however.

Designate the real prerequisites via a user-defined variable, and use that in the recipe, too.  This may be particularly natural in view of the fact that it is common for there already to be just such a variable.

The last alternative would be my recommendation.  Specifically, it would look something like this:

A_OBJS = a.o b.o c.o

# ...

liba.so: $(A_OBJS) test.psm
        $(archiver_command) $(archiver_options) $(A_OBJS)


来源: stackexchange

问:
Keyboard is hidden on orientation change
My keyboard is hidden when the orientation of the android phone changes to landscape. What should I do in order to show my keyboard?</p>

答:
```<code>getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
</code>```

put this in onCreate() and onResume() in your class file.

ContentLicense: CC BY-SA 3.0

Body:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

put this in onCreate() and onResume() in your class file.


问:
Getting error at the time of Use-AzureSqlJobConnection -CurrentAzureSubscription
I am trying to execute the script on an elastic pool using powershell. When I execute this command,

Use-AzureSqlJobConnection -CurrentAzureSubscription -ResourceGroupName {ABC}

It is giving me error for, Use-AzureSqlJobConnection : No Elastic Database Jobs control database found.

Please help me with what I am missing here, to create something in the portal ?

Thanks in advance.

答:
If you are trying to execute a script on your databases using elastic jobs, you should first Create and configure the agent, the elastic database job agent (it is a service running on azure for automation on Azure SQL Databases).
in this case you should look into the links about it:

some overview about the service:

https://learn.microsoft.com/en-us/azure/sql-database/elastic-jobs-overview

configure the servic jobs using Powershell:

https://learn.microsoft.com/en-us/azure/sql-database/elastic-jobs-powershell

configure the servic jobs using TSQL:

https://learn.microsoft.com/en-us/azure/sql-database/elastic-jobs-tsql

If you just want to to use Power Shell to run the same script on all of your databases (once),
you may want to use another script dew to -ResourceGroupName is a property of Elastic jobs.
you should try using command like Invoke-Sqlcmd, iterating on all databases in the elastic pool.

https://learn.microsoft.com/en-us/powershell/module/sqlserver/invoke-sqlcmd?view=sqlserver-ps

I recommend you to try look into the Powershell Model dbatools (https://dbatools.io/)
it has a lot of useful powershell commands ready to use.

ContentLicense: CC BY-SA 4.0


问:
How to hide component with a certain condition?
I have a angular 8 application. And I want to hide a component if a condition is true.

The condition is this:

```<code>"status === EcheqSubmissionStatus.EXPIRED"
</code>```

So I tried like this:

EcheqProcessComponent template:

```<code> <div *ngIf="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED">

    <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"
      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"
      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>
  </div>
</code>```

EcheqProcessComponent ts file:

```<code>export class EcheqProcessComponent   implements OnInit {
  @ViewChild(EcheqPageComponent, {static: false}) pageComponent: EcheqPageComponent;
  EcheqSubmissionStatus = EcheqSubmissionStatus;
  eCheqLoaded = false;
  eCheqError = false;
  currentEcheqSubmission: EcheqSubmission;
  currentEcheqDefinition: EcheqDefinition;
  currentEcheqPages: Array<EcheqPage>;
  currentEcheqPager: EcheqPager;
  currentEcheqPage: EcheqPage;
  currentEcheqPageIdx: number;
  currentEcheqId: string;
  currentEcheqPath = new Array<number>();
  sending = false;
  submitting = false;
</code>```

But now always the navigation buttons are not visible. What not has to be.

and this is the ts of EcheqProgressNavComponent:

```<code>export class EcheqProgressNavComponent extends EcheqElementComponent implements OnInit {
  EcheqSubmissionStatus = EcheqSubmissionStatus;
  @Input() currentPage: number;
  @Input() totalPages: number;
  @Input() conditionals: { isFirst?: boolean; sending?: boolean };

  @Output() previous = new EventEmitter<void>();
  @Output() next = new EventEmitter<void>();
  @Input() isbtnDisabled = true;
  @Input()  showComponent = false;

  ngOnInit() {}
}
</code>```

Yes, I also tried that of course:

```<code> <div *ngIf="currentEcheqSubmission.status !== EcheqSubmissionStatus.EXPIRED">

    <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>
</code>```

But then the component is still visible.

答:
```<code>    <div *ngIf="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED">
</code>```

This *ngIf shows the div if the condition if true. If you want to hide it, you need to negate the condition.

```<code>    <div *ngIf="currentEcheqSubmission.status !== EcheqSubmissionStatus.EXPIRED">
</code>```

Body:
I have a angular 8 application. And I want to hide a component if a condition is true.

The condition is this:

"status === EcheqSubmissionStatus.EXPIRED"

So I tried like this:

EcheqProcessComponent template:

    <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"
      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"
      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

EcheqProcessComponent ts file:

export class EcheqProcessComponent   implements OnInit {
  @ViewChild(EcheqPageComponent, {static: false}) pageComponent: EcheqPageComponent;
  EcheqSubmissionStatus = EcheqSubmissionStatus;
  eCheqLoaded = false;
  eCheqError = false;
  currentEcheqSubmission: EcheqSubmission;
  currentEcheqDefinition: EcheqDefinition;
  currentEcheqPages: Array<EcheqPage>;
  currentEcheqPager: EcheqPager;
  currentEcheqPage: EcheqPage;
  currentEcheqPageIdx: number;
  currentEcheqId: string;
  currentEcheqPath = new Array<number>();
  sending = false;
  submitting = false;

But now always the navigation buttons are not visible. What not has to be.

and this is the ts of EcheqProgressNavComponent:

export class EcheqProgressNavComponent extends EcheqElementComponent implements OnInit {
  EcheqSubmissionStatus = EcheqSubmissionStatus;
  @Input() currentPage: number;
  @Input() totalPages: number;
  @Input() conditionals: { isFirst?: boolean; sending?: boolean };

  @Output() previous = new EventEmitter<void>();
  @Output() next = new EventEmitter<void>();
  @Input() isbtnDisabled = true;
  @Input()  showComponent = false;

  ngOnInit() {}
}

Yes, I also tried that of course:

    <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

But then the component is still visible.

Body:
    <div *ngIf="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED">

This *ngIf shows the div if the condition if true. If you want to hide it, you need to negate the condition.

    <div *ngIf="currentEcheqSubmission.status !== EcheqSubmissionStatus.EXPIRED">


问:
Is there any way to add FieldValue.increment() inside FieldValue.arrayUnion?
I created a shopping cart app. When user clicks the same product I want to increment number.
if the user clicks the same item 10 times, I want to update firestore like this.

items:[{'productId':'1234','count':10},{'productId':'1111','count':1}]

So, I decided to use FieldValue.increment(1). But I got an error when adding it inside arrayUnion

Error

```<code>Unhandled Exception: PlatformException(error, Invalid data. FieldValue.increment() can only be used with set() and update(), null)
</code>```

code

```<code>  Future<void> addToCart(ProductModel model){
    var ref = _db.collection('cart').document('7iRLSvH5sgMjaBNw0V4E');

    return ref.setData({
      'userId':'1234',
      'items':FieldValue.arrayUnion([{
        'count':FieldValue.increment(1),
        'productId':model.subCategoryId,
        'productName':model.subCategoryName
      }])
    },merge: true);
  }
</code>```

答:
Invalid data. FieldValue.increment() can only be used with set() and update(), null)

As the error clearly states, you can use FieldValue.increment() only when using set() and update() functions and not when using FieldValue.arrayUnion. You cannot add an element to an array and increment one of its elements at the same time. Besides that, FieldValue.increment() can only increment a property of type number which should exist distinct within a document and not as a member of an array.

If you need to increment the value of an array member, you should get that array on the client, get the desired element, update it and then write the document back.

Edit:

If the following item:

```<code>[{'productId':'1234','count':10}]
</code>```

It is an object with two properties that exist within an array of objects, you cannot use FieldValue.increment(), to increment the count property of a single object. You cannot simply map that object into a custom object. Actually, you have in your document a list of HashMaps. So you need to write code for that, by iterating through the list, find the corresponding count property you want to increment, increment it and then write the document back.

Body:
I created a shopping cart app. When user clicks the same product I want to increment number.
if the user clicks the same item 10 times, I want to update firestore like this.

items:[{'productId':'1234','count':10},{'productId':'1111','count':1}]

So, I decided to use FieldValue.increment(1). But I got an error when adding it inside arrayUnion

Error

Unhandled Exception: PlatformException(error, Invalid data. FieldValue.increment() can only be used with set() and update(), null)

code

  Future<void> addToCart(ProductModel model){
    var ref = _db.collection('cart').document('7iRLSvH5sgMjaBNw0V4E');

    return ref.setData({
      'userId':'1234',
      'items':FieldValue.arrayUnion([{
        'count':FieldValue.increment(1),
        'productId':model.subCategoryId,
        'productName':model.subCategoryName
      }])
    },merge: true);
  }

Body:
Invalid data. FieldValue.increment() can only be used with set() and update(), null)

As the error clearly states, you can use FieldValue.increment() only when using set() and update() functions and not when using FieldValue.arrayUnion. You cannot add an element to an array and increment one of its elements at the same time. Besides that, FieldValue.increment() can only increment a property of type number which should exist distinct within a document and not as a member of an array.

If you need to increment the value of an array member, you should get that array on the client, get the desired element, update it and then write the document back.

Edit:

If the following item:

[{'productId':'1234','count':10}]

It is an object with two properties that exist within an array of objects, you cannot use FieldValue.increment(), to increment the count property of a single object. You cannot simply map that object into a custom object. Actually, you have in your document a list of HashMaps. So you need to write code for that, by iterating through the list, find the corresponding count property you want to increment, increment it and then write the document back.


问:
How to add non-english characters on a screen title in pygame?
I wanted to make a program with some cyrillic text in it. I made this code that would open up a window, have a title in Russian, and would put some Russian text (meaning Rasputin) on screen.The cyrillic font file supports cyrillic text.

```<code>import pygame as pg

pg.init()
pg.font.init()
font = pg.font.Font("Cyrillic-font.ttf",24)
gameDisplay = pg.display.set_mode((600, 400))
pg.display.set_caption("Распутин")

gameExit = False

while not gameExit:
    for event in pg.event.get():
        if event.type == pg.QUIT:
             gameExit = True
    gameDisplay.fill((255,255,255))
    text = font.render("Распутин",True,(255,0,0))
    gameDisplay.blit(text,(200,200))
    pg.display.update()
quit()
</code>```

The program will display the text onto the screen. However, in the title, all that appears is "????????". I've attempted to use the font.render into the pg.display.set_caption(), but that wouldn't work as font.render gives a pygame surface instead of a string, so the code would stop.

答:
In my opinion, it is an operative system design failure.

In windows 10 Pro I just changed "Region Settings" to Russian. Find it in "Region, Administrative". All keep old language and text Russian text has Cyrillic letters.

Maybe is not the best solution, but it works.

Body:
I wanted to make a program with some cyrillic text in it. I made this code that would open up a window, have a title in Russian, and would put some Russian text (meaning Rasputin) on screen.The cyrillic font file supports cyrillic text.

import pygame as pg

pg.init()
pg.font.init()
font = pg.font.Font("Cyrillic-font.ttf",24)
gameDisplay = pg.display.set_mode((600, 400))
pg.display.set_caption("Распутин")

gameExit = False

while not gameExit:
    for event in pg.event.get():
        if event.type == pg.QUIT:
             gameExit = True
    gameDisplay.fill((255,255,255))
    text = font.render("Распутин",True,(255,0,0))
    gameDisplay.blit(text,(200,200))
    pg.display.update()
quit()

The program will display the text onto the screen. However, in the title, all that appears is "????????". I've attempted to use the font.render into the pg.display.set_caption(), but that wouldn't work as font.render gives a pygame surface instead of a string, so the code would stop.


问:
Why echo of combined variables in for loop doesn't work?
what is wrong with "echo" line in my loop?
It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ?
After loop is done, I do "manual check" of the saver variables and they apparently exist.

Script:

```<code>#!/bin/bash
for i in {1..3}
 do
  read -p "Insert value $i: " v$i
  echo "you wrote " $v$i          #I have problem in this line
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
</code>```

Console output:

```<code>./input_2.sh
Insert value 1: what
you wrote  1              #output should be: you wrote what
Insert value 2: the
you wrote  2              #output should be: you wrote the
Insert value 3: hell
you wrote  3              #output should be: you wrote hell

check of saved values:
what
the
hell
</code>```

Thanks

答:
As pointed out, you need indirect variable expansion. However, you can also use an array to group related values. v[$i] is a valid name for read.

```<code>for i in {1..3}
 do
  read -p "Insert value $i: " "v[$i]"
  echo "you wrote ${v[$i]}"
 done

echo
echo "check of saved values:"
echo "${v[1]}"
echo "${v[2]}"
echo "${v[3]}"
</code>```

Body:
what is wrong with "echo" line in my loop?
It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ?
After loop is done, I do "manual check" of the saver variables and they apparently exist.

Script:

#!/bin/bash
for i in {1..3}
 do
  read -p "Insert value $i: " v$i
  echo "you wrote " $v$i          #I have problem in this line
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3

Console output:

./input_2.sh
Insert value 1: what
you wrote  1              #output should be: you wrote what
Insert value 2: the
you wrote  2              #output should be: you wrote the
Insert value 3: hell
you wrote  3              #output should be: you wrote hell

check of saved values:
what
the
hell

Thanks

Body:
As pointed out, you need indirect variable expansion. However, you can also use an array to group related values. v[$i] is a valid name for read.

for i in {1..3}
 do
  read -p "Insert value $i: " "v[$i]"
  echo "you wrote ${v[$i]}"
 done

echo
echo "check of saved values:"
echo "${v[1]}"
echo "${v[2]}"
echo "${v[3]}"


问:
Here Maps autocomplete geocode has some strange issue with language translation
Using the here maps autocomplete.geocoder.api v6.2 and passing &language=en parameter, a search returns results with the "label" instead of English language with French language.

This is GET endpoint I'm calling with all the other parameters i use

```<code>https://autocomplete.geocoder.api.here.com/6.2/suggest.json
?query=c
&mapview=51.756414,-0.652059,51.309901,0.331888
&app_code=MY_APP_CODE
&app_id=MY_APP_ID
maxresults=15
&country=GBR
&prox=51.508530,-0.076132,30000
&language=en

</code>```

The result of the above GET endpoint call is this json

```<code>{
  "suggestions": [
    {
      "label": "United Kingdom, Comté d'Oxford",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_HTKAfbquVEou80WZXdrniC",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté d'Oxford"
      },
      "distance": 86196,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Hertford",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_szH9Ci92RVY5reHH1VSa6A",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Hertford"
      },
      "distance": 26970,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Hampshire",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_IBS0mvpblzLbehAjAMG7.C",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Hampshire"
      },
      "distance": 114129,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Berk",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_n-TkgE8S4qt9kGGUkawVGB",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Berk"
      },
      "distance": 61719,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Buckingham",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_vX7N0mZ1b4HC5V1DXwy3iA",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Buckingham"
      },
      "distance": 75626,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, CR0 1, Croydon",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_gbk1f7HBWIP8q34qF94w6A",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Surrey",
        "city": "Croydon",
        "postalCode": "CR0 1"
      },
      "distance": 15228,
      "matchLevel": "city"
    },
    {
      "label": "United Kingdom, London, City of London",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_OIY4l1Ys6bIUnZCJo8RQ7B",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "London",
        "city": "London",
        "district": "City of London",
        "postalCode": "EC1A 4"
      },
      "distance": 1986,
      "matchLevel": "district"
    },
    {
      "label": "United Kingdom, CR0 1, Croydon, Croydon",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_A-KWPtq3xkU9R1OFqELWpA",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Surrey",
        "city": "Croydon",
        "district": "Croydon",
        "postalCode": "CR0 1"
      },
      "distance": 15228,
      "matchLevel": "district"
    },
    {
      "label": "United Kingdom, Comté de Bedford",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_ajXmsYY9XFqUFqvj1ba7wA",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Bedford"
      },
      "distance": 47643,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Warwick",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_9PDEEpbiURmpFWb9vPQpeD",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Warwick"
      },
      "distance": 147331,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, CT1 2, Canterbury",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_VD8YPCI.JUqDjxD8sP84AC",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Kent",
        "city": "Canterbury",
        "postalCode": "CT1 2"
      },
      "distance": 83989,
      "matchLevel": "city"
    },
    {
      "label": "United Kingdom, Comté de Northampton",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_zORnAshlbaC1KPrAO3l7xB",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Northampton"
      },
      "distance": 98330,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, CT1 2, Canterbury, Canterbury",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_jqhKXfcVudUg4b2WGi6teB",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Kent",
        "city": "Canterbury",
        "district": "Canterbury",
        "postalCode": "CT1 2"
      },
      "distance": 83989,
      "matchLevel": "district"
    },
    {
      "label": "United Kingdom, Comté d'Oxford, OX3 0, Oxford, Cheney Student Village",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_Q2z9awYLuQ7mVhvrPipzjC",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté d'Oxford",
        "city": "Oxford",
        "district": "Oxford",
        "street": "Cheney Student Village",
        "postalCode": "OX3 0"
      },
      "distance": 84092,
      "matchLevel": "street"
    },
    {
      "label": "United Kingdom, Comté d'Oxford, OX1 3, Oxford, Catte Street",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_bQFSMkK5C8pdIWfOI.zTZB",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté d'Oxford",
        "city": "Oxford",
        "district": "Oxford",
        "street": "Catte Street",
        "postalCode": "OX1 3"
      },
      "distance": 85769,
      "matchLevel": "street"
    }
  ]
}
</code>```

Notice that the "label":"United Kingdom, Comté d'Oxford" is in French language instead of the one expected that is English since I'm using the language:en parameter

答:
Regarding documentation on scroll please to language parameter :  The preferred language of address elements in the result.

The language parameter must be provided as 2-letter ISO language code. The plural form of the parameter (languages) is not supported and ignored. Only one language can be provided. The language setting changes the language of result elements where available in the map data. The language setting has no impact on matching or ranking and it does not express any regional preference.

The default response language is the language that is most relevant to the query.

Also, the language parameter has no impact on which results are returned because is a preferred(not required), in other words to say the "query" parameter has higher priority(has more impact on matching) unlike the "language" parameter.

Body:
Using the here maps autocomplete.geocoder.api v6.2 and passing &language=en parameter, a search returns results with the "label" instead of English language with French language.

This is GET endpoint I'm calling with all the other parameters i use

https://autocomplete.geocoder.api.here.com/6.2/suggest.json
?query=c
&mapview=51.756414,-0.652059,51.309901,0.331888
&app_code=MY_APP_CODE
&app_id=MY_APP_ID
maxresults=15
&country=GBR
&prox=51.508530,-0.076132,30000
&language=en

The result of the above GET endpoint call is this json

{
  "suggestions": [
    {
      "label": "United Kingdom, Comté d'Oxford",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_HTKAfbquVEou80WZXdrniC",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté d'Oxford"
      },
      "distance": 86196,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Hertford",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_szH9Ci92RVY5reHH1VSa6A",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Hertford"
      },
      "distance": 26970,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Hampshire",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_IBS0mvpblzLbehAjAMG7.C",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Hampshire"
      },
      "distance": 114129,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Berk",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_n-TkgE8S4qt9kGGUkawVGB",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Berk"
      },
      "distance": 61719,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Buckingham",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_vX7N0mZ1b4HC5V1DXwy3iA",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Buckingham"
      },
      "distance": 75626,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, CR0 1, Croydon",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_gbk1f7HBWIP8q34qF94w6A",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Surrey",
        "city": "Croydon",
        "postalCode": "CR0 1"
      },
      "distance": 15228,
      "matchLevel": "city"
    },
    {
      "label": "United Kingdom, London, City of London",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_OIY4l1Ys6bIUnZCJo8RQ7B",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "London",
        "city": "London",
        "district": "City of London",
        "postalCode": "EC1A 4"
      },
      "distance": 1986,
      "matchLevel": "district"
    },
    {
      "label": "United Kingdom, CR0 1, Croydon, Croydon",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_A-KWPtq3xkU9R1OFqELWpA",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Surrey",
        "city": "Croydon",
        "district": "Croydon",
        "postalCode": "CR0 1"
      },
      "distance": 15228,
      "matchLevel": "district"
    },
    {
      "label": "United Kingdom, Comté de Bedford",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_ajXmsYY9XFqUFqvj1ba7wA",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Bedford"
      },
      "distance": 47643,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, Comté de Warwick",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_9PDEEpbiURmpFWb9vPQpeD",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Warwick"
      },
      "distance": 147331,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, CT1 2, Canterbury",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_VD8YPCI.JUqDjxD8sP84AC",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Kent",
        "city": "Canterbury",
        "postalCode": "CT1 2"
      },
      "distance": 83989,
      "matchLevel": "city"
    },
    {
      "label": "United Kingdom, Comté de Northampton",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_zORnAshlbaC1KPrAO3l7xB",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté de Northampton"
      },
      "distance": 98330,
      "matchLevel": "county"
    },
    {
      "label": "United Kingdom, CT1 2, Canterbury, Canterbury",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_jqhKXfcVudUg4b2WGi6teB",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Kent",
        "city": "Canterbury",
        "district": "Canterbury",
        "postalCode": "CT1 2"
      },
      "distance": 83989,
      "matchLevel": "district"
    },
    {
      "label": "United Kingdom, Comté d'Oxford, OX3 0, Oxford, Cheney Student Village",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_Q2z9awYLuQ7mVhvrPipzjC",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté d'Oxford",
        "city": "Oxford",
        "district": "Oxford",
        "street": "Cheney Student Village",
        "postalCode": "OX3 0"
      },
      "distance": 84092,
      "matchLevel": "street"
    },
    {
      "label": "United Kingdom, Comté d'Oxford, OX1 3, Oxford, Catte Street",
      "language": "en",
      "countryCode": "GBR",
      "locationId": "NT_bQFSMkK5C8pdIWfOI.zTZB",
      "address": {
        "country": "United Kingdom",
        "state": "England",
        "county": "Comté d'Oxford",
        "city": "Oxford",
        "district": "Oxford",
        "street": "Catte Street",
        "postalCode": "OX1 3"
      },
      "distance": 85769,
      "matchLevel": "street"
    }
  ]
}

Notice that the "label":"United Kingdom, Comté d'Oxford" is in French language instead of the one expected that is English since I'm using the language:en parameter


问:
Missing sudo password in Ansible
Ansible asks for sudo password from following code, it tries to create a new postgres user.

Error message:

fatal: [xxx.xxx.xxx.xxx] => Missing sudo password

main.yml

```<code>- name: 'Provision a PostgreSQL server'
  hosts: "dbservers"
  sudo: yes
  sudo_user: postgres
  roles:
    - postgres
</code>```

create_db.yml

```<code>- name: Make sure the PostgreSQL users are present
  postgresql_user: name=rails password=secret role_attr_flags=CREATEDB,NOSUPERUSER
  sudo_user: postgres
  sudo: yes
</code>```

The remote_user that used to login to this machine is a non-root user, it has no password, and can only login using key auth.

For user postgres, this account doesn't have the password as well, because the database was just installed.

Since I logged in as non-root user, of course it will ask for password when switch to postgress account in order to create database user. But it won't be need for password if switch to postgres from root account. So, I wonder if there is a way to switch to root, and then switch to user postgres.

Note: the root account has no public key, no password, and cannot login from SSH.

答:
You can specificy the sudo password when running the Ansible playbook:</p>

```<code>ansible-playbook playbook.yml -i inventory.ini --extra-vars "ansible_sudo_pass=yourPassword"
</code>```

Title: Missing sudo password in Ansible

Body:
Ansible asks for sudo password from following code, it tries to create a new postgres user.

Error message:

fatal: [xxx.xxx.xxx.xxx] => Missing sudo password

main.yml

- name: 'Provision a PostgreSQL server'
  hosts: "dbservers"
  sudo: yes
  sudo_user: postgres
  roles:
    - postgres

create_db.yml

- name: Make sure the PostgreSQL users are present
  postgresql_user: name=rails password=secret role_attr_flags=CREATEDB,NOSUPERUSER
  sudo_user: postgres
  sudo: yes

The remote_user that used to login to this machine is a non-root user, it has no password, and can only login using key auth.

For user postgres, this account doesn't have the password as well, because the database was just installed.

Since I logged in as non-root user, of course it will ask for password when switch to postgress account in order to create database user. But it won't be need for password if switch to postgres from root account. So, I wonder if there is a way to switch to root, and then switch to user postgres.

Note: the root account has no public key, no password, and cannot login from SSH.

Body:
You can specificy the sudo password when running the Ansible playbook:

ansible-playbook playbook.yml -i inventory.ini --extra-vars "ansible_sudo_pass=yourPassword"


问:
How would I send the same data to several android phones using TCP?
This is a bit of a "further down the track now" extension to a question I asked a while ago... I have a better understanding of sockets now, and have some working code but need to improve it...

Ok, so I have currently got UDP multicasting working to send short strings of text from a Java 'server' application to several Android phones (which will potentially become several hundred Android phones).  This works fine most of the time, but it does tend to lose the odd string on the odd phone, and randomly it will just go total loss for a short period and nothing will get through to any of them, which can be a little frustrating.

Since, as I understand, there is no way to broadcast on TCP - my idea is to have the phones initially 'connect' to the server app using a ServerSocket.  This will do nothing more than harvest client IP addresses which are to be stored in a Set<InetAddress> called clients.  Then I will want to iterate over these addresses and send the string to each phone individually - but I don't want to block the code, nor do I want to spend forever waiting for sends to occur if, say, the phone has gone to sleep and can't / won't accept connections.  The information will need to get to all phones within a few seconds of starting to send (even with 2-300 clients).

My initial code is below, and the questions I have regarding it are:

Is this code in one thread enough?

Would a modern CPU make good use of several threads with the address set split evenly amongst them (say 4 threads?)

Is it (as I believe) a bad idea to spin every connection/send off in its own thread?

Does setting the socket timeout allow the thread to work through its list faster? Or will this cause problems?

If socket timeout setting is a good idea, then what is a sensible time?  Or do I need to just test to get this right?

Thanks in advance for any help you guys can provide...

```<code>for (InetAddress client : clients) {
try {
    Socket sendQuestionSocket = new Socket(client, portSend);
    // Theory: 50 milliseconds is enough to connect, and could allow 200 clients
    // to get their questions in around 10 seconds.  Maybe?
    sendQuestionSocket.setSoTimeout(50);
    PrintWriter outStream = new PrintWriter(sendQuestionSocket.getOutputStream());
    outStream.println(question.toString());
    outStream.flush(); // Do I need this line?
    sendQuestionSocket.close();
    outStream.close();
} catch (InterruptedIOException e) {
    logger.log(Level.WARNING, "Couldn't connect in time... passing this one over");
    e.printStackTrace();
} catch (UnknownHostException e) {
    logger.log(Level.SEVERE, "Unable to find that client");
    e.printStackTrace();
} catch (IOException e) {
    logger.log(Level.SEVERE, "Unable to create question sending port");
    e.printStackTrace();
}
</code>```

}

答: I would go with threads here: one thread for every client. It is ok for modern cpu, and it won't make you block for execution. So, the live clients will get the answer as soon as possible even if there are a lot of dead clients.</p>

Body:
This is a bit of a "further down the track now" extension to a question I asked a while ago... I have a better understanding of sockets now, and have some working code but need to improve it...

Ok, so I have currently got UDP multicasting working to send short strings of text from a Java 'server' application to several Android phones (which will potentially become several hundred Android phones).  This works fine most of the time, but it does tend to lose the odd string on the odd phone, and randomly it will just go total loss for a short period and nothing will get through to any of them, which can be a little frustrating.

Since, as I understand, there is no way to broadcast on TCP - my idea is to have the phones initially 'connect' to the server app using a ServerSocket.  This will do nothing more than harvest client IP addresses which are to be stored in a Set<InetAddress> called clients.  Then I will want to iterate over these addresses and send the string to each phone individually - but I don't want to block the code, nor do I want to spend forever waiting for sends to occur if, say, the phone has gone to sleep and can't / won't accept connections.  The information will need to get to all phones within a few seconds of starting to send (even with 2-300 clients).

My initial code is below, and the questions I have regarding it are:

Is this code in one thread enough?

Would a modern CPU make good use of several threads with the address set split evenly amongst them (say 4 threads?)

Is it (as I believe) a bad idea to spin every connection/send off in its own thread?

Does setting the socket timeout allow the thread to work through its list faster? Or will this cause problems?

If socket timeout setting is a good idea, then what is a sensible time?  Or do I need to just test to get this right?

Thanks in advance for any help you guys can provide...

for (InetAddress client : clients) {
try {
    Socket sendQuestionSocket = new Socket(client, portSend);
    // Theory: 50 milliseconds is enough to connect, and could allow 200 clients
    // to get their questions in around 10 seconds.  Maybe?
    sendQuestionSocket.setSoTimeout(50);
    PrintWriter outStream = new PrintWriter(sendQuestionSocket.getOutputStream());
    outStream.println(question.toString());
    outStream.flush(); // Do I need this line?
    sendQuestionSocket.close();
    outStream.close();
} catch (InterruptedIOException e) {
    logger.log(Level.WARNING, "Couldn't connect in time... passing this one over");
    e.printStackTrace();
} catch (UnknownHostException e) {
    logger.log(Level.SEVERE, "Unable to find that client");
    e.printStackTrace();
} catch (IOException e) {
    logger.log(Level.SEVERE, "Unable to create question sending port");
    e.printStackTrace();
}

}


问:
Count Rows in Doctrine QueryBuilder
I'm using Doctrine's QueryBuilder to build a query, and I want to get the total count of results from the query.   </p>

```<code>$repository = $em->getRepository('FooBundle:Foo');

$qb = $repository->createQueryBuilder('n')
        ->where('n.bar = :bar')
        ->setParameter('bar', $bar);

$query = $qb->getQuery();

//this doesn't work
$totalrows = $query->getResult()->count();
</code>```

<p>I just want to run a count on this query to get the total rows, but not return the actual results.  (After this count query, I'm going to further modify the query with maxResults for pagination.)   </p>

答:
You can also get the number of data by using the count function. </p>

```<code>$query = $this->dm->createQueryBuilder('AppBundle:Items')
                    ->field('isDeleted')->equals(false)
                    ->getQuery()->count();
</code>```

Title: Count Rows in Doctrine QueryBuilder

Body:
I'm using Doctrine's QueryBuilder to build a query, and I want to get the total count of results from the query.

$repository = $em->getRepository('FooBundle:Foo');

$qb = $repository->createQueryBuilder('n')
        ->where('n.bar = :bar')
        ->setParameter('bar', $bar);

$query = $qb->getQuery();

//this doesn't work
$totalrows = $query->getResult()->count();

I just want to run a count on this query to get the total rows, but not return the actual results.  (After this count query, I'm going to further modify the query with maxResults for pagination.)

Body:
You can also get the number of data by using the count function.

$query = $this->dm->createQueryBuilder('AppBundle:Items')
                    ->field('isDeleted')->equals(false)
                    ->getQuery()->count();


问:
chose colors for scale_colour_colorblind() in ggthemes
I would like to chose specific colors of the colorblind_pal() from ggthemes

This works:

```<code>library(ggplot2)
library(ggthemes)

p <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg,
                                     colour = factor(gear))) + facet_wrap(~am)
p + theme_igray() + scale_colour_colorblind()
</code>```

Now I would like to chose specific colors of the colorblind_pal() for my plot. How can I chose them?

I tried following with no success:

```<code>my_palette <- palette(c("#000000","#F0E442","#D55E00"))
p + theme_igray() + scale_colour_colorblind(my_palette)
</code>```

答:
Since you already have the colors, you can just use scale_color_manual:

```<code>library(ggthemes)
library(ggplot2)
COLS=colorblind_pal()(8)

COLS = COLS[c(1,5,7)]

p <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg,
                                     colour = factor(gear))) + facet_wrap(~am)
p + theme_igray() + scale_colour_manual(values=COLS))
</code>```

Body:
I would like to chose specific colors of the colorblind_pal() from ggthemes

This works:

library(ggplot2)
library(ggthemes)

p <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg,
                                     colour = factor(gear))) + facet_wrap(~am)
p + theme_igray() + scale_colour_colorblind()

Now I would like to chose specific colors of the colorblind_pal() for my plot. How can I chose them?

I tried following with no success:

my_palette <- palette(c("#000000","#F0E442","#D55E00"))
p + theme_igray() + scale_colour_colorblind(my_palette)

Body:
Since you already have the colors, you can just use scale_color_manual:

library(ggthemes)
library(ggplot2)
COLS=colorblind_pal()(8)

COLS = COLS[c(1,5,7)]

p <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg,
                                     colour = factor(gear))) + facet_wrap(~am)
p + theme_igray() + scale_colour_manual(values=COLS))


问:
Firebase not sending verification code to phone the second time
In my app, I'm using Firebase to verify the user's phone number. However, the verification system is inconsistent and sends the OTP only the first time. For example, I get the OTP when I'm signing in for the first time, but if I sign out and try to sign in again, I don't get the OTP.

This is the activity where the user is asked to enter the OTP:

```<code>import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

import java.util.concurrent.TimeUnit;

public class EnterOTPActivity extends AppCompatActivity {
    String userPhoneNumber;

    private int autoResendCount=0, resumeCount=0;
    private final String ctryCode = "+91";
    private String verificationId;
    private FirebaseAuth mAuth;
    private TextView resendOtp, enterOtpMessage, timerTV;
    private ProgressDialog progressDialog;
    private EditText otpField;
    private boolean firstSend=true,timerOn=true;
    FirebaseFirestore db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enter_otp);
        mAuth = FirebaseAuth.getInstance();
        otpField = findViewById(R.id.editTextOtp);
        resendOtp =  findViewById(R.id.resendOTPButton);
        timerTV = findViewById(R.id.resendTimer);
        userPhoneNumber = getIntent().getStringExtra("USER_MOB").trim();
        sendVerificationCode(userPhoneNumber);
        startResendTimer(15);
        getSupportActionBar().setTitle("Verification");
        resendOtp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!timerOn) {
                    startResendTimer(30);
                    firstSend = false;
                    sendVerificationCode(userPhoneNumber);
                }
            }
        });
        FloatingActionButton next = findViewById(R.id.fab2);
        enterOtpMessage =  findViewById(R.id.aboutotpverif);
        enterOtpMessage.setText(enterOtpMessage.getText().toString() + " " + ctryCode + userPhoneNumber);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Please wait while we check your verification code");
        progressDialog.setTitle("Verification");
        progressDialog.setCancelable(false);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //check if otp is correct here
                if (otpField.getText().toString().length() == 6) {
                    verifyCode(otpField.getText().toString().trim());
                    if(!progressDialog.isShowing())
                    progressDialog.show();
                } else {
                    View parentLayout = findViewById(android.R.id.content);
                    Snackbar.make(parentLayout, "A valid verification code has 6 digits", Snackbar.LENGTH_SHORT)
                            .setAction("OKAY", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            })
                            .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                            .show();
                }
            }
        });
    }

    private void verifyCode(String code) {

        try {
            PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
            signInwithCredential(credential);

        }
        catch (Exception e) {
            // code here is executed when we don't get the OTP and enter a wrong one
            progressDialog.dismiss();
            progressDialog.setCancelable(true);
            View parentLayout = findViewById(android.R.id.content);
            Snackbar.make(parentLayout, getString(R.string.incorrect_code_t1), Snackbar.LENGTH_LONG)
                    .setAction("OKAY", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    })
                    .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                    .show();
            if(progressDialog.isShowing())
            progressDialog.dismiss();
        }
    }

    private void signInwithCredential(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    isRegisteredUser();
                }
                else {
                    if(progressDialog.isShowing())
                    progressDialog.dismiss();
                    View parentLayout = findViewById(android.R.id.content);
                    Snackbar.make(parentLayout, "Incorrect verification code", Snackbar.LENGTH_SHORT)
                            .setAction("OKAY", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            })
                            .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                            .show();
                    if(progressDialog.isShowing())
                    progressDialog.dismiss();

                }
            }
        });

    }

    private void sendVerificationCode(String number) {
        final String phoneNumber = ctryCode + number;
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phoneNumber,        // Phone number to verify
                120,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallbacks
    }

    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

        @Override
        public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);
            verificationId = s;
        }

        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
            String code = phoneAuthCredential.getSmsCode();
            if (code != null) {
                verifyCode(code);
                otpField.setText(code);
                if(!progressDialog.isShowing())
                progressDialog.show();
            }
        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    };

    private void isRegisteredUser() {

        final String userId = ctryCode + userPhoneNumber;
        db = FirebaseFirestore.getInstance();
        db.collection("users")
                .whereEqualTo("phone", userId)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        try{
                        if (task.isSuccessful()) {

                            saveToken(userId);

                            for (QueryDocumentSnapshot document : task.getResult()) {
                                if (document.getId().equalsIgnoreCase(userId)) {

                                    Intent startmainact = new Intent(EnterOTPActivity.this, MainActivity.class);
                                    startmainact.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(startmainact);
                                    finish();
                                    return;
                                }
                                //Log.d(TAG, document.getId() + " => " + document.getData());
                            }

                            Intent startposact = new Intent(EnterOTPActivity.this, ParOrStudActivity.class);

                            startposact.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(startposact);
                            finish();

                        } else {
                            View parentLayout = findViewById(android.R.id.content);
                            Snackbar.make(parentLayout, "Database error: please try again", Snackbar.LENGTH_SHORT)
                                    .setAction("OKAY", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {

                                        }
                                    })
                                    .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                                    .show();
                        }
                    }
                        catch(Exception e){
                            View parentLayout = findViewById(android.R.id.content);
                            Snackbar.make(parentLayout, "Database error: please try again", Snackbar.LENGTH_SHORT)
                                    .setAction("OKAY", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {

                                        }
                                    })
                                    .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                                    .show();
                        }
                    }

                });
    }

    private void saveToken(final String userId) {
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();
                        FirebaseFirestore.getInstance().collection("users").document(userId).update("token",token);
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (autoResendCount<2 && resumeCount>0) {
            sendVerificationCode(userPhoneNumber);
            autoResendCount=autoResendCount+1;
            resumeCount=resumeCount+1;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        progressDialog.dismiss();
    }

    public void startResendTimer(int seconds) {
        timerTV.setVisibility(View.VISIBLE);
        resendOtp.setEnabled(false);

        new CountDownTimer(seconds*1000, 1000) {

            public void onTick(long millisUntilFinished) {
                String secondsString = Long.toString(millisUntilFinished/1000);
                if (millisUntilFinished<10000) {
                    secondsString = "0"+secondsString;
                }
                timerTV.setText(" (0:"+ secondsString+")");
            }

            public void onFinish() {
                resendOtp.setEnabled(true);
                timerTV.setVisibility(View.GONE);
                timerOn=false;
            }
        }.start();
    }

    @Override
    public void onBackPressed() {
        // do not allow user to go back to the screen before
    }
}
</code>```

This erratic verification system delivers an incompetent UX. Is there any way to get around it?

答:
If you read Firebase Docs about PhoneAuthProvider, it is clearly stated:

The verifyPhoneNumber method is reentrant: if you call it multiple times, such as in an activity's onStart method, the verifyPhoneNumber method will not send a second SMS unless the original request has timed out.

In your case, you set the timeout at 120 seconds. If you really want to test this behavior, I suggest reducing the timeout to 10 or 20 seconds, and see if you can resend OTP after the timeout.

Additionally, if you want to get the timeout event, you can add onCodeAutoRetrievalTimeOut as a part of PhoneAuthProvider.OnVerificationStateChangedCallbacks. I think it is safe to set your resendOtp enabled as true in that callback. And it is way better than defining your own timer.

Body:
In my app, I'm using Firebase to verify the user's phone number. However, the verification system is inconsistent and sends the OTP only the first time. For example, I get the OTP when I'm signing in for the first time, but if I sign out and try to sign in again, I don't get the OTP.

This is the activity where the user is asked to enter the OTP:

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

import java.util.concurrent.TimeUnit;

public class EnterOTPActivity extends AppCompatActivity {
    String userPhoneNumber;

    private int autoResendCount=0, resumeCount=0;
    private final String ctryCode = "+91";
    private String verificationId;
    private FirebaseAuth mAuth;
    private TextView resendOtp, enterOtpMessage, timerTV;
    private ProgressDialog progressDialog;
    private EditText otpField;
    private boolean firstSend=true,timerOn=true;
    FirebaseFirestore db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enter_otp);
        mAuth = FirebaseAuth.getInstance();
        otpField = findViewById(R.id.editTextOtp);
        resendOtp =  findViewById(R.id.resendOTPButton);
        timerTV = findViewById(R.id.resendTimer);
        userPhoneNumber = getIntent().getStringExtra("USER_MOB").trim();
        sendVerificationCode(userPhoneNumber);
        startResendTimer(15);
        getSupportActionBar().setTitle("Verification");
        resendOtp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!timerOn) {
                    startResendTimer(30);
                    firstSend = false;
                    sendVerificationCode(userPhoneNumber);
                }
            }
        });
        FloatingActionButton next = findViewById(R.id.fab2);
        enterOtpMessage =  findViewById(R.id.aboutotpverif);
        enterOtpMessage.setText(enterOtpMessage.getText().toString() + " " + ctryCode + userPhoneNumber);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Please wait while we check your verification code");
        progressDialog.setTitle("Verification");
        progressDialog.setCancelable(false);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //check if otp is correct here
                if (otpField.getText().toString().length() == 6) {
                    verifyCode(otpField.getText().toString().trim());
                    if(!progressDialog.isShowing())
                    progressDialog.show();
                } else {
                    View parentLayout = findViewById(android.R.id.content);
                    Snackbar.make(parentLayout, "A valid verification code has 6 digits", Snackbar.LENGTH_SHORT)
                            .setAction("OKAY", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            })
                            .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                            .show();
                }
            }
        });
    }

    private void verifyCode(String code) {

        try {
            PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
            signInwithCredential(credential);

        }
        catch (Exception e) {
            // code here is executed when we don't get the OTP and enter a wrong one
            progressDialog.dismiss();
            progressDialog.setCancelable(true);
            View parentLayout = findViewById(android.R.id.content);
            Snackbar.make(parentLayout, getString(R.string.incorrect_code_t1), Snackbar.LENGTH_LONG)
                    .setAction("OKAY", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    })
                    .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                    .show();
            if(progressDialog.isShowing())
            progressDialog.dismiss();
        }
    }

    private void signInwithCredential(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    isRegisteredUser();
                }
                else {
                    if(progressDialog.isShowing())
                    progressDialog.dismiss();
                    View parentLayout = findViewById(android.R.id.content);
                    Snackbar.make(parentLayout, "Incorrect verification code", Snackbar.LENGTH_SHORT)
                            .setAction("OKAY", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            })
                            .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                            .show();
                    if(progressDialog.isShowing())
                    progressDialog.dismiss();

                }
            }
        });

    }

    private void sendVerificationCode(String number) {
        final String phoneNumber = ctryCode + number;
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phoneNumber,        // Phone number to verify
                120,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallbacks
    }

    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

        @Override
        public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);
            verificationId = s;
        }

        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
            String code = phoneAuthCredential.getSmsCode();
            if (code != null) {
                verifyCode(code);
                otpField.setText(code);
                if(!progressDialog.isShowing())
                progressDialog.show();
            }
        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    };

    private void isRegisteredUser() {

        final String userId = ctryCode + userPhoneNumber;
        db = FirebaseFirestore.getInstance();
        db.collection("users")
                .whereEqualTo("phone", userId)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        try{
                        if (task.isSuccessful()) {

                            saveToken(userId);

                            for (QueryDocumentSnapshot document : task.getResult()) {
                                if (document.getId().equalsIgnoreCase(userId)) {

                                    Intent startmainact = new Intent(EnterOTPActivity.this, MainActivity.class);
                                    startmainact.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(startmainact);
                                    finish();
                                    return;
                                }
                                //Log.d(TAG, document.getId() + " => " + document.getData());
                            }

                            Intent startposact = new Intent(EnterOTPActivity.this, ParOrStudActivity.class);

                            startposact.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(startposact);
                            finish();

                        } else {
                            View parentLayout = findViewById(android.R.id.content);
                            Snackbar.make(parentLayout, "Database error: please try again", Snackbar.LENGTH_SHORT)
                                    .setAction("OKAY", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {

                                        }
                                    })
                                    .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                                    .show();
                        }
                    }
                        catch(Exception e){
                            View parentLayout = findViewById(android.R.id.content);
                            Snackbar.make(parentLayout, "Database error: please try again", Snackbar.LENGTH_SHORT)
                                    .setAction("OKAY", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {

                                        }
                                    })
                                    .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
                                    .show();
                        }
                    }

                });
    }

    private void saveToken(final String userId) {
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();
                        FirebaseFirestore.getInstance().collection("users").document(userId).update("token",token);
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (autoResendCount<2 && resumeCount>0) {
            sendVerificationCode(userPhoneNumber);
            autoResendCount=autoResendCount+1;
            resumeCount=resumeCount+1;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        progressDialog.dismiss();
    }

    public void startResendTimer(int seconds) {
        timerTV.setVisibility(View.VISIBLE);
        resendOtp.setEnabled(false);

        new CountDownTimer(seconds*1000, 1000) {

            public void onTick(long millisUntilFinished) {
                String secondsString = Long.toString(millisUntilFinished/1000);
                if (millisUntilFinished<10000) {
                    secondsString = "0"+secondsString;
                }
                timerTV.setText(" (0:"+ secondsString+")");
            }

            public void onFinish() {
                resendOtp.setEnabled(true);
                timerTV.setVisibility(View.GONE);
                timerOn=false;
            }
        }.start();
    }

    @Override
    public void onBackPressed() {
        // do not allow user to go back to the screen before
    }
}

This erratic verification system delivers an incompetent UX. Is there any way to get around it?


问:
Getting null argument when I run any program in eclipse
I tried execution in eclipse with two different palindrome programs in java. But when i click Run As Java Application all i get is the below error.
I am getting a different error when i run the same program in command prompt as well

答:
Try to reinstall Eclipse. If that does not help try to see if your java is installed correctly. Go to command prompt and navigate to the project rootfolder.
Then do the following (trying to compile the program):

javac Palindrome.java or javac Palindrome2.java

When this does work try to run the programs with either:

java MyFirstJavaProgram
or
java MyFirstJavaProgram2
to try and run the program you just compiled. Then you can check if the fault is in your java installation or if it is in Eclipse.


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答:
Tooth and nail, and sometimes you lose.  The problem is that it's always easy to be tempted to build something cool.

Why build something simple and efficient when it can be complicated and wonderful?

Try to remind people of the XP rule of building the simplest thing that can possibly work.

OwnerDisplayName: ʞɔıu

ContentLicense: CC BY-SA 2.5

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

OwnerDisplayName: Charlie Martin


问:
Grails Domain Classes Dates
For some reason, i would like to be able to add a reference date, like 0-0-0, which will represent 'no date'. Any way of doing that ? And will 0/0/0 work?</p>

答:
Does the date 0/0/0 represent a real point (or interval) in time? In other words, if you had a desk Calendar that stretches infinitely far into the future and back into the past, could you find a page that corresponds to 0/0/0? If the answer is no, then this is not a valid Date value and therefore cannot be assigned to a Date variable.

On the other hand, if 0/0/0 represents a real point in time, e.g. the first day of the first year AD, then something like this might work

```<code>import static java.util.Calendar.*
def cal = Calendar.instance
cal[YEAR] = -1900
cal[MONTH] = 0
cal[DAY_OF_MONTH] = 1
cal.clearTime()

Date dayZero =  cal.time
</code>```

However, my instinct is that this is a bad idea, and there's a better solution to the underlying problem that this weird Date usage.

Title: Grails Domain Classes Dates

Body:
Does the date 0/0/0 represent a real point (or interval) in time? In other words, if you had a desk Calendar that stretches infinitely far into the future and back into the past, could you find a page that corresponds to 0/0/0? If the answer is no, then this is not a valid Date value and therefore cannot be assigned to a Date variable.

On the other hand, if 0/0/0 represents a real point in time, e.g. the first day of the first year AD, then something like this might work

import static java.util.Calendar.*
def cal = Calendar.instance
cal[YEAR] = -1900
cal[MONTH] = 0
cal[DAY_OF_MONTH] = 1
cal.clearTime()

Date dayZero =  cal.time

However, my instinct is that this is a bad idea, and there's a better solution to the underlying problem that this weird Date usage.


答:
You could use scale_color_manual in order to manually specify the colors to use:

```<code>library(ggplot2)
library(ggthemes)

p <- ggplot(mtcars) +
  geom_point(aes(x = wt, y = mpg, colour = factor(gear))) +
  facet_wrap(~am) +
  theme_igray() +
  scale_color_manual(values = c("#000000","#F0E442","#D55E00"))
p
</code>```

Title: chose colors for scale_colour_colorblind() in ggthemes

Body:
You could use scale_color_manual in order to manually specify the colors to use:

library(ggplot2)
library(ggthemes)

p <- ggplot(mtcars) +
  geom_point(aes(x = wt, y = mpg, colour = factor(gear))) +
  facet_wrap(~am) +
  theme_igray() +
  scale_color_manual(values = c("#000000","#F0E442","#D55E00"))
p


问:
How to dump data from SQL Server into MS Access table using hybrid connections
I need to pull data from SQL server using a query where its statement is stored in a MS access table and dump the data into another table.

There are 2 tables, 01-MyStoredSQLs and 02-tmpTableData

The problem is that there are 2 connections as well. That's why I called it Hybrid.

My Final result is the data from SQL Server into the tmpTableData (result of a query where its statement is stored in the MyStoredSQLs table)

Public Sub DumpSQLServerData()
Dim conn As ADODB.Connection
On Error GoTo errMSG

Set conn = New ADODB.Connection

conn.ConnectionString = "DSN=myDSN; UID=MyID;Pwd=MyPWd"
conn.Open

Dim db As DAO.Database
Set db = CurrentDb

Dim rs As DAO.Recordset
'Retrieving the SQL Statment that is stored in the MyStoredSQLs table
Set rs = db.OpenRecordset("SELECT [Statement] FROM MyStoredSQLs WHERE ID=1")
Dim tmpSQL As String
Dim tmpINTOSQL As String

tmpSQL = rs(0)
'Hybrid statement
tmpINTOSQL = "INSERT INTO tmpTableData" & tmpSQL

conn.Execute (tmpINTOSQL), dbFailOnError

conn.Close
rs.Close
db.Close

Set conn = Nothing
Set rs = Nothing
Set db = Nothing
errMSG:
    Debug.Print Err.Description
End Sub
```

答:
You can't expect SQL server to magically be able to access tables stored elsewhere.

Execute the query in Access, and either use a linked table, or specify the location of the table, e.g.

```<code>INSERT INTO tmpTableData SELECT Something FROM [ODBC;DSN=myDSN;UID=MyID;Pwd=MyPWd].Schema.TableInSQLServer
</code>```

If you want to execute the query on SQL server, not Microsoft Access, then SQL server will need to be able to access the Access database file, and use OPENROWSET to query the Access table.

As an alternate, you can create a passthrough query, and use that to copy the table:

```<code>Dim qd As DAO.QueryDef
Set qd = db.CreateQueryDef("~tmpQuery")
qd.Connect = "ODBC;DSN=myDSN;UID=MyID;Pwd=MyPWd"
qd.ReturnsRecords = True
qd.SQL = tmpSQL
Set qd = Nothing
db.Execute "INSERT INTO tmpTable SELECT * FROM [~tmpQuery]"
db.QueryDefs.Delete "~tmpQuery"
</code>```

Body:
You can't expect SQL server to magically be able to access tables stored elsewhere.

Execute the query in Access, and either use a linked table, or specify the location of the table, e.g.

INSERT INTO tmpTableData SELECT Something FROM [ODBC;DSN=myDSN;UID=MyID;Pwd=MyPWd].Schema.TableInSQLServer

If you want to execute the query on SQL server, not Microsoft Access, then SQL server will need to be able to access the Access database file, and use OPENROWSET to query the Access table.

As an alternate, you can create a passthrough query, and use that to copy the table:

Dim qd As DAO.QueryDef
Set qd = db.CreateQueryDef("~tmpQuery")
qd.Connect = "ODBC;DSN=myDSN;UID=MyID;Pwd=MyPWd"
qd.ReturnsRecords = True
qd.SQL = tmpSQL
Set qd = Nothing
db.Execute "INSERT INTO tmpTable SELECT * FROM [~tmpQuery]"
db.QueryDefs.Delete "~tmpQuery"


问:
Build Contacts Application using Android SDK
I am trying to build default Contacts application from Source code using Android SDK (i.e. Eclipse & ADT) as I wanted to add some more options into contact details (which are specific to my requirement). But it's giving me some compilation errors as android.jar is not having all the classes required to build this application.
Please tell me how can I achieve this.

Thanks,
Parag

答: You cannot build the "default Contacts application from Source code using Android SDK". You can only build that app as part of a complete custom firmware build.</p>


问:
Amount of properties per command/event in event sourcing
I'm learning cqrs/event sourcing, and recently I listen some speach and speaker told that you need pass as few parameters to event as possible, in other words to make events tiny as possible. The main reason for that is it's impossible to change events later as it will break the event history, and its easelly to design small events correctly. But what if for example in UI you need fill in for example form with 10 fields to create new aggregate, and same situation can be with updating the aggregate? How to be in such a case? And how to be if business later consider to change something, but we have huge event which updating 10 fields?</p>

答:
The decision is always context-specific and each case deserves its own review of using thin events vs fat events.

The motivation for using thin domain events is to include just enough information that is required to ensure the state transition.

As for fat events, your projections might require a piece of entity state to avoid using any logic in the projection itself (best practice).

For integration, you'd prefer emitting fat events because you hardly know who will consume your event. Still, the content of the event should convey the information related to the meaning of the event itself.

References:

Putting your events on a diet

Patterns for Decoupling in Distributed Systems: Fat Event


问:
How to fix "Call to a member function xy on array" without using foreach?
I have an object inside an array stored in the variable $image

```<code>array(1) { [250]=> object(Magento\Framework\DataObject)#11025 (1) { ["_data":protected]=> array(26) { ["value_id"]=> string(3) "250" ["file"]=> string(58) "/i/n/insetktenschutz-doppeltuer-im-zargenrahmen_37_1_3.jpg"  ... } } }
</code>```

If I try to return a value, e.g. file like this:

```<code>echo $image->getFile();
</code>```

Then of course I get Fatal error: Uncaught Error: Call to a member function getFile() on array

So I tried to call it like this:

```<code>$image = $image[0];
echo $image->getFile();
</code>```

But I get Exception #0 (Exception): Notice: Undefined offset: 0

So I tried to cast it to an object:

```<code>$image = (object) $image;
echo $image->getFile();
</code>```

Now I get Fatal error: Uncaught Error: Call to undefined method stdClass::getFile()

Then I used a foreach:

```<code>foreach($image as $i) {
    echo $image->getFile();  // alternative: $image->getData('file')
}
</code>```

and it works! Why does it work with foreach and how can I make it work without?

答:
I don't think that there is anything like a functional forEach in php, anyway you could make an ArrayObject subclass in order to encapsulate the iteration logic

class MyArray extends ArrayObject {
    public function getData($data){
        foreach($this as $element) {
            $element->getData($data);
        }
    }
}

// and use it
$my = new MyArray(array( /* put your objects here */ ));
$my->getData("file");
```

<p>EDIT</p>

<p>a more generic version</p>

```class MyArray extends ArrayObject {
    public function __call($name, $data){
        foreach($this as $element) {
            $element->$name(...$data);
        }
    }
}
$my = new MyArray(array( /* put your objects here */ ));
$my->getData("file");
```

Body:
I have an object inside an array stored in the variable $image

array(1) { [250]=> object(Magento\Framework\DataObject)#11025 (1) { ["_data":protected]=> array(26) { ["value_id"]=> string(3) "250" ["file"]=> string(58) "/i/n/insetktenschutz-doppeltuer-im-zargenrahmen_37_1_3.jpg"  ... } } }

If I try to return a value, e.g. file like this:

echo $image->getFile();

Then of course I get Fatal error: Uncaught Error: Call to a member function getFile() on array

So I tried to call it like this:

$image = $image[0];
echo $image->getFile();

But I get Exception #0 (Exception): Notice: Undefined offset: 0

So I tried to cast it to an object:

$image = (object) $image;
echo $image->getFile();

Now I get Fatal error: Uncaught Error: Call to undefined method stdClass::getFile()

Then I used a foreach:

foreach($image as $i) {
    echo $image->getFile();  // alternative: $image->getData('file')
}

and it works! Why does it work with foreach and how can I make it work without?

Body:
I don't think that there is anything like a functional forEach in php, anyway you could make an ArrayObject subclass in order to encapsulate the iteration logic

class MyArray extends ArrayObject {
    public function getData($data){
        foreach($this as $element) {
            $element->getData($data);
        }
    }
}

// and use it
$my = new MyArray(array( /* put your objects here */ ));
$my->getData("file");

EDIT

a more generic version

class MyArray extends ArrayObject {
    public function __call($name, $data){
        foreach($this as $element) {
            $element->$name(...$data);
        }
    }
}
$my = new MyArray(array( /* put your objects here */ ));
$my->getData("file");


问:
Filter data by group & preserve empty groups
I wonder how can I filter my data by group, and preserve the groups that are empty?

Example:

```<code>year = c(1,2,3,1,2,3,1,2,3)
site = rep(c("a", "b", "d"), each = 3)
value = c(3,3,0,1,8,5,10,18,27)

df <- data.frame(year, site, value)
</code>```

I want to subset the rows where the value is more than 5. For some groups, this is never true. Filter function simply skips empty groups.

How can I keep my empty groups and have NA instead? Ideally, I would like to use dplyr funtions instead of base R.

My filtering approach, where .preserve does not preserve empty groups:

```<code>df %>%
  group_by(site) %>%
  filter(value > 5, .preserve = TRUE)
</code>```

Expected output:

```<code>    year site  value
  <dbl> <fct> <dbl>
1    NA a        NA
2     2 b         8
3     1 d        10
4     2 d        18
5     3 d        27
</code>```

答:
With the addition of tidyr, you can do:

```<code>df %>%
 group_by(site) %>%
 filter(value > 5) %>%
 ungroup() %>%
 complete(site = df$site)

  site   year value
  <fct> <dbl> <dbl>
1 a        NA    NA
2 b         2     8
3 d         1    10
4 d         2    18
5 d         3    27
</code>```

Or if you want to keep it in dplyr:

```<code>df %>%
 group_by(site) %>%
 filter(value > 5) %>%
 bind_rows(df %>%
            group_by(site) %>%
            filter(all(value <= 5)) %>%
            summarise_all(~ NA))
</code>```

Body:
I wonder how can I filter my data by group, and preserve the groups that are empty?

Example:

year = c(1,2,3,1,2,3,1,2,3)
site = rep(c("a", "b", "d"), each = 3)
value = c(3,3,0,1,8,5,10,18,27)

df <- data.frame(year, site, value)

I want to subset the rows where the value is more than 5. For some groups, this is never true. Filter function simply skips empty groups.

How can I keep my empty groups and have NA instead? Ideally, I would like to use dplyr funtions instead of base R.

My filtering approach, where .preserve does not preserve empty groups:

df %>%
  group_by(site) %>%
  filter(value > 5, .preserve = TRUE)

Expected output:

    year site  value
  <dbl> <fct> <dbl>
1    NA a        NA
2     2 b         8
3     1 d        10
4     2 d        18
5     3 d        27

Body:
With the addition of tidyr, you can do:

df %>%
 group_by(site) %>%
 filter(value > 5) %>%
 ungroup() %>%
 complete(site = df$site)

  site   year value
  <fct> <dbl> <dbl>
1 a        NA    NA
2 b         2     8
3 d         1    10
4 d         2    18
5 d         3    27

Or if you want to keep it in dplyr:

df %>%
 group_by(site) %>%
 filter(value > 5) %>%
 bind_rows(df %>%
            group_by(site) %>%
            filter(all(value <= 5)) %>%
            summarise_all(~ NA))


问:
Why my regex does not match the 'username' constraints
I am struggling to write a regex on code camp which must fit the following 4 constraints defined for a correct 'username'

1) Usernames can only use alpha-numeric characters.

2) The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.

3) Username letters can be lowercase and uppercase.

4) Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.

Here is the Regex I came up with, in the following code (first line)

```<code>let userCheck = /[a-zA-Z]([a-zA-Z]+\d*|\d\d+)/; // the regex I wrote
let result = userCheck.test(username);
</code>```

However, it displays the following fault

```<code>Your regex should not match BadUs3rnam3
Your regex should not match c57bT3
</code>```

I am absolutely confused. I actually know what the correct regex to this problem is, however, I need to know where my own regex is going wrong which is producing the above error. Please help

答:
Your code passes because you are not using anchors so you get a partial match.

You could update the pattern to ^[a-zA-Z](?:[a-zA-Z]+\d*|\d{2,})$

Another way to write it could be matching either 2 chars a-zA-Z and 0+ digits, or in case there is a single char a-zA-Z, match 2 or more digits to pass the rule
A two-character username can only use alphabet letters as characters.

```<code>^(?:[a-zA-Z]{2,}\d*|[a-zA-Z]\d{2,})$
</code>```

Regex demo

let userCheck = /^[a-zA-Z](?:[a-zA-Z]+\d*|\d{2,})$/;
[
  "BadUs3rnam3",
  "c57bT3",
  "aa",
  "a111111",
  "a1",
  "11"
].forEach(username => console.log(username + ": " + userCheck.test(username)));```

Body:
I am struggling to write a regex on code camp which must fit the following 4 constraints defined for a correct 'username'

1) Usernames can only use alpha-numeric characters.

2) The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.

3) Username letters can be lowercase and uppercase.

4) Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.

Here is the Regex I came up with, in the following code (first line)

let userCheck = /[a-zA-Z]([a-zA-Z]+\d*|\d\d+)/; // the regex I wrote
let result = userCheck.test(username);

However, it displays the following fault

Your regex should not match BadUs3rnam3
Your regex should not match c57bT3

I am absolutely confused. I actually know what the correct regex to this problem is, however, I need to know where my own regex is going wrong which is producing the above error. Please help

Body:
Your code passes because you are not using anchors so you get a partial match.

You could update the pattern to ^[a-zA-Z](?:[a-zA-Z]+\d*|\d{2,})$

Another way to write it could be matching either 2 chars a-zA-Z and 0+ digits, or in case there is a single char a-zA-Z, match 2 or more digits to pass the rule
A two-character username can only use alphabet letters as characters.

^(?:[a-zA-Z]{2,}\d*|[a-zA-Z]\d{2,})$

Regex demo

let userCheck = /^[a-zA-Z](?:[a-zA-Z]+\d*|\d{2,})$/;
[
  "BadUs3rnam3",
  "c57bT3",
  "aa",
  "a111111",
  "a1",
  "11"
].forEach(username => console.log(username + ": " + userCheck.test(username)));


问:
What Need to Pass for Logout Passport Function
Using Passport for Access Token and Refresh Token. For Logout function what should be Posted/Get and What will be the URL?

API Route:

```<code> Route::group([
      'middleware' => 'auth:api'
    ], function() {
        Route::get('logout', 'api\LoginController@logout');
    });
</code>```

```<code>public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return $this->loggedOut($request);
    }
</code>```

URL: http://localhost:8000/api/auth/logout ???

What should be posted for this URL ?

答:
You have to pass access_token in Authorization header which you have got after successfully logged in.

Your logout route is protected by passport so When calling routes that are protected by Passport, your application's API consumers should specify their access token as a Bearer token in the Authorization header of their request.

For example, when using the Guzzle HTTP library:

```<code>$response = $client->request('GET', '/api/logout', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);
</code>```

from the doc laravel passport passing access token

Body:
Using Passport for Access Token and Refresh Token. For Logout function what should be Posted/Get and What will be the URL?

API Route:

 Route::group([
      'middleware' => 'auth:api'
    ], function() {
        Route::get('logout', 'api\LoginController@logout');
    });

public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return $this->loggedOut($request);
    }

URL: http://localhost:8000/api/auth/logout ???

What should be posted for this URL ?

Body:
You have to pass access_token in Authorization header which you have got after successfully logged in.

Your logout route is protected by passport so When calling routes that are protected by Passport, your application's API consumers should specify their access token as a Bearer token in the Authorization header of their request.

For example, when using the Guzzle HTTP library:

$response = $client->request('GET', '/api/logout', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);

from the doc laravel passport passing access token