问:
OOP throw two dice this.setSumTotal(); does not work
Just been experimenting with a class in which 2 dice are thrown and the total calculated. I am using OOP setting the total to this.dice1+this.dice2. However, when instantiating a Dice in another class the dice1 & dice2 throw work fine and generate 2 random numbers between 1 and 6. However, the sumTotal just defaults to 0 rather than adding dice1 and dice2.

Dice class:

public class Dice {

```<code>//create a random class
Random random = new Random();

//constants set the boundaries of possible dice roll values
private final static int UPPER_DICE_ROLL_LIMIT=6;
private final static int LOWER_DICE_ROLL_LIMIT=1;

//instance vars
private int dice1;
private int dice2;
private int sumTotal;

/**
 * default constructor
 */
public Dice() {
}

/**
 * @param dice1
 * @param dice2
 * @param sumTotal
 */
public Dice(int dice1, int dice2) {
    this.setDice1(dice1);
    this.setDice2(dice2);
    this.setSumTotal();
}

/**
 * @return the dice1
 */
public int getDice1() {
    return dice1;
}

/**
 * sets the number of dice1's roll - must be >=1 & <=6
 * @param dice1 the dice1 to set
 */
public void setDice1(int dice1) throws IllegalArgumentException {
    if (dice1>=LOWER_DICE_ROLL_LIMIT && dice1<=UPPER_DICE_ROLL_LIMIT) {
        this.dice1 = dice1;
    }else {
        throw new IllegalArgumentException("Invalid number");
    }
}

/**
 * @return the dice2
 */
public int getDice2() {
    return dice2;
}

/**
 * sets the number of dice2's roll - must be >=1 & <=6
 * @param dice2 the dice2 to set
 */
public void setDice2(int dice2) throws IllegalArgumentException {
    if (dice2>=LOWER_DICE_ROLL_LIMIT && dice2<=UPPER_DICE_ROLL_LIMIT) {
        this.dice2 = dice2;
    }else {
        throw new IllegalArgumentException("Invalid number");
    }this.dice2 = dice2;
}

/**
 * @return the sumTotal
 */
public int getSumTotal() {
    return sumTotal;
}

/**
 * sets the total score of the two dice (dice1 + dice2)
 * @param sumTotal the sumTotal to set
 */
public void setSumTotal() {
    this.sumTotal = this.dice1 + this.dice2;
}

/**
 * method to set randomly set the values of the dice rolls
 */
public void rollDice() {

    this.setDice1(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);
    this.setDice2(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);

}
</code>```

}

Game class:

public class Game {

```<code>public static void main(String[] args) {

    Dice dice = new Dice();

    dice.rollDice();

    System.out.println(dice.getDice1());
    System.out.println(dice.getDice2());
    System.out.println(dice.getSumTotal());

    }
</code>```

}

Thanks in advance, Cameron

答:
Your function setSumTotal() is currently not called after rolling your dice. You could change your function rollDice() to:</p>
```<code>public void rollDice() {

    this.setDice1(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);
    this.setDice2(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);
    this.setSumTotal();

}
</code>```

Body:
Just been experimenting with a class in which 2 dice are thrown and the total calculated. I am using OOP setting the total to this.dice1+this.dice2. However, when instantiating a Dice in another class the dice1 & dice2 throw work fine and generate 2 random numbers between 1 and 6. However, the sumTotal just defaults to 0 rather than adding dice1 and dice2.

Dice class:

public class Dice {

//create a random class
Random random = new Random();

//constants set the boundaries of possible dice roll values
private final static int UPPER_DICE_ROLL_LIMIT=6;
private final static int LOWER_DICE_ROLL_LIMIT=1;

//instance vars
private int dice1;
private int dice2;
private int sumTotal;

/**
 * default constructor
 */
public Dice() {
}

/**
 * @param dice1
 * @param dice2
 * @param sumTotal
 */
public Dice(int dice1, int dice2) {
    this.setDice1(dice1);
    this.setDice2(dice2);
    this.setSumTotal();
}

/**
 * @return the dice1
 */
public int getDice1() {
    return dice1;
}

/**
 * sets the number of dice1's roll - must be >=1 & <=6
 * @param dice1 the dice1 to set
 */
public void setDice1(int dice1) throws IllegalArgumentException {
    if (dice1>=LOWER_DICE_ROLL_LIMIT && dice1<=UPPER_DICE_ROLL_LIMIT) {
        this.dice1 = dice1;
    }else {
        throw new IllegalArgumentException("Invalid number");
    }
}

/**
 * @return the dice2
 */
public int getDice2() {
    return dice2;
}

/**
 * sets the number of dice2's roll - must be >=1 & <=6
 * @param dice2 the dice2 to set
 */
public void setDice2(int dice2) throws IllegalArgumentException {
    if (dice2>=LOWER_DICE_ROLL_LIMIT && dice2<=UPPER_DICE_ROLL_LIMIT) {
        this.dice2 = dice2;
    }else {
        throw new IllegalArgumentException("Invalid number");
    }this.dice2 = dice2;
}

/**
 * @return the sumTotal
 */
public int getSumTotal() {
    return sumTotal;
}

/**
 * sets the total score of the two dice (dice1 + dice2)
 * @param sumTotal the sumTotal to set
 */
public void setSumTotal() {
    this.sumTotal = this.dice1 + this.dice2;
}

/**
 * method to set randomly set the values of the dice rolls
 */
public void rollDice() {

    this.setDice1(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);
    this.setDice2(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);

}

}

Game class:

public class Game {

public static void main(String[] args) {

    Dice dice = new Dice();

    dice.rollDice();

    System.out.println(dice.getDice1());
    System.out.println(dice.getDice2());
    System.out.println(dice.getSumTotal());

    }

}

Thanks in advance, Cameron

Body:
Your function setSumTotal() is currently not called after rolling your dice. You could change your function rollDice() to:

public void rollDice() {

    this.setDice1(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);
    this.setDice2(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);
    this.setSumTotal();

}


来源: stackexchange

问:
Syntax error in sqlite statement in python?
I have the following code fragment in an object initializer. However, the third line below gives the error sqlite3.OperationalError: near "(": syntax error

```<code>self._conn = sqlite3.connect('dictionary')
cursor = self._conn.cursor()
cursor.execute('CREATE TABLE `words` (`word` VARCHAR(15) NOT NULL, PRIMARY (`word`));')
</code>```

Any ideas as to what could be causing this. I'm far from an export at SQL but I fail to see what I did incorrectly.

答:
You are missing a KEY here.

```<code>CREATE TABLE `words` (`word` VARCHAR(15) NOT NULL, PRIMARY KEY(`word`))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code fragment in an object initializer. However, the third line below gives the error sqlite3.OperationalError: near "(": syntax error

self._conn = sqlite3.connect('dictionary')
cursor = self._conn.cursor()
cursor.execute('CREATE TABLE `words` (`word` VARCHAR(15) NOT NULL, PRIMARY (`word`));')

Any ideas as to what could be causing this. I'm far from an export at SQL but I fail to see what I did incorrectly.

Body:
You are missing a KEY here.

CREATE TABLE `words` (`word` VARCHAR(15) NOT NULL, PRIMARY KEY(`word`))


问:
Override placeholder value in third party input
I'm using a third party tag-input and there's already a placeholder value. I would like to change the value of the placeholder. How would I do that? Right now it's "Enter a tag."</p>

```<code><tag-input name="tags" [(ngModel)]='tags'></tag-input>
</code>```

答:
<tag-input
  [(ngModel)]="game_ids"
  **secondaryPlaceholder="enter game id's"**
  [modelAsStrings]="true"
  [errorMessages]="asyncErrorMessages"
  [asyncValidators]="asyncValidators"
  (onAdd)="onTagAdd($event)"
  (onRemove)="onTagRemove($event)"
  #tagsinput
></tag-input>
```

Body:
I'm using a third party tag-input and there's already a placeholder value. I would like to change the value of the placeholder. How would I do that? Right now it's "Enter a tag."

<tag-input name="tags" [(ngModel)]='tags'></tag-input>

ContentLicense: CC BY-SA 4.0


问:
flutter: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>'
I get this error while serializing my json.
I am not sure I understand the error, but I have figured out that the code never reaches Prices.fromJson if I try to print something there. As you can see I am using Firebase Cloud Functions to return a data with nested data objects, and I struggle to get them serialized.

Code:

```<code>class Price {
  final DateTime validFrom;
  final DateTime validTo;
  final double nokPerKwh;

  const Price({
    required this.validFrom,
    required this.validTo,
    required this.nokPerKwh,
  });

  factory Price.fromJson(Map<String, dynamic> json) {
    return Price(
      validFrom: DateTime.parse(json['validFrom']),
      validTo: DateTime.parse(json['validTo']),
      nokPerKwh: json['nokPerKwh'],
    );
  }
}

class Prices {
  final double now;
  final Price lowest;
  final Price highest;

  const Prices({
    required this.now,
    required this.lowest,
    required this.highest,
  });

  factory Prices.fromJson(Map<String, dynamic> json) {
    return Prices(
      now: json['now'],
      lowest: Price.fromJson(json['lowest']),
      highest: Price.fromJson(json['highest']),
    );
  }
}

class ShowerCost {
  final DateTime time;
  final int minutes;
  final Prices prices;

  const ShowerCost({
    required this.time,
    required this.minutes,
    required this.prices,
  });

  factory ShowerCost.fromJson(Map<String, dynamic> json) {
    print(json); <--- {minutes: 20, time: 2022-02-07T23:46:41.625Z, prices: {now: 11.848, highest: null, lowest: {nokPerKwh: 1.1848, validFrom: 2022-02-08T00:00:00+01:00, validTo: 2022-02-08T01:00:00+01:00}}}
    return ShowerCost(
      time: DateTime.parse(json['time']),
      minutes: json['minutes'],
      prices: Prices.fromJson(json['prices']),
    );
  }
}

Future<ShowerCost> getShowerCost() async {
  try {
    HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('getShowerCost');
    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 7, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 7, 23).toIso8601String()
    });
    return ShowerCost.fromJson(results.data);
  } catch (error) {
    print(error);
    return Future.error(error);
  }
}
</code>```

答:
Both @rapaterno's and @mohamed abu-ghazalla's answers pointed me into the right direction.
Conversion to Map<String, dynamic> using Map<String, dynamic>.from(...) needed to happen in all the child's fromJson() params:

```<code>factory Price.fromJson(Map<String, dynamic> json) {
  return Price(
    validFrom: DateTime.parse(json['validFrom']),
    validTo: DateTime.parse(json['validTo']),
    nokPerKwh: json['nokPerKwh'],
  );
}

factory Prices.fromJson(Map<String, dynamic> json) {
  return Prices(
    now: json['now'],
    lowest: Price.fromJson(Map<String, dynamic>.from(json['lowest'])),   <--- HERE
    highest: Price.fromJson(Map<String, dynamic>.from(json['highest'])), <--- HERE
  );
}

factory ShowerCost.fromJson(Map<String, dynamic> json) {
  return ShowerCost(
    time: DateTime.parse(json['time']),
    minutes: json['minutes'],
    prices: Prices.fromJson(Map<String, dynamic>.from(json['prices'])),  <--- HERE
  );
}

Future<ShowerCost> getShowerCost() async {
  try {
    HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('getShowerCost');
    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 8, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 8, 23).toIso8601String()
    });
    return ShowerCost.fromJson(results.data);
  } catch (error) {
    print(error);
    return Future.error(error);
  }
}
</code>```

Body:
I get this error while serializing my json.
I am not sure I understand the error, but I have figured out that the code never reaches Prices.fromJson if I try to print something there. As you can see I am using Firebase Cloud Functions to return a data with nested data objects, and I struggle to get them serialized.

Code:

class Price {
  final DateTime validFrom;
  final DateTime validTo;
  final double nokPerKwh;

  const Price({
    required this.validFrom,
    required this.validTo,
    required this.nokPerKwh,
  });

  factory Price.fromJson(Map<String, dynamic> json) {
    return Price(
      validFrom: DateTime.parse(json['validFrom']),
      validTo: DateTime.parse(json['validTo']),
      nokPerKwh: json['nokPerKwh'],
    );
  }
}

class Prices {
  final double now;
  final Price lowest;
  final Price highest;

  const Prices({
    required this.now,
    required this.lowest,
    required this.highest,
  });

  factory Prices.fromJson(Map<String, dynamic> json) {
    return Prices(
      now: json['now'],
      lowest: Price.fromJson(json['lowest']),
      highest: Price.fromJson(json['highest']),
    );
  }
}

class ShowerCost {
  final DateTime time;
  final int minutes;
  final Prices prices;

  const ShowerCost({
    required this.time,
    required this.minutes,
    required this.prices,
  });

  factory ShowerCost.fromJson(Map<String, dynamic> json) {
    print(json); <--- {minutes: 20, time: 2022-02-07T23:46:41.625Z, prices: {now: 11.848, highest: null, lowest: {nokPerKwh: 1.1848, validFrom: 2022-02-08T00:00:00+01:00, validTo: 2022-02-08T01:00:00+01:00}}}
    return ShowerCost(
      time: DateTime.parse(json['time']),
      minutes: json['minutes'],
      prices: Prices.fromJson(json['prices']),
    );
  }
}

Future<ShowerCost> getShowerCost() async {
  try {
    HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('getShowerCost');
    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 7, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 7, 23).toIso8601String()
    });
    return ShowerCost.fromJson(results.data);
  } catch (error) {
    print(error);
    return Future.error(error);
  }
}

Body:
Both @rapaterno's and @mohamed abu-ghazalla's answers pointed me into the right direction.
Conversion to Map<String, dynamic> using Map<String, dynamic>.from(...) needed to happen in all the child's fromJson() params:

factory Price.fromJson(Map<String, dynamic> json) {
  return Price(
    validFrom: DateTime.parse(json['validFrom']),
    validTo: DateTime.parse(json['validTo']),
    nokPerKwh: json['nokPerKwh'],
  );
}

factory Prices.fromJson(Map<String, dynamic> json) {
  return Prices(
    now: json['now'],
    lowest: Price.fromJson(Map<String, dynamic>.from(json['lowest'])),   <--- HERE
    highest: Price.fromJson(Map<String, dynamic>.from(json['highest'])), <--- HERE
  );
}

factory ShowerCost.fromJson(Map<String, dynamic> json) {
  return ShowerCost(
    time: DateTime.parse(json['time']),
    minutes: json['minutes'],
    prices: Prices.fromJson(Map<String, dynamic>.from(json['prices'])),  <--- HERE
  );
}

Future<ShowerCost> getShowerCost() async {
  try {
    HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('getShowerCost');
    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 8, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 8, 23).toIso8601String()
    });
    return ShowerCost.fromJson(results.data);
  } catch (error) {
    print(error);
    return Future.error(error);
  }
}


问:
If q-char-sequence is about source file, then why the grammar doesn't have source-file-name?
C2x, 6.10.2 Source file inclusion, Semantics, 2 (emphasis added):

A preprocessing directive of the form

```<code># include " q-char-sequence " new-line
</code>```

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

C2x, 6.4.7 Header names, Syntax, 1:

```<code>header-name:
                 < h-char-sequence >
                 " q-char-sequence "
</code>```

If q-char-sequence is about source file, then why the grammar doesn't have source-file-name?

Meaning that per grammar "x.c", "x.h", <x.c>, and <x.h> are all header-name. A bit confused.

答:
The grammar could not have been written

```<code>header-name: < source-file-name > | " source-file-name "
source-file-name: h-char-sequence | q-char-sequence
</code>```

because that would allow either type of char-sequence to be used with either type of delimiter, and that would be incorrect, because the sequences are not the same. h-char-sequence does not allow > and q-char-sequence does not allow ".

If that's not your question then I don't understand what you want to know.

Body:
C2x, 6.10.2 Source file inclusion, Semantics, 2 (emphasis added):

A preprocessing directive of the form

# include " q-char-sequence " new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

C2x, 6.4.7 Header names, Syntax, 1:

header-name:
                 < h-char-sequence >
                 " q-char-sequence "

If q-char-sequence is about source file, then why the grammar doesn't have source-file-name?

Meaning that per grammar "x.c", "x.h", <x.c>, and <x.h> are all header-name. A bit confused.

Body:
The grammar could not have been written

header-name: < source-file-name > | " source-file-name "
source-file-name: h-char-sequence | q-char-sequence

because that would allow either type of char-sequence to be used with either type of delimiter, and that would be incorrect, because the sequences are not the same. h-char-sequence does not allow > and q-char-sequence does not allow ".

If that's not your question then I don't understand what you want to know.


问:
Is there a way to create a list that auto populates with the the required articles?
I am a UI/UX designer and I have taken on a new project to overhaul our Zendesk. I have no experience but I am learning on the fly, I have already built a custom sidebar navigation and now my problem is this:

Is there a way to have the sidebar auto populate with the categories and articles from our knowledge base? I assume there is a way to do this, otherwise that would mean every time I upload a new document to our knowledge base I will also have to go back into the code and add the href with the link and title to the sidebar nav html and I'm certain that's not the way this works. I'm happy to do the research but I don't know what to search for, I've tried researching auto populating lists etc. but nothing matches my need. I can manually input every article into the side bar and it functions beautifully, I just figured there was an actual way to automate this once the code is input.

Thank you in advance,

-Newbie

答:
Why are you adding a list manually, you can call API for all categories of your Help Centre and make a sidebar:

1). Add the below code to your script.js file at the bottom.

```<code>$.getJSON('/api/v2/help_center/categories/' , function(el){
  console.log(el)
  var _x = '';
  $.each(el.categories, function (idx, itm){
    _x += '<a href = "'+itm.html_url+'" class="category-items">' + itm.name + '</a><br>';
  });

if("ul.categories"){
  $(".categories").html(_x);
}
});
</code>```

2). document_head.hbs should have jquery CDN.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</code>```

3). Add this HTML to your template where you want to show the categories.

 Categories

The given solution is only for listing all categories not articles, you can add the articles inside the categories using the API inside it: https://developer.zendesk.com/api-reference/help_center/help-center-api/articles/

If you want to show only articles not categories then replace the API with the article's API.

Body:
Why are you adding a list manually, you can call API for all categories of your Help Centre and make a sidebar:

1). Add the below code to your script.js file at the bottom.

$.getJSON('/api/v2/help_center/categories/' , function(el){
  console.log(el)
  var _x = '';
  $.each(el.categories, function (idx, itm){
    _x += '<a href = "'+itm.html_url+'" class="category-items">' + itm.name + '</a><br>';
  });

if("ul.categories"){
  $(".categories").html(_x);
}
});

2). document_head.hbs should have jquery CDN.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

3). Add this HTML to your template where you want to show the categories.

 Categories

The given solution is only for listing all categories not articles, you can add the articles inside the categories using the API inside it: https://developer.zendesk.com/api-reference/help_center/help-center-api/articles/

If you want to show only articles not categories then replace the API with the article's API.


问:
proc transpose with duplicate ID values
I need help with proc transpose procedure in SAS. My code initially was:

```<code>proc transpose data=temp out=temp1;
by patid;
var text;
Id datanumber;
run;
</code>```

This gave me error "The ID value " " occurs twice in the same BY group". I modified the code to this:

```<code>proc sort data = temp;
by patid text datanumber;
run;

data temp;
set temp by patid text datanumber;
if first.datanunmber then n = 0;
n+1;
run;

proc sort data = temp;
by patid text datanumber n;
run;

proc transpose out=temp1 (drop=n) let;
by patid;
var text;
id datanumber;
run;
</code>```

This is giving me error: variable n is not recognized. Adding a let option is giving a lot of error "occurs twice in the same BY group". I want to keep all id values.

Please help me in this.

Data Example:
Patid          Text

答: Try to sort your dataset by patid text n datanumber, (n before datanumber).</p>

Title: proc transpose with duplicate ID values

Body:
I need help with proc transpose procedure in SAS. My code initially was:

proc transpose data=temp out=temp1;
by patid;
var text;
Id datanumber;
run;

This gave me error "The ID value " " occurs twice in the same BY group". I modified the code to this:

proc sort data = temp;
by patid text datanumber;
run;

data temp;
set temp by patid text datanumber;
if first.datanunmber then n = 0;
n+1;
run;

proc sort data = temp;
by patid text datanumber n;
run;

proc transpose out=temp1 (drop=n) let;
by patid;
var text;
id datanumber;
run;

This is giving me error: variable n is not recognized. Adding a let option is giving a lot of error "occurs twice in the same BY group". I want to keep all id values.

Please help me in this.

Data Example:
Patid          Text


问:
How to get MVC ActionLink Full Path in Jquery
I am trying to set the class on the selected menu anchor based on the URL. I have below actionlinks

```<code>@Html.ActionLink("Home","Index","Home" new {type="new task"},null)
@Html.ActionLink("Home","Index")
</code>```

I need to get its fullpath in Jquery to change the selected link based on the url as given below

```<code>$("a").each(function () {
 if (location.indexOf($(this).prop('href')) != -1) {
                          $(this).addClass('mlnkactive').siblings().removeClass('mlnkactive');
                        $(this).parent().addClass('mlnkactive').siblings().removeClass('mlnkactive');
});
</code>```

The problem is that when i get href of the links using $(this).prop('href') , both of the above Home links have the same href.So both of the Anchors are selected and I am unable to set the class on the selected Link based on URL.

Thanks,

答:
Maybe try to user normal  with @Url.Action inside href attribute. For example:</p>

```<code><a href="@Url.Action("action_name", "controller", new { action_parametr_name = action_parameter_value})">Link 1</a>
</code>```

Body:
I am trying to set the class on the selected menu anchor based on the URL. I have below actionlinks

@Html.ActionLink("Home","Index","Home" new {type="new task"},null)
@Html.ActionLink("Home","Index")

I need to get its fullpath in Jquery to change the selected link based on the url as given below

$("a").each(function () {
 if (location.indexOf($(this).prop('href')) != -1) {
                          $(this).addClass('mlnkactive').siblings().removeClass('mlnkactive');
                        $(this).parent().addClass('mlnkactive').siblings().removeClass('mlnkactive');
});

The problem is that when i get href of the links using $(this).prop('href') , both of the above Home links have the same href.So both of the Anchors are selected and I am unable to set the class on the selected Link based on URL.

Thanks,

Body:
Maybe try to user normal  with @Url.Action inside href attribute. For example:

<a href="@Url.Action("action_name", "controller", new { action_parametr_name = action_parameter_value})">Link 1</a>


问:
Can I pass an infinite number of arguments to a generic type?
I'm trying to pass a few arguments, but I get an error from linter: TS2314: Generic type 'FruitKit ' requires 1 type argument(s).

I tried to use something by type ...args, but it also didn't work.

```<code>interface Apple {
    red: number;
    yellow: number;
}

interface Banana {
    ripe: number;
    rotten: number;
}

interface FruitKit<T> {
    fruits: T
}

interface MyCustomFruitKit extends FruitKit<Apple, Banana> {}

const FruitKit: MyCustomFruitKit = {
    fruits: {
        red: 1,
        yellow: 2
    }
};
</code>```

答:
You can only pass a single type argument to a type that expects only a single type parameter. What you in this case depends on what you want, whether you want FruitKit<Apple, Banana> to mean that each property is both an Apple and a Banana, or that each property is either an Apple or a Banana. From your example usage, I suspect you want either/or, which is the union type Apple | Banana:

```<code>interface MyCustomFruitKit extends FruitKit<Apple | Banana> {}
</code>```

Playground link

(If you wanted them to be both, it would be &, an intersection, rather than |, and your objects in the usage example would need all four properties [red and yellow and ripe and rotten].)

Side note: I'd avoid having a type and a constant with the same name (FruitKit). Although the names live in different namespaces, it's still confusing to the programmer reading the code.

Body:
I'm trying to pass a few arguments, but I get an error from linter: TS2314: Generic type 'FruitKit ' requires 1 type argument(s).

I tried to use something by type ...args, but it also didn't work.

interface Apple {
    red: number;
    yellow: number;
}

interface Banana {
    ripe: number;
    rotten: number;
}

interface FruitKit<T> {
    fruits: T
}

interface MyCustomFruitKit extends FruitKit<Apple, Banana> {}

const FruitKit: MyCustomFruitKit = {
    fruits: {
        red: 1,
        yellow: 2
    }
};

Body:
You can only pass a single type argument to a type that expects only a single type parameter. What you in this case depends on what you want, whether you want FruitKit<Apple, Banana> to mean that each property is both an Apple and a Banana, or that each property is either an Apple or a Banana. From your example usage, I suspect you want either/or, which is the union type Apple | Banana:

interface MyCustomFruitKit extends FruitKit<Apple | Banana> {}

Playground link

(If you wanted them to be both, it would be &, an intersection, rather than |, and your objects in the usage example would need all four properties [red and yellow and ripe and rotten].)

Side note: I'd avoid having a type and a constant with the same name (FruitKit). Although the names live in different namespaces, it's still confusing to the programmer reading the code.


问:
React Native image cropping with multi picker and permission handling
I'm working on an application that is based on image processing. I need to select multiple images from the picker at the same time and show them in the view container, where first it will ask for permission then pick images from the gallery or camera. I also need a cropping feature in it to crop the image. Something like the utility class of image selection supports all the options needed for the application. I'm using the following code</p>
```<code>class App extends Component {

  state = {
    image: Images.placeholderImage
  }

  onPress = () => {
    // Here goes the picker code
  }

 render() {
    return (
      <View>
        <View>
          <Image source={this.state.image} style={{width:200, height:200}}/>
        </View>
        <TouchableOpacity onPress={this.onPress}>
          <Text>Select Image</Text>
        </TouchableOpacity>
      </View>
    )
  }
}
</code>```

答:
Go to Simulator > Device > Erase All Content and Settings

worked for me in iOS

Body:
I'm working on an application that is based on image processing. I need to select multiple images from the picker at the same time and show them in the view container, where first it will ask for permission then pick images from the gallery or camera. I also need a cropping feature in it to crop the image. Something like the utility class of image selection supports all the options needed for the application. I'm using the following code

class App extends Component {

  state = {
    image: Images.placeholderImage
  }

  onPress = () => {
    // Here goes the picker code
  }

 render() {
    return (
      <View>
        <View>
          <Image source={this.state.image} style={{width:200, height:200}}/>
        </View>
        <TouchableOpacity onPress={this.onPress}>
          <Text>Select Image</Text>
        </TouchableOpacity>
      </View>
    )
  }
}


问:
How to set an angular mat radio button to selected by default?
I would like to ask , I am using the update angular verion. I was trying to set a mat radio button as selected by default , I tried using [checked]="true" but it does not seem to work . Any idea ? or any update on the syntax? Thanks.

#Code

```<code> <mat-radio-group name="isSubleaseCoterminusWithMasterLease" (change)="onChangeSubleaseCoterminus($event)" [(ngModel)]="dealDispositionFormFields.isSubleaseCoterminusWithMasterLease">
            <div class="flex" style="justify-content: space-between;">
              <div class="deal-form-btn-group w-46-per" [ngClass]="{'v-bg-color': dealDispositionFormFields.isSubleaseCoterminusWithMasterLease === 'No'}"  >
                <div class="deal-form-btn-group-radio">
                  <mat-radio-button
                  [checked]='true'
                  *ngIf="dealDispositionFormFields.isSubleaseCoterminusWithMasterLease === 'No' else notSubleaseCoterminusWithMasterLease"
                    color="accent"
                    [value]="'No'">
                      <span class="alter-text-color">No</span>
                  </mat-radio-button>
                  <ng-template #notSubleaseCoterminusWithMasterLease>
                    <mat-radio-button
                     [checked]="true"
                      [value]="'No'">
                        No
                    </mat-radio-button>
                  </ng-template>
                </div>
              </div>
            </div>
          </mat-radio-group>
</code>```

答:
You can use ngModel inside the <mat-radio-group> tag this as follows

```<code><mat-radio-group  [(ngModel)]="selected">
</code>```

And in your .ts file

```<code>selected: string;
ngOnInit(){
   this.selected = "No";
}
</code>```

Here is a working example:  Stackblitz

Body:
I would like to ask , I am using the update angular verion. I was trying to set a mat radio button as selected by default , I tried using [checked]="true" but it does not seem to work . Any idea ? or any update on the syntax? Thanks.

#Code

 <mat-radio-group name="isSubleaseCoterminusWithMasterLease" (change)="onChangeSubleaseCoterminus($event)" [(ngModel)]="dealDispositionFormFields.isSubleaseCoterminusWithMasterLease">

                  <mat-radio-button
                  [checked]='true'
                  *ngIf="dealDispositionFormFields.isSubleaseCoterminusWithMasterLease === 'No' else notSubleaseCoterminusWithMasterLease"
                    color="accent"
                    [value]="'No'">
                      No
                  </mat-radio-button>
                  <ng-template #notSubleaseCoterminusWithMasterLease>
                    <mat-radio-button
                     [checked]="true"
                      [value]="'No'">
                        No
                    </mat-radio-button>
                  </ng-template>

          </mat-radio-group>

Body:
You can use ngModel inside the <mat-radio-group> tag this as follows

<mat-radio-group  [(ngModel)]="selected">

And in your .ts file

selected: string;
ngOnInit(){
   this.selected = "No";
}

Here is a working example:  Stackblitz


问:
PHP, Get array key by searching in every sub array
I have an array of list of currencies and each currency got an subarray with all countries.

I will receive a country (alpha 2 code) and i need to retrieve the currency associated with my previous array.

```<code>$currencies = [
    'EUR' => ['AT', 'BE', 'CY', 'EE', 'FI', 'FR', 'DE', 'GR', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PT', 'ES', 'SI', 'SK'],
    'JPY' => ['JP'],
    'IDR' => ['ID']
];
</code>```

I can do it with a foreach, but i hope that PHP have a function to automatically do it but i didn't find it.

Someone already do that ?

答:
You could use array_filter to get an array that matches a condition.

$needle = 'AT';

$filtered = array_filter($currencies, function ($haystack) use ($needle) {
    // return in_array($needle, $haystack);
    return isset(array_flip($haystack)[$needle]); // more efficient than in_array
});

$countriesArray = array_keys($filtered); // ['EUR']
```
<p>Using Collections</p>
```$res = collect($currencies)
    ->filter(function ($haystack) use ($needle) {
        return isset(array_flip($haystack)[$needle]);
    })
    ->keys()
    ->all();
```
<p>Using Collection and short closures</p>
```$res = collect($currencies)
    ->filter(fn($haystack) => isset(array_flip($haystack)[$needle]))
    ->keys()
    ->all();
```

Body:
I have an array of list of currencies and each currency got an subarray with all countries.

I will receive a country (alpha 2 code) and i need to retrieve the currency associated with my previous array.

$currencies = [
    'EUR' => ['AT', 'BE', 'CY', 'EE', 'FI', 'FR', 'DE', 'GR', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PT', 'ES', 'SI', 'SK'],
    'JPY' => ['JP'],
    'IDR' => ['ID']
];

I can do it with a foreach, but i hope that PHP have a function to automatically do it but i didn't find it.

Someone already do that ?

Body:
You could use array_filter to get an array that matches a condition.

$needle = 'AT';

$filtered = array_filter($currencies, function ($haystack) use ($needle) {
    // return in_array($needle, $haystack);
    return isset(array_flip($haystack)[$needle]); // more efficient than in_array
});

$countriesArray = array_keys($filtered); // ['EUR']

Using Collections

$res = collect($currencies)
    ->filter(function ($haystack) use ($needle) {
        return isset(array_flip($haystack)[$needle]);
    })
    ->keys()
    ->all();

Using Collection and short closures

$res = collect($currencies)
    ->filter(fn($haystack) => isset(array_flip($haystack)[$needle]))
    ->keys()
    ->all();


问:
Delete key and value form a dictionary, if it is longer than 5 symbols
How to create a new dictionary where all keys and values are converted to string type? If string length is more than 5 symbols it must be excluded from the answer (both the key and value)

My code now looks like this:

file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

key_values = file1data.items()
new_dictionary = {str(key):str(value) for key, value in key_values}

print((str(new_dictionary)))

```

It can covert all values and keys to a string type, but not detect if length is more than 5.

For example if is given this dictionary: {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

The result should be: {"1":"2","2":"5","1231":"14","-2":"7"}

答:
Add if statement inside dict comprehension like so</p>
```<code>file1data = {"1": "2", 2: 5, "12dade": -1, "1231": 14, "-2": 7}

key_values = file1data.items()
new_dictionary = {str(key): str(value) for key, value in key_values if len(str(key)) <= 5 and len(str(value)) <= 5}

print((str(new_dictionary)))
</code>```

Body:
How to create a new dictionary where all keys and values are converted to string type? If string length is more than 5 symbols it must be excluded from the answer (both the key and value)

My code now looks like this:

file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

key_values = file1data.items()
new_dictionary = {str(key):str(value) for key, value in key_values}

print((str(new_dictionary)))

It can covert all values and keys to a string type, but not detect if length is more than 5.

For example if is given this dictionary: {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

The result should be: {"1":"2","2":"5","1231":"14","-2":"7"}

Body:
Add if statement inside dict comprehension like so

file1data = {"1": "2", 2: 5, "12dade": -1, "1231": 14, "-2": 7}

key_values = file1data.items()
new_dictionary = {str(key): str(value) for key, value in key_values if len(str(key)) <= 5 and len(str(value)) <= 5}

print((str(new_dictionary)))


Title: Delete key and value form a dictionary, if it is longer than 5 symbols

Body:
Use a comprehension:

d = {'1': '2', 2: 5, '12dade': -1, '1231': 14, '-2': 7}
out = {k: v for k, v in d.items() if len(str(k)) <= 5 and len(str(v)) <= 5}
print(out)

# Output
{'1': '2', 2: 5, '1231': 14, '-2': 7}


问:
Xamarin Forms Zxing scan problem with Black Background and White Qr Codes on Andriod Device
The problem about Zxing Forms Mobile is cannot scan black background, white color qr code. I've already tried to scan black color qr code,white background and it works.My test device is Android.

I've tried scan white color qr code by using a scanner which i found in play store and it works.So qr code is not bad.

I've tried all the variations in MobileBarcodeScanningOptions.

```<code>            var options = new MobileBarcodeScanningOptions
            {
                UseNativeScanning = true,
                TryHarder = true,
                TryInverted = true,
                AutoRotate = true,
                DisableAutofocus = false,
                UseFrontCameraIfAvailable = false,
                DelayBetweenAnalyzingFrames = 150,
                InitialDelayBeforeAnalyzingFrames = 300,
                DelayBetweenContinuousScans = 1000,
                PossibleFormats = new List<BarcodeFormat>
                {
                    BarcodeFormat.QR_CODE,
                }
            };
</code>```

So Is there anything for solution?

答:
Try to put a frame in the qr, with that it allowed me to scan.

This work for me

This dont

Body:
The problem about Zxing Forms Mobile is cannot scan black background, white color qr code. I've already tried to scan black color qr code,white background and it works.My test device is Android.

I've tried scan white color qr code by using a scanner which i found in play store and it works.So qr code is not bad.

I've tried all the variations in MobileBarcodeScanningOptions.

            var options = new MobileBarcodeScanningOptions
            {
                UseNativeScanning = true,
                TryHarder = true,
                TryInverted = true,
                AutoRotate = true,
                DisableAutofocus = false,
                UseFrontCameraIfAvailable = false,
                DelayBetweenAnalyzingFrames = 150,
                InitialDelayBeforeAnalyzingFrames = 300,
                DelayBetweenContinuousScans = 1000,
                PossibleFormats = new List<BarcodeFormat>
                {
                    BarcodeFormat.QR_CODE,
                }
            };

So Is there anything for solution?


问:
CSS Animation Wave effect with 3 layers
I'm trying to create a wave animation with 3 layers. The animation as you can see in the snippet, doesn't seem smooth, and it seems like the waves aren't endless. Besides I can't really get to see the waves structure like in the picture.

I would to see the waves without interruption, when it comes to the end of the animation, it is clearly noticeable that the animation has ended.
[![

.w1 {
  stroke: none;
  fill: #b3696c;
  opacity: 55%;
  animation: move1 4.5s linear infinite;
}
.w2 {
  stroke: none;
  fill: #b3696c;
  opacity: 35%;
  transform: translate3d(0, 0, 0);
  animation: move2 4.5s linear infinite;
}
.w3 {
  stroke: none;
  fill: #cf2127;
  opacity: 30%;
  transform: translate3d(0, 0, 0);
  animation: move3 2s linear infinite;
}
@keyframes move1 {
  0% {
    transform: translateX(-500px) scaleX(2.5);
  }
  50% {
    transform: translateX(-100) scaleX(2.5);
  }
  100% {
    transform: translateX(0) scaleX(2.5);
  }
}
@keyframes move2 {
  0% {
    transform: translateX(-600px) scaleX(3);
  }
  50% {
    transform: translateX(-100) scaleX(2.5);
  }
  100% {
    transform: translateX(0) scaleX(3);
  }
}
@keyframes move3 {
  0% {
    transform: translateX(-800px) scaleX(4);
  }
  50% {
    transform: translateX(-100) scaleX(2.5);
  }
  100% {
    transform: translateX(0) scaleX(4);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="waveAnimation">
      <svg viewBox="0 0 500 150" preserveAspectRatio="none">
        <path
          class="w1 waveTop"
          d="M-8.74,71.55 C289.78,255.11 349.60,4.47 505.36,34.05 L500.00,150.00 L0.00,150.00 Z"
        />
        <path
          class="w2 waveMiddle"
          d="M-23.42,125.83 C187.63,45.89 299.38,57.73 526.80,123.86 L500.00,150.00 L0.00,150.00 Z"
        />
        <path
          class="w3 waveBottom"
          d="M-23.42,125.83 C172.96,-152.44 217.55,183.06 504.22,55.77 L500.00,150.00 L0.00,150.00 Z"
        />
      </svg>
    </div></code>```

答:
Here is my solution, I hope it helps you.

.w1 {
    stroke: none;
    fill: #b3696c;
    opacity: 55%;
    animation: move1 6s linear infinite;
  }
  .w2 {
    stroke: none;
    fill: #b3696c;
    opacity: 35%;
    transform: translate3d(0, 0, 0);
    animation: move2 6s linear infinite;
  }
  .w3 {
    stroke: none;
    fill: #cf2127;
    opacity: 30%;
    transform: translate3d(0, 0, 0);
    animation: move3 2s linear infinite;
  }
  @keyframes move1 {
    0% {
      transform: translateX(-500px) scaleX(2.5);
    }
    25% {
      transform: translateX(-100) scaleX(2.5);
    }
    50% {
      transform: translateX(0) scaleX(2.5);
    }
    75% {
      transform: translateX(-100) scaleX(2.5);
    }
    100% {
      transform: translateX(-500px) scaleX(2.5);
    }
  }
  @keyframes move2 {
    0% {
      transform: translateX(-600px) scaleX(3);
    }
    25% {
      transform: translateX(-100) scaleX(2.5);
    }
    50% {
      transform: translateX(0) scaleX(3);
    }
    75% {
      transform: translateX(-100) scaleX(2.5);
    }
    100% {
      transform: translateX(-600px) scaleX(3);
    }
  }
  @keyframes move3 {
    0% {
      transform: translateX(-800px) scaleX(3);
    }
    25% {
      transform: translateX(-100) scaleX(2.5);
    }
    50% {
      transform: translateX(0) scaleX(3);
    }
    75% {
      transform: translateX(-100) scaleX(2.5);
    }
    100% {
      transform: translateX(-800px) scaleX(3);
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="waveAnimation">
  <svg viewBox="0 0 500 150" preserveAspectRatio="none">
    <path
    class="w1 waveTop"
    d="M-8.74,71.55 C289.78,255.11 349.60,4.47 505.36,34.05 L500.00,150.00 L0.00,150.00 Z"
    />
    <path
    class="w2 waveMiddle"
    d="M-23.42,125.83 C187.63,45.89 299.38,57.73 526.80,123.86 L500.00,150.00 L0.00,150.00 Z"
    />
    <path
    class="w3 waveBottom"
    d="M-23.42,125.83 C172.96,-152.44 217.55,183.06 504.22,55.77 L500.00,150.00 L0.00,150.00 Z"
    />
  </svg>
</div></code>```

Title: CSS Animation Wave effect with 3 layers

Body:
I'm trying to create a wave animation with 3 layers. The animation as you can see in the snippet, doesn't seem smooth, and it seems like the waves aren't endless. Besides I can't really get to see the waves structure like in the picture.

I would to see the waves without interruption, when it comes to the end of the animation, it is clearly noticeable that the animation has ended.
[![

.w1 {
  stroke: none;
  fill: #b3696c;
  opacity: 55%;
  animation: move1 4.5s linear infinite;
}
.w2 {
  stroke: none;
  fill: #b3696c;
  opacity: 35%;
  transform: translate3d(0, 0, 0);
  animation: move2 4.5s linear infinite;
}
.w3 {
  stroke: none;
  fill: #cf2127;
  opacity: 30%;
  transform: translate3d(0, 0, 0);
  animation: move3 2s linear infinite;
}
@keyframes move1 {
  0% {
    transform: translateX(-500px) scaleX(2.5);
  }
  50% {
    transform: translateX(-100) scaleX(2.5);
  }
  100% {
    transform: translateX(0) scaleX(2.5);
  }
}
@keyframes move2 {
  0% {
    transform: translateX(-600px) scaleX(3);
  }
  50% {
    transform: translateX(-100) scaleX(2.5);
  }
  100% {
    transform: translateX(0) scaleX(3);
  }
}
@keyframes move3 {
  0% {
    transform: translateX(-800px) scaleX(4);
  }
  50% {
    transform: translateX(-100) scaleX(2.5);
  }
  100% {
    transform: translateX(0) scaleX(4);
  }
}

      <svg viewBox="0 0 500 150" preserveAspectRatio="none">
        <path
          class="w1 waveTop"
          d="M-8.74,71.55 C289.78,255.11 349.60,4.47 505.36,34.05 L500.00,150.00 L0.00,150.00 Z"
        />
        <path
          class="w2 waveMiddle"
          d="M-23.42,125.83 C187.63,45.89 299.38,57.73 526.80,123.86 L500.00,150.00 L0.00,150.00 Z"
        />
        <path
          class="w3 waveBottom"
          d="M-23.42,125.83 C172.96,-152.44 217.55,183.06 504.22,55.77 L500.00,150.00 L0.00,150.00 Z"
        />
      </svg>

Body:
Here is my solution, I hope it helps you.

.w1 {
    stroke: none;
    fill: #b3696c;
    opacity: 55%;
    animation: move1 6s linear infinite;
  }
  .w2 {
    stroke: none;
    fill: #b3696c;
    opacity: 35%;
    transform: translate3d(0, 0, 0);
    animation: move2 6s linear infinite;
  }
  .w3 {
    stroke: none;
    fill: #cf2127;
    opacity: 30%;
    transform: translate3d(0, 0, 0);
    animation: move3 2s linear infinite;
  }
  @keyframes move1 {
    0% {
      transform: translateX(-500px) scaleX(2.5);
    }
    25% {
      transform: translateX(-100) scaleX(2.5);
    }
    50% {
      transform: translateX(0) scaleX(2.5);
    }
    75% {
      transform: translateX(-100) scaleX(2.5);
    }
    100% {
      transform: translateX(-500px) scaleX(2.5);
    }
  }
  @keyframes move2 {
    0% {
      transform: translateX(-600px) scaleX(3);
    }
    25% {
      transform: translateX(-100) scaleX(2.5);
    }
    50% {
      transform: translateX(0) scaleX(3);
    }
    75% {
      transform: translateX(-100) scaleX(2.5);
    }
    100% {
      transform: translateX(-600px) scaleX(3);
    }
  }
  @keyframes move3 {
    0% {
      transform: translateX(-800px) scaleX(3);
    }
    25% {
      transform: translateX(-100) scaleX(2.5);
    }
    50% {
      transform: translateX(0) scaleX(3);
    }
    75% {
      transform: translateX(-100) scaleX(2.5);
    }
    100% {
      transform: translateX(-800px) scaleX(3);
    }
  }

<div class="waveAnimation">
  <svg viewBox="0 0 500 150" preserveAspectRatio="none">
    <path
    class="w1 waveTop"
    d="M-8.74,71.55 C289.78,255.11 349.60,4.47 505.36,34.05 L500.00,150.00 L0.00,150.00 Z"
    />
    <path
    class="w2 waveMiddle"
    d="M-23.42,125.83 C187.63,45.89 299.38,57.73 526.80,123.86 L500.00,150.00 L0.00,150.00 Z"
    />
    <path
    class="w3 waveBottom"
    d="M-23.42,125.83 C172.96,-152.44 217.55,183.06 504.22,55.77 L500.00,150.00 L0.00,150.00 Z"
    />
  </svg>
</div>


问:
Highlight DT diagonal in R Shiny
I have a large datatable in a Shiny app and would like to highlight the diagonal, using logic something like if rowNum == colNum then 'blue' else 'white'.

The rowCallback DT option would let me style by row number, but I can't find anything in the docs that would do the equivalent for column number at the same time.

The best idea I have is to create ~200 extra boolean columns in the table just to determine whether each cell is highlighted or not, hiding them, and using formatStyle(valueColumns = 201:400) to style the others. But that seems like massive overkill here. Any bright ideas?

答:
```<code>library(tidyverse)
library(DT)
data <- rbind(c(1,2,3), c(4,5,6), c(7,8,9)) %>% as_tibble()
data
#> # A tibble: 3 x 3
#>      V1    V2    V3
#>   <dbl> <dbl> <dbl>
#> 1     1     2     3
#> 2     4     5     6
#> 3     7     8     9
data <-
  data %>%
  mutate(row_id = row_number()) %>%
  pivot_longer(-row_id) %>%
  group_by(row_id) %>%
  mutate(
    col_id = row_number(),
    value = value %>% as.character(),
    value = case_when(
      row_id == col_id ~ str_glue("<div style = 'color:red'> {value} </div>"),
      TRUE ~ value
    )
  ) %>%
  ungroup() %>%
  select(row_id, name, value) %>%
  pivot_wider() %>%
  select(-row_id)
data
#> # A tibble: 3 x 3
#>   V1                         V2                        V3
#>   <glue>                     <glue>                    <glue>
#> 1 <div style = 'color:red'>… 2                         3
#> 2 4                          <div style = 'color:red'… 6
#> 3 7                          8                         <div style = 'color:red'…

datatable(escape = FALSE, data)
</code>```

Title: Highlight DT diagonal in R Shiny


问:
Input box opens if one cell change and another is blank
I have the following script that adds the techs id to COLUMN J when the status is changed to "COMPLETED"

However I want the input box to open if the target cell (COMPLETED_COLUMN_NUMBER) is empty

```<code>function onEdit(e) {
  COMPLETED(e);
}

SHEET_TO_WORK_ON = 'Scoresby'; // Please enter the name of your sheet here
STATUS_COLUMN_NUMBER = 4;    // Enter the number of the column with the statuses here
LABOUR_COLUMN_NUMBER = 7;   // Enter the number of the column with the total amount charged here
COMPLETED_COLUMN_NUMBER = 10   // Enter the number of the column with the inspection

function COMPLETED(e){
  let range = e.range,
      sheet1 = range.getSheet();

  if (sheet1.getName() == SHEET_TO_WORK_ON && range.columnStart == STATUS_COLUMN_NUMBER && range.rowStart > 1 && e.value == 'Completed'){
      range.offset(0,COMPLETED_COLUMN_NUMBER - STATUS_COLUMN_NUMBER).setValue(Browser.inputBox('Tech ', 'Fill in the ID for the to who inspected the repair', Browser.Buttons.OK_CANCEL))
  }
}
</code>```

答:
I understand that you want to upgrade your code so it opens the input dialogue only if the target cell is empty. If my understanding of the scenario is correct, then there is one minor modification that you can script to upgrade your project. You only have to take the Range object in the script and use the getValue method to check if it is empty. In the following example I created the variable targetCellData to save the cell content. Then, if the cell is empty (meaning the content equals to '') the code runs the input dialogue.

function onEdit(e) {
  COMPLETED(e);
}

SHEET_TO_WORK_ON = 'Scoresby';
STATUS_COLUMN_NUMBER = 4;
LABOUR_COLUMN_NUMBER = 7;
COMPLETED_COLUMN_NUMBER = 10;

function COMPLETED(e) {
  let range = e.range,
    sheet1 = range.getSheet();

  if (sheet1.getName() == SHEET_TO_WORK_ON && range.columnStart ==
    STATUS_COLUMN_NUMBER && range.rowStart > 1 && e.value == 'Completed') {
    var targetCellData = range.offset(0, COMPLETED_COLUMN_NUMBER -
      STATUS_COLUMN_NUMBER).getValue();

    if (targetCellData == '') {
      range.offset(0, COMPLETED_COLUMN_NUMBER - STATUS_COLUMN_NUMBER).setValue(
        Browser.inputBox('Tech ',
          'Fill in the ID for the to who inspected the repair', Browser
          .Buttons.OK_CANCEL));
    }
  }
}
```

Please test this approach and let me know if it helps.

Body:
I have the following script that adds the techs id to COLUMN J when the status is changed to "COMPLETED"

However I want the input box to open if the target cell (COMPLETED_COLUMN_NUMBER) is empty

function onEdit(e) {
  COMPLETED(e);
}

SHEET_TO_WORK_ON = 'Scoresby'; // Please enter the name of your sheet here
STATUS_COLUMN_NUMBER = 4;    // Enter the number of the column with the statuses here
LABOUR_COLUMN_NUMBER = 7;   // Enter the number of the column with the total amount charged here
COMPLETED_COLUMN_NUMBER = 10   // Enter the number of the column with the inspection

function COMPLETED(e){
  let range = e.range,
      sheet1 = range.getSheet();

  if (sheet1.getName() == SHEET_TO_WORK_ON && range.columnStart == STATUS_COLUMN_NUMBER && range.rowStart > 1 && e.value == 'Completed'){
      range.offset(0,COMPLETED_COLUMN_NUMBER - STATUS_COLUMN_NUMBER).setValue(Browser.inputBox('Tech ', 'Fill in the ID for the to who inspected the repair', Browser.Buttons.OK_CANCEL))
  }
}

Body:
I understand that you want to upgrade your code so it opens the input dialogue only if the target cell is empty. If my understanding of the scenario is correct, then there is one minor modification that you can script to upgrade your project. You only have to take the Range object in the script and use the getValue method to check if it is empty. In the following example I created the variable targetCellData to save the cell content. Then, if the cell is empty (meaning the content equals to '') the code runs the input dialogue.

function onEdit(e) {
  COMPLETED(e);
}

SHEET_TO_WORK_ON = 'Scoresby';
STATUS_COLUMN_NUMBER = 4;
LABOUR_COLUMN_NUMBER = 7;
COMPLETED_COLUMN_NUMBER = 10;

function COMPLETED(e) {
  let range = e.range,
    sheet1 = range.getSheet();

  if (sheet1.getName() == SHEET_TO_WORK_ON && range.columnStart ==
    STATUS_COLUMN_NUMBER && range.rowStart > 1 && e.value == 'Completed') {
    var targetCellData = range.offset(0, COMPLETED_COLUMN_NUMBER -
      STATUS_COLUMN_NUMBER).getValue();

    if (targetCellData == '') {
      range.offset(0, COMPLETED_COLUMN_NUMBER - STATUS_COLUMN_NUMBER).setValue(
        Browser.inputBox('Tech ',
          'Fill in the ID for the to who inspected the repair', Browser
          .Buttons.OK_CANCEL));
    }
  }
}

Please test this approach and let me know if it helps.


问:
How to get Contact Information and Alternate Contact in AWS/Billing using boto3?
I am working on a project in which through the boto3 SDK I need to obtain the information from Alternate Contacts and Contact Information.

Is there a method that do this with boto3? Thanks!

答:
The current version of boto provides an method for requesting the Alternate Contact information:</p>
```<code>import boto3

CONTACT_TYPES = ['BILLING','OPERATIONS','SECURITY']

client = boto.client('account')

alternate_contact = client.get_alternate_contact(
    AccountId=event['AccountId'],
    AlternateContactType=CONTACT_TYPES[0])

</code>```

Body:
The current version of boto provides an method for requesting the Alternate Contact information:

import boto3

CONTACT_TYPES = ['BILLING','OPERATIONS','SECURITY']

client = boto.client('account')

alternate_contact = client.get_alternate_contact(
    AccountId=event['AccountId'],
    AlternateContactType=CONTACT_TYPES[0])


问:
How to bind data from a List<class> to Picker element in Xamarin
I have a list (List<Customer> l_Customer) that gets data from an API. <Customer> class includes fullname that is of string value. How can i get only the full names from that list and display them on the Picker's dropdown list?

答:
there is an example to do exactly this in the docs

```<code><Picker Title="Select a customer"
    ItemsSource="{Binding l_Customer}"
    ItemDisplayBinding="{Binding fullname}" />
</code>```

or in code

```<code>var picker = new Picker { Title = "Select a Customer" };
picker.SetBinding(Picker.ItemsSourceProperty, "l_Customer");
picker.ItemDisplayBinding = new Binding("fullname");
</code>```

Body:
there is an example to do exactly this in the docs

<Picker Title="Select a customer"
    ItemsSource="{Binding l_Customer}"
    ItemDisplayBinding="{Binding fullname}" />

or in code

var picker = new Picker { Title = "Select a Customer" };
picker.SetBinding(Picker.ItemsSourceProperty, "l_Customer");
picker.ItemDisplayBinding = new Binding("fullname");


问:
Unable to debug with F11 with VSCODE (toggled Fullscreen)?
It seems that F11 for toggle fullscreen is overwrite F11 "Step into" keyboard shortcut while debugging. How it can be fixed?

答:
Go to: System Preferences -> Keyboard -> Shortcuts (tab) -> Mission Control (list on the left side) -> Show Desktop (checkbox).
There are 2 options:

Disable option (uncheck the box),

Change the key (double click on the key, and then press the new key like F12 or whatever you prefer).
(Tested on Monterey 12.1 and VSCode)


问:
Play multiple tracks <audio>
I'm trying to use the <audio> tag, and I want to have as many tracks playing as I add. But in the end, the very first track plays in a circle. How can this be fixed?

```<code><audio id="audio" preload="" autoplay="" loop="">
  <source type="audio/mp3" src="music/mus1.mp3">
  <source type="audio/mp3" src="music/mus.mp3">
</audio>
</code>```
```<code><script type="text/javascript">
var audio = document.getElementById("audio");

function pVid() {
    audio.paused ? audio.play() : audio.pause();
}
</script>
</code>```

答:
I hope adding below sample code will do the work :

```<code>function skipAndplayNext() {
            sounds[current].pause();
            document.getElementById(current + '').classList.remove('paused');
            document.getElementById(current + '').classList.remove('playing');
            current++;
            if (current > (sounds.length - 1)) {
                current = 0
            }
            sounds[current].play();
            document.getElementById(current + '').classList.add('playing');
        }
</code>```

Title: Play multiple tracks <audio>

Body:
I'm trying to use the <audio> tag, and I want to have as many tracks playing as I add. But in the end, the very first track plays in a circle. How can this be fixed?

<audio id="audio" preload="" autoplay="" loop="">
  <source type="audio/mp3" src="music/mus1.mp3">
  <source type="audio/mp3" src="music/mus.mp3">
</audio>

Body:
I hope adding below sample code will do the work :

function skipAndplayNext() {
            sounds[current].pause();
            document.getElementById(current + '').classList.remove('paused');
            document.getElementById(current + '').classList.remove('playing');
            current++;
            if (current > (sounds.length - 1)) {
                current = 0
            }
            sounds[current].play();
            document.getElementById(current + '').classList.add('playing');
        }


问:
SQL Server 2017 Triggers dont respect database design and null value conditions inside it fail
I have two key problems with triggers in SQL Server 2017. They are:

They don't respect database design.

NULL value conditions in the trigger fail.

Let me explain:

1. They don't respect database design:
Lets say I have tables and a view like below and I am trying to create a trigger which would insert into multiple tables based on what has been inserted into the view. (taken and edited from this post - Instead of trigger to update view with multiple tables)

```<code>
CREATE TABLE persons
(personid  int,
 firstname varchar(32) default 'Charles',
 lastname  varchar(32));

CREATE TABLE employees
(employeeid int,
 personid   int,
 title      varchar(32));

CREATE VIEW vwEmployees AS
SELECT p.personid, employeeid, firstname, lastname, title
  FROM employees e JOIN persons p
    ON e.personid = p.personid;

CREATE TRIGGER tgEmployeesInsert ON vwEmployees
INSTEAD OF INSERT AS
BEGIN
  INSERT INTO persons (personid, firstname, lastname)
  SELECT personid, firstname, lastname
    FROM INSERTED

  INSERT INTO employees (employeeid, personid, title)
  SELECT employeeid, personid, title
    FROM INSERTED
END;

INSERT INTO vwEmployees (personid, employeeid, lastname, title)
VALUES(1, 1, 'Doe', 'SQL Developer');

</code>```

If I use the select statement like below:

```<code>select * from persons
</code>```

This will fetch me results as below:

personid
firstname
lastname

1

Doe

I am not sure if you noticed above but the default for firstname should have been 'Charles' as mentioned in the create table above.

2. NULL value conditions in the trigger fail.

Here, I used the same method as above for creating an instead of trigger for updating a view with multiple tables.
Lets say I have a trigger like below:

```<code>CREATE or ALTER TRIGGER oc.trg_Update_Tracker ON oc.BP_Tracker
INSTEAD OF Update AS
BEGIN
       Begin Try
       SET NOCOUNT ON
       Begin
            if update(Partner_ID) or update(Partner_Name) or update(LEI)
            Begin
                Update oc.Business_Partner
                SET Partner_ID=ins.Partner_ID, Partner_Name=ins.Partner_Name, LEI=ins.LEI, User_Changed = ins.User_Changed
                from oc.Business_Partner bp, inserted as ins, deleted as del
                where bp.Partner_ID = del.Partner_ID and bp.Partner_Name = del.Partner_Name
            End
.........
</code>```

Lets say the bp.Partner_Name is null and del.Partner_Name is null. In this case, the update statement fails because the condition bp.Partner_Name = del.Partner_Name fails in the trigger. If the same update statement were to be passed outside the trigger on the table - that works. Also, if I remove the condition bp.Partner_Name = del.Partner_Name, the trigger update would work.

Would really appreciate if someone could explain me what's going on.

答:
I would put this in a comment, but there no way it's fit:

TL;DR: The problem isn't the trigger, it's your understanding that's flawed.

1: They do respect database design

The DEFAULT value was respected, you just told SQL Server to not use it. Let's look at your INSERT statement:

  INSERT INTO persons (personid, firstname, lastname)
  SELECT personid, firstname, lastname
    FROM INSERTED
```
<p>So you are inserted the values <code>personid</code>, <code>firstname</code> and <code>lastname</code> from the <code>inserted</code> pseudo table into the table <code>persons</code>. These columns have the value <code>1</code>, <code>NULL</code>, and <code>'Doe'</code> respectively. You have, in your <code>INSERT</code> statement specifically stated you want to <code>INSERT</code> the value of <code>firstname</code> into the column of the same name, and that value is <code>NULL</code>, so <code>NULL</code> was inserted.</p>
<p>If you wanted the default value, you should have omitted <code>firstname</code> in the <code>INSERT</code> entirely, or stated <code>DEFAULT</code> in the <code>SELECT</code>:</p>
<pre class="lang-sql prettyprint-override"><code>  INSERT INTO persons (personid, lastname)
  SELECT personid, lastname
    FROM INSERTED;

  INSERT INTO persons (personid, firstname, lastname)
  SELECT personid, DEFAULT, lastname
    FROM INSERTED;
</code>```

A DEFAULT constraint is only used when the column is omitted from the SELECT or the DEFAULT option is passed. NULL is still a value, just an unknown one, and explicitly inserting NULL into a column does not result in the DEFAULT value to be used.

2: "NULL value conditions in the trigger fail"

Firstly, I need to address your query; it's not 1989 any more. It's 2022, and the ANSI-92 explicit join syntax has been around for 30 years and it is long past time you adopted it.

I cannot, however, test this trigger has the DML and DDL is omitted for the objects it references, and it's own DDL is incomplete. As questions should be limited to 1 question though, then fixing that trigger is for a separate new question.

Body:
I have two key problems with triggers in SQL Server 2017. They are:

They don't respect database design.

NULL value conditions in the trigger fail.

Let me explain:

1. They don't respect database design:
Lets say I have tables and a view like below and I am trying to create a trigger which would insert into multiple tables based on what has been inserted into the view. (taken and edited from this post - Instead of trigger to update view with multiple tables)

CREATE TABLE persons
(personid  int,
 firstname varchar(32) default 'Charles',
 lastname  varchar(32));

CREATE TABLE employees
(employeeid int,
 personid   int,
 title      varchar(32));

CREATE VIEW vwEmployees AS
SELECT p.personid, employeeid, firstname, lastname, title
  FROM employees e JOIN persons p
    ON e.personid = p.personid;

CREATE TRIGGER tgEmployeesInsert ON vwEmployees
INSTEAD OF INSERT AS
BEGIN
  INSERT INTO persons (personid, firstname, lastname)
  SELECT personid, firstname, lastname
    FROM INSERTED

  INSERT INTO employees (employeeid, personid, title)
  SELECT employeeid, personid, title
    FROM INSERTED
END;

INSERT INTO vwEmployees (personid, employeeid, lastname, title)
VALUES(1, 1, 'Doe', 'SQL Developer');

If I use the select statement like below:

select * from persons

This will fetch me results as below:

personid
firstname
lastname

1

Doe

I am not sure if you noticed above but the default for firstname should have been 'Charles' as mentioned in the create table above.

2. NULL value conditions in the trigger fail.

Here, I used the same method as above for creating an instead of trigger for updating a view with multiple tables.
Lets say I have a trigger like below:

CREATE or ALTER TRIGGER oc.trg_Update_Tracker ON oc.BP_Tracker
INSTEAD OF Update AS
BEGIN
       Begin Try
       SET NOCOUNT ON
       Begin
            if update(Partner_ID) or update(Partner_Name) or update(LEI)
            Begin
                Update oc.Business_Partner
                SET Partner_ID=ins.Partner_ID, Partner_Name=ins.Partner_Name, LEI=ins.LEI, User_Changed = ins.User_Changed
                from oc.Business_Partner bp, inserted as ins, deleted as del
                where bp.Partner_ID = del.Partner_ID and bp.Partner_Name = del.Partner_Name
            End
.........

Lets say the bp.Partner_Name is null and del.Partner_Name is null. In this case, the update statement fails because the condition bp.Partner_Name = del.Partner_Name fails in the trigger. If the same update statement were to be passed outside the trigger on the table - that works. Also, if I remove the condition bp.Partner_Name = del.Partner_Name, the trigger update would work.

Would really appreciate if someone could explain me what's going on.

Body:
I would put this in a comment, but there no way it's fit:

TL;DR: The problem isn't the trigger, it's your understanding that's flawed.

1: They do respect database design

The DEFAULT value was respected, you just told SQL Server to not use it. Let's look at your INSERT statement:

  INSERT INTO persons (personid, firstname, lastname)
  SELECT personid, firstname, lastname
    FROM INSERTED

So you are inserted the values personid, firstname and lastname from the inserted pseudo table into the table persons. These columns have the value 1, NULL, and 'Doe' respectively. You have, in your INSERT statement specifically stated you want to INSERT the value of firstname into the column of the same name, and that value is NULL, so NULL was inserted.

If you wanted the default value, you should have omitted firstname in the INSERT entirely, or stated DEFAULT in the SELECT:

  INSERT INTO persons (personid, lastname)
  SELECT personid, lastname
    FROM INSERTED;

  INSERT INTO persons (personid, firstname, lastname)
  SELECT personid, DEFAULT, lastname
    FROM INSERTED;

A DEFAULT constraint is only used when the column is omitted from the SELECT or the DEFAULT option is passed. NULL is still a value, just an unknown one, and explicitly inserting NULL into a column does not result in the DEFAULT value to be used.

2: "NULL value conditions in the trigger fail"

Firstly, I need to address your query; it's not 1989 any more. It's 2022, and the ANSI-92 explicit join syntax has been around for 30 years and it is long past time you adopted it.

I cannot, however, test this trigger has the DML and DDL is omitted for the objects it references, and it's own DDL is incomplete. As questions should be limited to 1 question though, then fixing that trigger is for a separate new question.


问:
How to Get sum of transactions in Recursive query
I have two Tables, the first table have a parent-child relationship with itself, and the second table stores the transactions for the first table

First Table

Note: parent_id is in relationship with Nominal

second table

Note: first_level_id is in relationship with the id of the first table

in the model, I Created a relationship like below

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class first_level extends Model
{
    use HasFactory;
    use LogsActivity;

    public function children()
    {
        return $this->hasMany(first_level::class, 'parent_id', 'Nominal')->with(['children']);
    }

    public function transactions()
    {
        return $this->hasMany(second_level::class, 'first_level_id', 'id');
    }
}
</code>```

Now in the controller when I want to get all the Children and their transactions I can only get the children without their transactions. So how do get all the children with the sum of their transactions?

My controller:

```<code>    public function getGeneralLedger(Request $request)
    {
     $items = first_level::with('children')->with('transactions')->where('parent_id', 0)->get();
     return response()->json(['data' => $items]);
    }
</code>```

答:
I fixed my problem by modifying my model

My model

```<code>    public function children()
    {
        return $this->hasMany(first_level::class, 'parent_id', 'Nominal')
            ->with('transactions')
            ->with('children')
            ->withsum('transactions', 'debit')
            ->withsum('transactions', 'credit');
    }

    public function transactions()
    {
        return $this->hasMany(second_level::class, 'first_level_id', 'id');
    }
</code>```

My Controller

```<code>        $items = first_level::with('children')
            ->where('parent_id', 0)
            ->get();
</code>```

Body:
I have two Tables, the first table have a parent-child relationship with itself, and the second table stores the transactions for the first table

First Table

Note: parent_id is in relationship with Nominal

second table

Note: first_level_id is in relationship with the id of the first table

in the model, I Created a relationship like below

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class first_level extends Model
{
    use HasFactory;
    use LogsActivity;

    public function children()
    {
        return $this->hasMany(first_level::class, 'parent_id', 'Nominal')->with(['children']);
    }

    public function transactions()
    {
        return $this->hasMany(second_level::class, 'first_level_id', 'id');
    }
}

Now in the controller when I want to get all the Children and their transactions I can only get the children without their transactions. So how do get all the children with the sum of their transactions?

My controller:

    public function getGeneralLedger(Request $request)
    {
     $items = first_level::with('children')->with('transactions')->where('parent_id', 0)->get();
     return response()->json(['data' => $items]);
    }

Body:
I fixed my problem by modifying my model

My model

    public function children()
    {
        return $this->hasMany(first_level::class, 'parent_id', 'Nominal')
            ->with('transactions')
            ->with('children')
            ->withsum('transactions', 'debit')
            ->withsum('transactions', 'credit');
    }

    public function transactions()
    {
        return $this->hasMany(second_level::class, 'first_level_id', 'id');
    }

My Controller

        $items = first_level::with('children')
            ->where('parent_id', 0)
            ->get();


问:
Objects are not valid as a React child React Native
I'm getting Render Error
Objects are not valid as a React child (found:object with keys {name, lati, long}). If you meant to render a collection of children, use an array instead.

I need to send the prop "name" from const mesta using Tab.Screen children, but keep getting the error.

My code:

MainContainer.js

```<code>import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {name: 'Praha', lati: '', long: ''},
  {name: 'České Budějovice', lati: '', long: ''},
  {name: 'Plzeň', lati: '', long: ''},
  {name: 'Karlovy Vary', lati: '', long: ''},
  {name: 'Ústí nad Labem', lati: '', long: ''},
  {name: 'Liberec', lati: '', long: ''},
  {name: 'Hradec Králové', lati: '', long: ''},
  {name: 'Pardubice', lati: '', long: ''},
  {name: 'Jihlava', lati: '', long: ''},
  {name: 'Brno', lati: '', long: ''},
  {name: 'Olomouc', lati: '', long: ''},
  {name: 'Ostrava', lati: '', long: ''},
  {name: 'Zlín', lati: '', long: ''},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary mesta={mesta}/>}/>
        {/* <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/> */}

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;
</code>```

Primary.js

```<code>import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';

var nazvy = ['Praha','České Budějovice','Plzeň','Karlovy Vary','Ústí nad Labem','Liberec','Hradec Králové','Pardubice','Jihlava','Brno','Olomouc','Ostrava','Zlín',]

export default function Primary(props)
{
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.mesta.map(itemz => (
                    <Text
                    style={styles.card2}
                    //onPress={() => navigation.navigate('Mapa')}
                    >
                        {itemz}
                    </Text>
                ))}
                    {nazvy.map(item => (
                        <Text
                        style={styles.card}
                        //onPress={() => navigation.navigate('Mapa')}
                        >
                            {item}
                        </Text>
                    ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });
</code>```

答:
You're rendering an object inside TextView. Refactor your code as below:

import * as React from "react";
import { StyleSheet, ScrollView, View, Text, Image } from "react-native";

var nazvy = [
  "Praha",
  "České Budějovice",
  "Plzeň",
  "Karlovy Vary",
  "Ústí nad Labem",
  "Liberec",
  "Hradec Králové",
  "Pardubice",
  "Jihlava",
  "Brno",
  "Olomouc",
  "Ostrava",
  "Zlín",
];

export default function Primary(props) {
  return (
    <ScrollView
      style={{
        flex: 1,
      }}
    >
      <View>
        {props.mesta.map((itemz) => (
          <>
            <Text
              style={styles.card2}
              //onPress={() => navigation.navigate('Mapa')}
            >
              {itemz.name}
            </Text>

            <Text
              style={styles.card2}
              //onPress={() => navigation.navigate('Mapa')}
            >
              {itemz.lati}
            </Text>

            <Text
              style={styles.card2}
              //onPress={() => navigation.navigate('Mapa')}
            >
              {itemz.long}
            </Text>
          </>
        ))}
        {nazvy.map((item) => (
          <Text
            style={styles.card}
            //onPress={() => navigation.navigate('Mapa')}
          >
            {item}
          </Text>
        ))}
      </View>
    </ScrollView>
  );
}

```

Body:
I'm getting Render Error
Objects are not valid as a React child (found:object with keys {name, lati, long}). If you meant to render a collection of children, use an array instead.

I need to send the prop "name" from const mesta using Tab.Screen children, but keep getting the error.

My code:

MainContainer.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {name: 'Praha', lati: '', long: ''},
  {name: 'České Budějovice', lati: '', long: ''},
  {name: 'Plzeň', lati: '', long: ''},
  {name: 'Karlovy Vary', lati: '', long: ''},
  {name: 'Ústí nad Labem', lati: '', long: ''},
  {name: 'Liberec', lati: '', long: ''},
  {name: 'Hradec Králové', lati: '', long: ''},
  {name: 'Pardubice', lati: '', long: ''},
  {name: 'Jihlava', lati: '', long: ''},
  {name: 'Brno', lati: '', long: ''},
  {name: 'Olomouc', lati: '', long: ''},
  {name: 'Ostrava', lati: '', long: ''},
  {name: 'Zlín', lati: '', long: ''},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary mesta={mesta}/>}/>
        {/* <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/> */}

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;

Primary.js

import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';

var nazvy = ['Praha','České Budějovice','Plzeň','Karlovy Vary','Ústí nad Labem','Liberec','Hradec Králové','Pardubice','Jihlava','Brno','Olomouc','Ostrava','Zlín',]

export default function Primary(props)
{
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.mesta.map(itemz => (
                    <Text
                    style={styles.card2}
                    //onPress={() => navigation.navigate('Mapa')}
                    >
                        {itemz}
                    </Text>
                ))}
                    {nazvy.map(item => (
                        <Text
                        style={styles.card}
                        //onPress={() => navigation.navigate('Mapa')}
                        >
                            {item}
                        </Text>
                    ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });