问:
Get index of searchresult in array
I have the following code:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     //HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
     //EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
     console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}```

How to get the index of the name in this array?

答:
One solution is by getting the element through .find(), and then use the .indexOf(). for example:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
    var found = member_data_list.find(row => row[0] === "franz")
    var index = member_data_list.indexOf(found)

    // if the element is exists then index's value will be greater than -1
    if (index > -1) {
      console.log("NAME IS IN ARRAY AT INDEX " + index)
    }
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}```

Title: Get index of searchresult in array

Body:
I have the following code:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     //HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
     //EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
     console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}

How to get the index of the name in this array?


来源: stackexchange

问:
How to Get first date and last date from given month in java?
We will pass month information in yyyyMM format.From that given input how i will get FirstDate and LastDate of that month?</p>

```<code>Input:-202002

OutPut Should be:-

First Date:- 2020-02-01,
Last Date:- 2020-02-29

DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
Date date = new Date();
System.out.println("First Date:- "+dateFormat.format(date));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
Date previousmonth = calendar.getTime();
System.out.println("LastDate:-"+dateFormat.format(previousmonth).toString());
</code>```

答:
try this, you can do it simply with LocalDate

String date = "202002";

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                .appendPattern("yyyyMM")
                                .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                                .toFormatter();

LocalDate firstDay = LocalDate.parse(date, formatter);
LocalDate lastDay = firstDay.withDayOfMonth(firstDay.getMonth().length(firstDay.isLeapYear()));
```

ContentLicense: CC BY-SA 4.0

Body:
We will pass month information in yyyyMM format.From that given input how i will get FirstDate and LastDate of that month?

Input:-202002

OutPut Should be:-

First Date:- 2020-02-01,
Last Date:- 2020-02-29

DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
Date date = new Date();
System.out.println("First Date:- "+dateFormat.format(date));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
Date previousmonth = calendar.getTime();
System.out.println("LastDate:-"+dateFormat.format(previousmonth).toString());


问:
Display laravel Pagination links twice in a page
I have implemented a laravel pagination in one of my project where pagination is working like a charm.

I have a requirement to display a pagination links on top of the table as well as the bottom of the table.
Like this

```<code>{!! $entries->render() !!}
<table class="table table-responsive" id="entries-table">
    <thead>
        <tr>
                <th>ID</th>
                <th>Advisor name</th>
        </tr>
    </thead>
    <tbody>
    @forelse($entries as $entries)
        <tr>
            <td> {{ $entries->id }} </td>
            <td> {{ $entries->name }} </td>
        </tr>
    @empty
    <tr>
        <td>
            <p>No record found.</p>
        </td>
    </tr>
    @endforelse
    </tbody>
</table>
{!! $entries->render() !!}
</code>```

When I try to use {!! $entries->render() !!} one more time in the bottom of the table or anywhere in a same page, it throws me the below error.

ErrorException (E_ERROR) Call to undefined method
  App\Models\Entries::render()

here is my Controller code

```<code>public function index(Request $request)
    {
        $entries = Entries::orderBy('id', 'DESC')->paginate(15);

        return view('entries.index')
            ->with('entries', $entries);
    }
</code>```

here I am dumping the varialbe $entries in controller using dd($entries) and this is what I am getting.

```<code>LengthAwarePaginator {#425 ▼
  #total: 215
  #lastPage: 15
  #items: Collection {#436 ▼
    #items: array:15 [▼
      0 => entries {#437 ▶}
      1 => entries {#438 ▶}
      2 => entries {#439 ▶}
      3 => entries {#440 ▶}
      4 => entries {#441 ▶}
      5 => entries {#442 ▶}
      6 => entries {#443 ▶}
      7 => entries {#444 ▶}
      8 => entries {#445 ▶}
      9 => entries {#446 ▶}
      10 => entries {#447 ▶}
      11 => entries {#448 ▶}
      12 => entries {#449 ▶}
      13 => entries {#450 ▶}
      14 => entries {#451 ▶}
    ]
  }
  #perPage: 15
  #currentPage: 1
  #path: "https://samplesite.com/entries/11"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▼
    "path" => "https://samplesite.com/entries/11"
    "pageName" => "page"
  ]
}
</code>```

Check this Video i am sharing with you for better idea

答:
You are overriding $entries collection with collection item in @forelse.

```<code>@forelse($entries as $entries)
    <tr>
        <td> {{ $entries->id }} </td>
        <td> {{ $entries->name }} </td>
    </tr>
@empty
</code>```

Change $entries to $entry:

```<code>@forelse($entries as $entry)
    <tr>
        <td> {{ $entry->id }} </td>
        <td> {{ $entry->name }} </td>
    </tr>
@empty
</code>```

Body:
I have implemented a laravel pagination in one of my project where pagination is working like a charm.

I have a requirement to display a pagination links on top of the table as well as the bottom of the table.
Like this

{!! $entries->render() !!}

                ID
                Advisor name

    @forelse($entries as $entries)

             {{ $entries->id }}
             {{ $entries->name }}

    @empty

No record found.

    @endforelse

{!! $entries->render() !!}

When I try to use {!! $entries->render() !!} one more time in the bottom of the table or anywhere in a same page, it throws me the below error.

ErrorException (E_ERROR) Call to undefined method
  App\Models\Entries::render()

here is my Controller code

public function index(Request $request)
    {
        $entries = Entries::orderBy('id', 'DESC')->paginate(15);

        return view('entries.index')
            ->with('entries', $entries);
    }

here I am dumping the varialbe $entries in controller using dd($entries) and this is what I am getting.

LengthAwarePaginator {#425 ▼
  #total: 215
  #lastPage: 15
  #items: Collection {#436 ▼
    #items: array:15 [▼
      0 => entries {#437 ▶}
      1 => entries {#438 ▶}
      2 => entries {#439 ▶}
      3 => entries {#440 ▶}
      4 => entries {#441 ▶}
      5 => entries {#442 ▶}
      6 => entries {#443 ▶}
      7 => entries {#444 ▶}
      8 => entries {#445 ▶}
      9 => entries {#446 ▶}
      10 => entries {#447 ▶}
      11 => entries {#448 ▶}
      12 => entries {#449 ▶}
      13 => entries {#450 ▶}
      14 => entries {#451 ▶}
    ]
  }
  #perPage: 15
  #currentPage: 1
  #path: "https://samplesite.com/entries/11"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▼
    "path" => "https://samplesite.com/entries/11"
    "pageName" => "page"
  ]
}

Check this Video i am sharing with you for better idea

Body:
You are overriding $entries collection with collection item in @forelse.

@forelse($entries as $entries)
    <tr>
        <td> {{ $entries->id }} </td>
        <td> {{ $entries->name }} </td>
    </tr>
@empty

Change $entries to $entry:

@forelse($entries as $entry)
    <tr>
        <td> {{ $entry->id }} </td>
        <td> {{ $entry->name }} </td>
    </tr>
@empty


问:
Pandas: create new column containing the corresponding value of the maximum in another column by group
I want to create a new column containing the corresponding value of the maximum in another column by group. This is best explained by example:

```<code>data = {'group':['g1', 'g1', 'g1', 'g1', 'g1', 'g1', 'g2', 'g2', 'g2', 'g2', 'g2'],
                    'A':[3, 1, 8, 2, 6, -1, 0, 13, -4, 0, 1],
                    'B':[5, 2, 3, 7, 11, -1, 4,-1, 1, 0, 2]}
df = pd.DataFrame(data)
df
</code>```

The following solution works as a shortcut, but I have a feeling that there is a better way to do it:

```<code>df.loc[:, 'Amax'] = df.loc[df.groupby('group')['B'].idxmax(), 'A']
df.loc[:, 'Amax'] = df.groupby('group')['Amax'].transform('median')

   group   A   B  Amax
0     g1   3   5   6.0
1     g1   1   2   6.0
2     g1   8   3   6.0
3     g1   2   7   6.0
4     g1   6  11   6.0
5     g1  -1  -1   6.0
6     g2   0   4   0.0
7     g2  13  -1   0.0
8     g2  -4   1   0.0
9     g2   0   0   0.0
10    g2   1   2   0.0
</code>```

Body:
I want to create a new column containing the corresponding value of the maximum in another column by group. This is best explained by example:

data = {'group':['g1', 'g1', 'g1', 'g1', 'g1', 'g1', 'g2', 'g2', 'g2', 'g2', 'g2'],
                    'A':[3, 1, 8, 2, 6, -1, 0, 13, -4, 0, 1],
                    'B':[5, 2, 3, 7, 11, -1, 4,-1, 1, 0, 2]}
df = pd.DataFrame(data)
df

The following solution works as a shortcut, but I have a feeling that there is a better way to do it:

df.loc[:, 'Amax'] = df.loc[df.groupby('group')['B'].idxmax(), 'A']
df.loc[:, 'Amax'] = df.groupby('group')['Amax'].transform('median')

   group   A   B  Amax
0     g1   3   5   6.0
1     g1   1   2   6.0
2     g1   8   3   6.0
3     g1   2   7   6.0
4     g1   6  11   6.0
5     g1  -1  -1   6.0
6     g2   0   4   0.0
7     g2  13  -1   0.0
8     g2  -4   1   0.0
9     g2   0   0   0.0
10    g2   1   2   0.0

Body:
Use transform

df['Amax']=df.loc[df.groupby('group')['B'].transform('idxmax'),'A'].values
df
Out[42]:
   group   A   B  Amax
0     g1   3   5     6
1     g1   1   2     6
2     g1   8   3     6
3     g1   2   7     6
4     g1   6  11     6
5     g1  -1  -1     6
6     g2   0   4     0
7     g2  13  -1     0
8     g2  -4   1     0
9     g2   0   0     0
10    g2   1   2     0


答:
Use DataFrame.set_index with GroupBy.transform, but because index is different assign array created by Series.to_numpy:

```<code>df['Amax'] = df.set_index('A').groupby('group')['B'].transform('idxmax').to_numpy()
print(df)
   group   A   B  Amax
0     g1   3   5     6
1     g1   1   2     6
2     g1   8   3     6
3     g1   2   7     6
4     g1   6  11     6
5     g1  -1  -1     6
6     g2   0   4     0
7     g2  13  -1     0
8     g2  -4   1     0
9     g2   0   0     0
10    g2   1   2     0
</code>```

Title: Pandas: create new column containing the corresponding value of the maximum in another column by group

Body:
Use DataFrame.set_index with GroupBy.transform, but because index is different assign array created by Series.to_numpy:

df['Amax'] = df.set_index('A').groupby('group')['B'].transform('idxmax').to_numpy()
print(df)
   group   A   B  Amax
0     g1   3   5     6
1     g1   1   2     6
2     g1   8   3     6
3     g1   2   7     6
4     g1   6  11     6
5     g1  -1  -1     6
6     g2   0   4     0
7     g2  13  -1     0
8     g2  -4   1     0
9     g2   0   0     0
10    g2   1   2     0


问:
Asp.Net AutoEventWireup - what is it doing code wise
I've been digging thru the Page, TemplateControl and Control classes in reflector trying to figure out where AutoEventWireUp property is actually getting used. I've failed miserably.

My understanding of AutoEventWireUp is sketchy but I think it casues event handler methods to be automatically wired up to events?
So I thought I'd see some code where this is happening, but this isn't the case.

Where is AutoEventWireUp actually used under the hood? Can I see the code in reflector?

Thanks in advance!

答:
I was going to write up an explanation but K. Scott Allen has a much better one.

My advice is to avoid AutoEventWireup and either override base "OnEvent" methods or explicitly wire up your own events as this will be faster, less magical, and easier to debug.

OwnerDisplayName: bplus

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Andrew Hare


问:
Escape $ sign using sed
I have a string in file a:

```<code>  my_password: "@$hp!sN0t"
</code>```

I want to escape the dollar sign by adding a backslash before it using sed. The output file b should contain:

```<code>  my_password: "@\$hp!sN0t"
</code>```

I used the command:

```<code>sed 's/\$/\\$/g' a >b
</code>```

And it works well.

But I want to skip escaping the dollar signs that are purposefully used for variables in the file.

For example, ${KEY_FILE_URI} is a variable mentioned inside the same file and its dollar sign should not be escaped.

Otherwise, the command should be able to replace the $ with \$ only if the $ comes inside double-quotes.

The other way is to use a second command to relace the \${ in file b with ${ and write to file c.

```<code>sed 's/\\${/${/g' b >c
</code>```

Is there any simpler method for this? How can I do that correctly?

答:
This might work for you (GNU sed):

```<code>sed 's/\$[^{]/\\&/g' file
</code>```

If the character following a $ is not a {, then insert a \ before the $.

Title: Escape $ sign using sed

Body:
I have a string in file a:

  my_password: "@$hp!sN0t"

I want to escape the dollar sign by adding a backslash before it using sed. The output file b should contain:

  my_password: "@\$hp!sN0t"

I used the command:

sed 's/\$/\\$/g' a >b

And it works well.

But I want to skip escaping the dollar signs that are purposefully used for variables in the file.

For example, ${KEY_FILE_URI} is a variable mentioned inside the same file and its dollar sign should not be escaped.

Otherwise, the command should be able to replace the $ with \$ only if the $ comes inside double-quotes.

The other way is to use a second command to relace the \${ in file b with ${ and write to file c.

sed 's/\\${/${/g' b >c

Is there any simpler method for this? How can I do that correctly?

Body:
This might work for you (GNU sed):

sed 's/\$[^{]/\\&/g' file

If the character following a $ is not a {, then insert a \ before the $.


问:
Associative array response to variables with wpdb get results
I am doing a ajax request which calls a php file which uses wpdb get results.

```<code>$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM t39b_felderkonfig WHERE user_id= %d ",  $user_id), ARRAY_A);
echo json_encode($result);
</code>```

It returns the following array:

```<code>[{"felderkonfig_id":"7","felderkonfig_kategorie":"1","felderkonfig_kategorie2":"1"]
</code>```

How can i now get the array into variables? I tried:

```<code>success: function (response) {
    var kategorie = response['felderkonfig_kategorie'];
    var kategorie2 = response['felderkonfig_kategorie2'];
    var industriesparte = response['felderkonfig_industriesparte'];
</code>```

But that doesnt work.

Solution:
$wpdb get results returns a multidimensional array. To access the array correctly:

```<code>var kategorie = response[0]['felderkonfig_kategorie'];
</code>```

Maybe this helps other wordpress developers.

答:
Value get issue. Hope this help you

var tmp = [{
  "felderkonfig_id": "7",
  "felderkonfig_kategorie": "1",
  "felderkonfig_kategorie2": "1"
}];
console.log(tmp[0]['felderkonfig_kategorie']);```

Body:
I am doing a ajax request which calls a php file which uses wpdb get results.

$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM t39b_felderkonfig WHERE user_id= %d ",  $user_id), ARRAY_A);
echo json_encode($result);

It returns the following array:

[{"felderkonfig_id":"7","felderkonfig_kategorie":"1","felderkonfig_kategorie2":"1"]

How can i now get the array into variables? I tried:

success: function (response) {
    var kategorie = response['felderkonfig_kategorie'];
    var kategorie2 = response['felderkonfig_kategorie2'];
    var industriesparte = response['felderkonfig_industriesparte'];

But that doesnt work.

Solution:
$wpdb get results returns a multidimensional array. To access the array correctly:

var kategorie = response[0]['felderkonfig_kategorie'];

Maybe this helps other wordpress developers.


问:
Push a div to the right
I'm coding a menu in french but I need to move all the buttons (Home, About us...) to the right.

I tried with float: right; but it doesn't work.

Here is my Result :

My Result

The  Home, Informations, etc.. are in a div. It's this div that i want to push right !

My Objective :

My Objective

My Code:

/*

            ==============================
            NAVBAR
            ==============================

            */

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

.logo {
  float: left;
  /*padding: 10px 0;*/
}

nav {
  float: right;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
}

.connection {
  line-height: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="container">

    <h1 class="logo">
      <img src="images/Logo/logo_gp_.png" width="100" alt="Description de l'image">
    </h1>

    <nav>
      <ul id="navbar-ul">
        <li class="navbar-li">Home</li>
        <li class="navbar-li">Informations</li>
        <li class="navbar-li">About us</li>
      </ul>
      <ul class="connection">
        <li>S'inscrire</li>
        <li>Se connecter</li>
      </ul>
    </nav>
  </div>
</header></code>```

Thanks

答:
remove the float: right from your .nav and add float:left from .logo

Now add display:flex to your .logo and for your container add:

```<code>.container{
 justify-content: space-between;
}
</code>```

I have not tested this. Let me know if this is what you wanted.

Title: Push a div to the right

Body:
I'm coding a menu in french but I need to move all the buttons (Home, About us...) to the right.

I tried with float: right; but it doesn't work.

Here is my Result :

My Result

The  Home, Informations, etc.. are in a div. It's this div that i want to push right !

My Objective :

My Objective

My Code:

/*

            ==============================
            NAVBAR
            ==============================

            */

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

.logo {
  float: left;
  /*padding: 10px 0;*/
}

nav {
  float: right;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
}

.connection {
  line-height: 2;
}

Home

Informations

About us

S'inscrire

Se connecter

Thanks

Body:
remove the float: right from your .nav and add float:left from .logo

Now add display:flex to your .logo and for your container add:

.container{
 justify-content: space-between;
}

I have not tested this. Let me know if this is what you wanted.


问:
Is there best practice to obtain elements/variables from collection based on different conditions
Or in general how to filter some elements from collection based on different and complex conditions in single pass

Let's say we have collection of elements

```<code>var cats = new List<Cat>{ new Cat("Fluffy"), new Cat("Meowista"), new Cat("Scratchy")};
</code>```

And somewhere we use this collection

```<code>public CatFightResult MarchBoxing(List<Cat> cats, string redCatName, string blueCatName)
{
    var redCat = cats.First(cat => cat.Name == redCatName);
    var blueCat = cats.First(cat => cat.Name == blueCatName);
    var redValue = redCat.FightValue();
    var blueValue = blueCat.FightValue();
    if (Cat.FightValuesEqualWithEpsilon(redValue, blueValue))
        return new CatFightResult{IsDraw: true};
    return new CatFightResult{Winner: redValue > blueValue ? redCat : blueCat};
}
</code>```

Question: Is there a nice way to obtain multiple variables from collection based on some condition(s)?
The question probably requires some sort of uniqueness in collection, let's first assume there is some (i.e. HashSet/Dictionary)

AND preferably:

SINGLE pass/cycle on collection (the most important reason of question, as you can see there are 2 filter operations in above method)

oneliner or like that, with readability, and the shorter the better

generic way (IEnumerable<T> I think, or ICollection<T>)

typos error-prone and changes/additions safe (minimal use of actual conditions in code, preferably checked

null/exception check, because my intention that null is valid result for obtained variable

Would be also cool to have ability to provide custom conditions, which probably could be done via Func parameters, but I didn't tested yet.

There are my attempts, which I've posted in my repo https://github.com/phomm/TreeBalancer/blob/master/TreeTraverse/Program.cs

Here is the adaptation to example with Cats:

```<code>public CatFightResult MarchBoxing(List<Cat> cats, string redCatName, string blueCatName)
{
    var redCat = null;
    var blueCat = null;

    //1 kinda oneliner, but hard to read and not errorprone
    foreach (var c in cats) _ = c.Name == redCatName ? redCat = n : n.Name == blueCatName ? blueCat = n : null;

    //2 very good try, because errorprone and easy to read (and find mistake in assignment), but not oneliner and not elegant (but fast) redundant fetching and not single pass at all, up to O(N*N) with FirstOrDefault
    var filter = new [] { redCatName, blueCatName }.ToDictionary(x => x.Key, x => cats.FirstOrDefault(n => n.Name == x.Key));
    redCat = filter[redCatName];
    blueCat = filter[blueCatName];

    //3 with readability and ckecks for mistakenly written searching keys (dictionary internal dupe key check) , but not oneliner and not actualy single pass
    var dic = new Dictionary<int, Func<Cat, Cat>> { { redCatName, n => redCat = n }, { blueCatName, n => blueCat = n } };
    cats.All(n => dic.TryGetValue(n.Name, out var func) ? func(n) is null : true);

    //4 best approach, BUT not generic (ofc one can write simple generic IEnumerable<T> ForEach extension method, and it would be strong candidate to win)
    cats.ForEach(n => _ = n.Name == redCatName ? redCat = n : n.Name == blueCatName ? blueCat = n : null);

    //5 nice approach, but not single pass, enumerating collection twice
    cats.Zip(cats, (n, s) => n.Name == redCatName ? redCat = n : n.Name == blueCatName ? blueCat = n : null);

    //6 the one I prefer best, however it's arguable due to breaking functional approach of Linq, causing side effects
    cats.All(n => (n.Name == redCatName ? redCat = n : n.Name == blueCatName ? blueCat = n : null) is null);
}
</code>```

All the options with ternary op are not extensible easily and relatively error-prone, but are quite short and Linq-ish, they also rely (some trade-off with confusion) on not returning/using actual results of ternary (with discard "_" or "is null" as bool). I think the approach with Dictionary of Funcs is a good candidate to implement custom conditions, just bake-in them with variables.

Thank you, looking forward your solutions ! :)

答:
I'm not sure if it's possible with Linq out of the box but if writing a custom extension once is an option for you, retrieving some values from a collection with arbitrary number of conditions may later be put in pretty concise manner.

For example, you may write something like

```<code>var (redCat, blueCat) = cats.FindFirsts(
    x => x.Name == redCatName,
    x => x.Name == blueCatName);
</code>```

If you introduce the FindFirsts() extension as follows:

```<code>public static class FindExtensions
{
    public static T[] FindFirsts<T>(this IEnumerable<T> collection,
        params Func<T, bool>[] conditions)
    {
        if (conditions.Length == 0)
            return new T[] { };

        var unmatchedConditions = conditions.Length;
        var lookupWork = conditions
            .Select(c => (
                value: default(T),
                found: false,
                cond: c
            ))
            .ToArray();
        foreach (var item in collection)
        {
            for (var i = 0; i < lookupWork.Length; i++)
            {
                if (!lookupWork[i].found && lookupWork[i].cond(item))
                {
                    lookupWork[i].found = true;
                    lookupWork[i].value = item;
                    unmatchedConditions--;
                }
            }
            if (unmatchedConditions <= 0)
                break;
        }
        return lookupWork.Select(x => x.value).ToArray();
    }
}
</code>```

The full demo can be hound here: https://dotnetfiddle.net/QdVJUd

Note: In order to deconstruct the result array (i.e. use var (redCat, blueCat) = ...), you have to define a deconstruction extension. I borrowed some code from this thread to do so.

Body:
Or in general how to filter some elements from collection based on different and complex conditions in single pass

Let's say we have collection of elements

var cats = new List<Cat>{ new Cat("Fluffy"), new Cat("Meowista"), new Cat("Scratchy")};

And somewhere we use this collection

public CatFightResult MarchBoxing(List<Cat> cats, string redCatName, string blueCatName)
{
    var redCat = cats.First(cat => cat.Name == redCatName);
    var blueCat = cats.First(cat => cat.Name == blueCatName);
    var redValue = redCat.FightValue();
    var blueValue = blueCat.FightValue();
    if (Cat.FightValuesEqualWithEpsilon(redValue, blueValue))
        return new CatFightResult{IsDraw: true};
    return new CatFightResult{Winner: redValue > blueValue ? redCat : blueCat};
}

Question: Is there a nice way to obtain multiple variables from collection based on some condition(s)?
The question probably requires some sort of uniqueness in collection, let's first assume there is some (i.e. HashSet/Dictionary)

AND preferably:

SINGLE pass/cycle on collection (the most important reason of question, as you can see there are 2 filter operations in above method)

oneliner or like that, with readability, and the shorter the better

generic way (IEnumerable<T> I think, or ICollection<T>)

typos error-prone and changes/additions safe (minimal use of actual conditions in code, preferably checked

null/exception check, because my intention that null is valid result for obtained variable

Would be also cool to have ability to provide custom conditions, which probably could be done via Func parameters, but I didn't tested yet.

There are my attempts, which I've posted in my repo https://github.com/phomm/TreeBalancer/blob/master/TreeTraverse/Program.cs

Here is the adaptation to example with Cats:

public CatFightResult MarchBoxing(List<Cat> cats, string redCatName, string blueCatName)
{
    var redCat = null;
    var blueCat = null;

    //1 kinda oneliner, but hard to read and not errorprone
    foreach (var c in cats) _ = c.Name == redCatName ? redCat = n : n.Name == blueCatName ? blueCat = n : null;

    //2 very good try, because errorprone and easy to read (and find mistake in assignment), but not oneliner and not elegant (but fast) redundant fetching and not single pass at all, up to O(N*N) with FirstOrDefault
    var filter = new [] { redCatName, blueCatName }.ToDictionary(x => x.Key, x => cats.FirstOrDefault(n => n.Name == x.Key));
    redCat = filter[redCatName];
    blueCat = filter[blueCatName];

    //3 with readability and ckecks for mistakenly written searching keys (dictionary internal dupe key check) , but not oneliner and not actualy single pass
    var dic = new Dictionary<int, Func<Cat, Cat>> { { redCatName, n => redCat = n }, { blueCatName, n => blueCat = n } };
    cats.All(n => dic.TryGetValue(n.Name, out var func) ? func(n) is null : true);

    //4 best approach, BUT not generic (ofc one can write simple generic IEnumerable<T> ForEach extension method, and it would be strong candidate to win)
    cats.ForEach(n => _ = n.Name == redCatName ? redCat = n : n.Name == blueCatName ? blueCat = n : null);

    //5 nice approach, but not single pass, enumerating collection twice
    cats.Zip(cats, (n, s) => n.Name == redCatName ? redCat = n : n.Name == blueCatName ? blueCat = n : null);

    //6 the one I prefer best, however it's arguable due to breaking functional approach of Linq, causing side effects
    cats.All(n => (n.Name == redCatName ? redCat = n : n.Name == blueCatName ? blueCat = n : null) is null);
}

All the options with ternary op are not extensible easily and relatively error-prone, but are quite short and Linq-ish, they also rely (some trade-off with confusion) on not returning/using actual results of ternary (with discard "_" or "is null" as bool). I think the approach with Dictionary of Funcs is a good candidate to implement custom conditions, just bake-in them with variables.

Thank you, looking forward your solutions ! :)

Body:
I'm not sure if it's possible with Linq out of the box but if writing a custom extension once is an option for you, retrieving some values from a collection with arbitrary number of conditions may later be put in pretty concise manner.

For example, you may write something like

var (redCat, blueCat) = cats.FindFirsts(
    x => x.Name == redCatName,
    x => x.Name == blueCatName);

If you introduce the FindFirsts() extension as follows:

public static class FindExtensions
{
    public static T[] FindFirsts<T>(this IEnumerable<T> collection,
        params Func<T, bool>[] conditions)
    {
        if (conditions.Length == 0)
            return new T[] { };

        var unmatchedConditions = conditions.Length;
        var lookupWork = conditions
            .Select(c => (
                value: default(T),
                found: false,
                cond: c
            ))
            .ToArray();
        foreach (var item in collection)
        {
            for (var i = 0; i < lookupWork.Length; i++)
            {
                if (!lookupWork[i].found && lookupWork[i].cond(item))
                {
                    lookupWork[i].found = true;
                    lookupWork[i].value = item;
                    unmatchedConditions--;
                }
            }
            if (unmatchedConditions <= 0)
                break;
        }
        return lookupWork.Select(x => x.value).ToArray();
    }
}

The full demo can be hound here: https://dotnetfiddle.net/QdVJUd

Note: In order to deconstruct the result array (i.e. use var (redCat, blueCat) = ...), you have to define a deconstruction extension. I borrowed some code from this thread to do so.


问:
sql statemement to select picture
hi please see here

in here, u will see "kk+'s photostream (44,986)" 5 other photos in thumbnail. and the current photo is selected with a black border.

my website has similar functions that display photo and 5 other photos from the same user. how can i get these 5 other photos using sql statement where the current photo is in the middle??

what i've thought is to get the row number of the current photo. afterwhich, do another sql query that uses limit to find the other 4 photos which is infront and behind of the current photo. but how do i get the row number of a selected row???

E.g

We have these photos: A, B, C, D, E, F, G, H, I, J

If the current photo is C, then the other 5 photos from the same user will be photo A,B,C,D,E.

If the current photo is F, then the other 5 photos from the same user will be photo D, E, F, G, H

Notice that the current photo is always in the middle of the 5 other photos.
or is there another solution to this??

答:
If the current photo has a numerical ID of say photo_id, you could use the following SQL to retrieve related photos:

```<code>SELECT *
FROM   photo_table
WHERE  photo_table.id > (photo_id-2)
   AND photo_table.id < (photo_id+2)
</code>```

If you are not interested in retrieving the current photo, just add a condition to exclude it, i.e.

```<code>  AND photo_table.id <> photo_id
</code>```

The question is - how to retrieve the id of the selected photo? If you have e.g. the filename of the photo in question, you could query along the following lines:

```<code>SELECT *
FROM   photo_table input_photo
WHERE  input_photo.filename = {some_parameter}
LEFT JOIN photo_table other_photos ON
          other_photos.id > (input_photo.id-2) AND
          other_photos.id < (input_photo.id+2)
</code>```

Hope that helps a little bit.

ContentLicense: CC BY-SA 3.0

Title: sql statemement to select picture

Body:
If the current photo has a numerical ID of say photo_id, you could use the following SQL to retrieve related photos:

SELECT *
FROM   photo_table
WHERE  photo_table.id > (photo_id-2)
   AND photo_table.id < (photo_id+2)

If you are not interested in retrieving the current photo, just add a condition to exclude it, i.e.

  AND photo_table.id <> photo_id

The question is - how to retrieve the id of the selected photo? If you have e.g. the filename of the photo in question, you could query along the following lines:

SELECT *
FROM   photo_table input_photo
WHERE  input_photo.filename = {some_parameter}
LEFT JOIN photo_table other_photos ON
          other_photos.id > (input_photo.id-2) AND
          other_photos.id < (input_photo.id+2)

Hope that helps a little bit.


问:
TextJoin: How to remove duplicate values?
I have the following table of data:

In C2, I then input the following formula =TEXTJOIN(", ",TRUE,IF($B$2:$B$7=$B2,$A$2:$A$7,"")) which returns the following:

However, I want the formula to ignore any duplicates and just return 1, 30

I've had a peruse, and looked a similarly asked questions on here, but i am unable to get anything to work

EDIT

I have partially resolved this with the following code:

=TEXTJOIN(", ",TRUE,IF($B$2:$B$13=$B2,IF(MATCH($A$2:$A$13,$A$2:$A$13,0)=ROW($A$2:$A$13)-ROW($A$2)+1,$A$2:$A$13,""),""))

However, if the ID code changes and an income code, previously populated under a different ID, appears it will just return blank:

Many thanks

Body:
Or, try this array formula (Ctrl+Shift+Enter) instead :

=TEXTJOIN(", ",TRUE,IF($B$2:$B$13=$B2,IF(MATCH($A$2:$A$13&$B$2:$B$13,$A$2:$A$13&$B$2:$B$13,0)=ROW($A$2:$A$13)-ROW($A$2)+1,$A$2:$A$13,""),""))


问:
No data getting to Google Analytics
GA Pro is not working on my website.

Below is the script in my site (GA account ID replaced with XXXXXXXX).

```<code><script type="text/javascript">
var s1 = new SWFObject("/player/player.swf","single","320","260","7");
s1.addParam("allowfullscreen","true");
s1.addParam("allowscriptaccess","always");
s1.addVariable("file","");
s1.addVariable("image","");
s1.addVariable("plugins","gapro-1");
s1.addVariable("gapro.accountid","UA-XXXXXXXX-1");
s1.addVariable("gapro.trackstarts","true");
s1.addVariable("gapro.trackpercentage","true");
s1.addVariable("gapro.tracktime","true");
s1.addVariable("gapro.idstring","||name||");
s1.write("player1");
</script>
</code>```

答:
This doesn't look like the standard GA code, shouldn't it look like this -</p>

```<code><script type="text/javascript">

  var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</code>```

Title: No data getting to Google Analytics

Body:
This doesn't look like the standard GA code, shouldn't it look like this -

<script type="text/javascript">

  var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>


问:
EF Core 3.1 how to automap in Many-to-many relationship
I have constructed a database model in .NET Core Entity framework with a DB first approach. I have several Many-to-many relationships in my database, and they are all represented with a joining table.

Like so:

```<code>public partial class Test1
{
    public Test1()
    {
        Test1_Test2= new HashSet<Test1_Test2>();
    }

    public int Id { get; set; }
    ..

    public virtual ICollection<Test1_Test2> Test1_Test2{ get; set; }
}
</code>```

```<code>public partial class Test2
{
    public Test2()
    {
        Test1_Test2= new HashSet<Test1_Test2>();
    }

    public int Id { get; set; }
    ..

    public virtual ICollection<Test1_Test2> Test1_Test2{ get; set; }
}
</code>```

```<code>public partial class Test1_Test2
{
    public int Test1Id{ get; set; }
    public int Test2Id{ get; set; }

    public virtual Test1 Test1{ get; set; }
    public virtual Test2 Test2{ get; set; }
}
</code>```

EF have constructed a Fluent API that supports this structure, with foreign keys and composite primary key in the joining table.

When I am to add something into this relationship, it is sort of a tedious operation, where I have to do something along the lines of this, in order to correctly populate my joining table:

```<code>_context.Test1.Add(Test1);
_context.Test2.Add(Test2);
Test1_Test2.Test1 = Test1;
Test1_Test2.Test2 = Test2;
_context.Test1_Test2.Add(Test1_Test2);
_context.SaveChanges();
</code>```

From the old EF in .NET Framework, I remember that it was sort of straight forward to do an automapper functionality which would make me able to only do the following:

```<code>Test1.Test2 = Test2;
_context.Test1.Add(Test1);
_context.SaveChanges();
</code>```

This is convenient as EF figures out how populate the joining table automatically. Also this is much more convenient when I have to make requests from these tables.

Therefore, how do I add an "automapper" functionality in .Net Core EF DB first - Is this even supported?

答:
In EF Core 3 Many-to-Many is not supported.  This is from the old docs:

Many-to-many

Many-to-many relationships without an entity class to represent the
join table are not yet supported. However, you can represent a
many-to-many relationship by including an entity class for the join
table and mapping two separate one-to-many relationships.

As a partial workaround you can add a NotMapped property or a function that traverses the two relationships.  You just can't write queries involving a NotMapped property.

But they are there in EF Core 5: Relationships - EF Core - Many-to-many

Body:
I have constructed a database model in .NET Core Entity framework with a DB first approach. I have several Many-to-many relationships in my database, and they are all represented with a joining table.

Like so:

public partial class Test1
{
    public Test1()
    {
        Test1_Test2= new HashSet<Test1_Test2>();
    }

    public int Id { get; set; }
    ..

    public virtual ICollection<Test1_Test2> Test1_Test2{ get; set; }
}

public partial class Test2
{
    public Test2()
    {
        Test1_Test2= new HashSet<Test1_Test2>();
    }

    public int Id { get; set; }
    ..

    public virtual ICollection<Test1_Test2> Test1_Test2{ get; set; }
}

public partial class Test1_Test2
{
    public int Test1Id{ get; set; }
    public int Test2Id{ get; set; }

    public virtual Test1 Test1{ get; set; }
    public virtual Test2 Test2{ get; set; }
}

EF have constructed a Fluent API that supports this structure, with foreign keys and composite primary key in the joining table.

When I am to add something into this relationship, it is sort of a tedious operation, where I have to do something along the lines of this, in order to correctly populate my joining table:

_context.Test1.Add(Test1);
_context.Test2.Add(Test2);
Test1_Test2.Test1 = Test1;
Test1_Test2.Test2 = Test2;
_context.Test1_Test2.Add(Test1_Test2);
_context.SaveChanges();

From the old EF in .NET Framework, I remember that it was sort of straight forward to do an automapper functionality which would make me able to only do the following:

Test1.Test2 = Test2;
_context.Test1.Add(Test1);
_context.SaveChanges();

This is convenient as EF figures out how populate the joining table automatically. Also this is much more convenient when I have to make requests from these tables.

Therefore, how do I add an "automapper" functionality in .Net Core EF DB first - Is this even supported?


问:
How to click on the toolbar
 element?
I'm developing test automation and I want to click on  element located in toolbar,I'm using python and selenium. Here is a code of website

```<code><dl class="ToolbarDropdown_menu_2wY9X ToolbarDropdown_isHidden_3UaGr" tabindex="0" style=""
xpath="1"><dt><span class="ToolbarDropdown_title_1NBVn">New</span>
<span class="DropdownArrow_arrowIcon_dDzph DropdownArrow_down_3dlvo"></span>
</dt>
<dd class="ToolbarDropdown_item_nP-_M" style="">Dataset</dd>
<dd class="ToolbarDropdown_item_nP-_M">Project</dd>
</dl>
</code>```

I need to click on  element with text Dataset.

I locate element in this way

```<code>DATASET_BUTTON = (By.XPATH, '//dd[contains(text(),"Dataset")]')
</code>```

And I want to perform action like that

```<code>self.driver.find_element(*VideosPageLocator.DATASET_BUTTON).click()
</code>```

And there is no action but in terminal looks like my step has passed. Do you have any idea how to click on element in dropdown?

答:
Maybe the action is done before DOM has loaded completely.

Try using WebDriverWait.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

web_driver_wait = WebDriverWait(self.driver, 10)
element = web_driver_wait.until(EC.element_to_be_clickable((By.XPATH,'//dd[contains(text(),"Dataset")]')))
element.click()
```

Title: How to click on the toolbar <dd> element?

Body:
I'm developing test automation and I want to click on  element located in toolbar,I'm using python and selenium. Here is a code of website

New

Dataset

Project

I need to click on  element with text Dataset.

I locate element in this way

DATASET_BUTTON = (By.XPATH, '//dd[contains(text(),"Dataset")]')

And I want to perform action like that

self.driver.find_element(*VideosPageLocator.DATASET_BUTTON).click()

And there is no action but in terminal looks like my step has passed. Do you have any idea how to click on element in dropdown?


问:
Can bash script be written inside a AWS Lambda function
Can I write a bash script inside a Lambda function? I read in the aws docs that it can execute code written in Python, NodeJS and Java 8.

It is mentioned in some documents that it might be possible to use Bash but there is no concrete evidence supporting it or any example

答:
Now you can create Lambda functions written in any kind of language by providing a custom runtime which teaches the Lambda function to understand the syntax of the language you want to use.

You can follow this to learn more AWS Lambda runtimes


问:
How to sample without replacement within groups in R
I have a data frame which contains a 'year' variable with values between 1 and 100000 repeating multiple times. I have another data frame with 1000 'loss amounts' with an associated probability for each loss. I'd like to merge loss amounts onto the year data frame by sampling from the loss amounts table. I want to sample without replacement within each level of the year variable e.g. within each level of the year variable the loss amounts should be unique.

Reproducible example below where I can only get it to sample without replacement across the full 'year' dataset and not just within the different levels of the year variable as required. Is there a way of doing this (ideally without using loops as I need the code to run quickly)

```<code>#mean frequency
freq <- 100
years <- 100000

#create data frame with number of losses in each year
num_losses <- rpois(years, freq)
year <- tibble(index=1:length(num_losses), num=num_losses)
year <- map2(year$index, year$num, function(x, y) rep(x, y)) %>% unlist() %>% tibble(year = .)

#lookup table with loss amounts
lookup <- tibble(prob = runif(1000, 0, 1), amount = rgamma(1000, shape = 1.688, scale = 700000)) %>%
  mutate(total_prob = cumsum(prob)/sum(prob),
         pdf = total_prob - lag(total_prob),
         pdf = ifelse(is.na(pdf), total_prob, pdf))

#add on amounts to year table by sampling from lookup table
sample_from_lookup <- function(number){
  amount <- sample(lookup$amount, number, replace = FALSE, prob = lookup$pdf)
}

amounts <- sample_from_lookup(nrow(year))
year <- tibble(year = year$year, amount = amounts)

</code>```

答:
I ended up using split to break the 'year' data into groups within a list. Then running the(slightly amended) sample_from_lookup function on each element of the list using map. Amended code below.</p>

```<code>#mean frequency
freq <- 5
years <- 100

#create data frame with number of losses in each year
num_losses <- rpois(years, freq)
year <- tibble(index=1:length(num_losses), num=num_losses)
year <- map2(year$index, year$num, function(x, y) rep(x, y)) %>% unlist() %>% tibble(year = .)
year_split = split(year, year$year)

#lookup table
lookup <- tibble(prob = runif(1000, 0, 1), amount = rgamma(1000, shape = 1.688, scale = 700000)) %>%
  mutate(total_prob = cumsum(prob)/sum(prob),
         pdf = total_prob - lag(total_prob),
         pdf = ifelse(is.na(pdf), total_prob, pdf))

#add on amounts to year table by sampling from lookup table
sample_from_lookup <- function(x){
  number = NROW(x)
  amount <- sample(lookup$amount, number, replace = FALSE, prob = lookup$pdf)
}

amounts <- map(year_split, sample_from_lookup) %>% unlist() %>% tibble(amount = .)
year <- tibble(year = year$year, amount = amounts$amount)
</code>```

Body:
I have a data frame which contains a 'year' variable with values between 1 and 100000 repeating multiple times. I have another data frame with 1000 'loss amounts' with an associated probability for each loss. I'd like to merge loss amounts onto the year data frame by sampling from the loss amounts table. I want to sample without replacement within each level of the year variable e.g. within each level of the year variable the loss amounts should be unique.

Reproducible example below where I can only get it to sample without replacement across the full 'year' dataset and not just within the different levels of the year variable as required. Is there a way of doing this (ideally without using loops as I need the code to run quickly)

#mean frequency
freq <- 100
years <- 100000

#create data frame with number of losses in each year
num_losses <- rpois(years, freq)
year <- tibble(index=1:length(num_losses), num=num_losses)
year <- map2(year$index, year$num, function(x, y) rep(x, y)) %>% unlist() %>% tibble(year = .)

#lookup table with loss amounts
lookup <- tibble(prob = runif(1000, 0, 1), amount = rgamma(1000, shape = 1.688, scale = 700000)) %>%
  mutate(total_prob = cumsum(prob)/sum(prob),
         pdf = total_prob - lag(total_prob),
         pdf = ifelse(is.na(pdf), total_prob, pdf))

#add on amounts to year table by sampling from lookup table
sample_from_lookup <- function(number){
  amount <- sample(lookup$amount, number, replace = FALSE, prob = lookup$pdf)
}

amounts <- sample_from_lookup(nrow(year))
year <- tibble(year = year$year, amount = amounts)

Body:
I ended up using split to break the 'year' data into groups within a list. Then running the(slightly amended) sample_from_lookup function on each element of the list using map. Amended code below.

#mean frequency
freq <- 5
years <- 100

#create data frame with number of losses in each year
num_losses <- rpois(years, freq)
year <- tibble(index=1:length(num_losses), num=num_losses)
year <- map2(year$index, year$num, function(x, y) rep(x, y)) %>% unlist() %>% tibble(year = .)
year_split = split(year, year$year)

#lookup table
lookup <- tibble(prob = runif(1000, 0, 1), amount = rgamma(1000, shape = 1.688, scale = 700000)) %>%
  mutate(total_prob = cumsum(prob)/sum(prob),
         pdf = total_prob - lag(total_prob),
         pdf = ifelse(is.na(pdf), total_prob, pdf))

#add on amounts to year table by sampling from lookup table
sample_from_lookup <- function(x){
  number = NROW(x)
  amount <- sample(lookup$amount, number, replace = FALSE, prob = lookup$pdf)
}

amounts <- map(year_split, sample_from_lookup) %>% unlist() %>% tibble(amount = .)
year <- tibble(year = year$year, amount = amounts$amount)


问:
React Native Picker ArrayIndexOutOfBoundsExeception
I am using Picker component from React Native.

I have two Picker components: State (stateList() function) and City (cityList() function). I am calling two APIs: apiState() function loads the list of State and based on the State selected, the apiCity(state_identification) function will display a list of City. (code snippet provided below)

Code Snippet:

```<code>    constructor(props) {
    super(props);
    this.state = {
        pickerValueState: null,
        dataState: [],

        pickerValueCity: null,
        dataCity: [],

        isLoading: true,
    }
}

componentDidMount() {
    this.apiState();
}

apiState() {
    let self = this;
    AsyncStorage.getItem('my_token').then((keyValue) => {
        axios({
            method: 'get',
            url: Constants.API_URL + 'user_c/cState/',
            responseType: 'json',
            headers: {
                'X-API-KEY': Constants.API_KEY,
                'Authorization': keyValue,
            },
        })
            .then(function (response) {
                console.log('Response State Data: ', response.data.state);
                self.setState({
                    dataState: response.data.state,
                    isLoading: false,
                });
            })
            .catch(function (error) {
                console.log('Error (1st): ', error);
            });
    }, (error) => {
        console.log('Error (2nd): ', error) //Display error
    });
}

apiCity(state_identification) {
    let self = this;
    AsyncStorage.getItem('my_token').then((keyValue) => {
        axios({
            method: 'post',
            url: Constants.API_URL + 'user_c/cCity/',
            data: {
                state_id: state_identification,
            },
            /*params: {
                state_id: state_identification,
            },*/
            responseType: 'json',
            headers: {
                'X-API-KEY': Constants.API_KEY,
                'Authorization': keyValue,
            },
        })
            .then(function (response) {
                console.log('Response City Data: ', response.data.all_city);
                self.setState({
                    pickerValueState: state_identification,
                    dataCity: response.data.all_city,
                    isLoading: false,
                });
            })
            .catch(function (error) {
                console.log('Error (1st): ', error);
            });
    }, (error) => {
        console.log('Error (2nd): ', error) //Display error
    });
}

stateList() {
    return (
        <View>
            <Text h4 h4Style={{ textAlign: 'center' }}>Select Location</Text>
            <Text h4 h4Style={styles.location}>State</Text>
            <View style={styles.pickerContainer}>
                <Picker
                    mode="dropdown"
                    selectedValue={this.state.pickerValueState}
                    //onValueChange={(itemValue, itemIndex) => this.setState({ pickerValueState: itemValue })}
                    onValueChange={(itemValue, itemIndex) => {
                        /*this.setState({ pickerValueState: itemValue },
                            () => {
                                this.apiCity(this.state.pickerValueState, itemValue);
                                console.log('State selected: ', (this.state.pickerValueState))
                            }
                        )*/
                        this.apiCity(itemValue)
                    }}
                >
                    {
                        this.state.dataState.map((item, key) => (
                            <Picker.Item label={item.state_desc} value={item.state} key={key} />)
                        )
                    }
                </Picker>
            </View>
        </View>
    );
}

cityList() {
    return (
        <View>
            <Text h4 h4Style={styles.location}>City</Text>
            <View style={styles.pickerContainer}>
                <Picker
                    mode="dropdown"
                    selectedValue={this.state.pickerValueCity}
                    onValueChange={(itemValue, itemIndex) => {
                        this.setState({ pickerValueCity: itemValue },
                            () => {
                                console.log('City selected: ', (this.state.pickerValueCity))
                            }
                        )
                    }}
                >
                    {
                        this.state.dataCity.map((item, key) => (
                            <Picker.Item label={item.city_desc} value={item.city} key={key} />)
                        )
                    }
                </Picker>
            </View>
        </View>
    );
}

render() {
    if (this.state.isLoading) {
        return (
            <View style={{ flex: 1, justifyContent: 'center' }}>
                <ActivityIndicator size="large" color="#0000ff" />
            </View>
        );
    } else {
        return (
            <View style={styles.container}>
                <View style={styles.locationContainer}>
                    {this.stateList()}
                    {this.cityList()}
                </View>
            </View>
        );
    }
}
}
</code>```

Before I continue here's what the JSON data and the relation between State and City looks like:

```<code>//Lists of states:

{
    "state": [
        {
            "state": "14",
            "state_desc": "Kuala Lumpur"
        },
        {
            "state": "10",
            "state_desc": "Selangor"
        }
    ]
}

//if "state":"14" is selected, these cities are rendered in the picker
{
    "all_city": [
        {
            "city": "262",
            "city_desc": "Kuala Lumpur"
        },
        {
            "city": "263",
            "city_desc": "Sungai Besi"
        }
    ]
}

//if "state":"10" is selected, these cities are rendered in the picker
{
    "all_city": [
        {
            "city": "256",
            "city_desc": "Puchong"
        }
    ]
}
</code>```

I am facing several issues with my code and these are:

1. ArrayIndexOutOfBoundsExeception: length=1;index=1 (screenshot provided below):

By following this sequence the app crashes 100% of the time:

select "state":"10"

then change to select "state":"14" and "city":"263"

then finally select "state":"10" again

the app immediately crashes.

2. Problem with loading values:

When the app initially loads, "state": "14" is auto-selected BUT the City picker remains empty / doesn't display the label.

Then if I select "state":"10", the City picker loads the value "city": "256" ( and shows the value on the console.log) and it displays the label "city_desc": "Puchong".

However, when I select "state": "14" again, the City picker doesn't load the value (doesn't show the value on the console.log) but only displays the label "city_desc": "Kuala Lumpur". It only starts loading the value once I start interchanging between "city_desc": "Kuala Lumpur" and "city_desc": "Sungai Besi"

FINALLY, when I select "state":"10" AGAIN, the City picker doesn't load the value (doesn't show the value on the console.log) but only displays the label "city_desc": "Puchong".

Lastly, I have tried the following solution(i.e key={item.length}) from here but it didn't work.

答:
with this:

```<code> this.setState({ pickerValueState: itemValue },
                        () => {
                            this.apiCity(this.state.pickerValueState);
                            console.log('State selected: ', (this.state.pickerValueState))
                        }
                    )
</code>```

you have a period where the state have the new state, but the old city. which cause your exception. try to set state of the new state in the response of the city api. so you set the new state and new city at the same time. which probably mean you should pass to the apiCity function the new state as a parameter, then you use it in the api response.

So in the change event just do:

```<code>this.apiCity(this.state.pickerValueState, itemValue);
</code>```

and in the apiCityFunction, after fetch in setState for both together - city and state:

```<code> self.setState({
       pickerValueState: state,
       dataCity: response.data.all_city,
       isLoading: false,
 });
</code>```

Body:
I am using Picker component from React Native.

I have two Picker components: State (stateList() function) and City (cityList() function). I am calling two APIs: apiState() function loads the list of State and based on the State selected, the apiCity(state_identification) function will display a list of City. (code snippet provided below)

Code Snippet:

    constructor(props) {
    super(props);
    this.state = {
        pickerValueState: null,
        dataState: [],

        pickerValueCity: null,
        dataCity: [],

        isLoading: true,
    }
}

componentDidMount() {
    this.apiState();
}

apiState() {
    let self = this;
    AsyncStorage.getItem('my_token').then((keyValue) => {
        axios({
            method: 'get',
            url: Constants.API_URL + 'user_c/cState/',
            responseType: 'json',
            headers: {
                'X-API-KEY': Constants.API_KEY,
                'Authorization': keyValue,
            },
        })
            .then(function (response) {
                console.log('Response State Data: ', response.data.state);
                self.setState({
                    dataState: response.data.state,
                    isLoading: false,
                });
            })
            .catch(function (error) {
                console.log('Error (1st): ', error);
            });
    }, (error) => {
        console.log('Error (2nd): ', error) //Display error
    });
}

apiCity(state_identification) {
    let self = this;
    AsyncStorage.getItem('my_token').then((keyValue) => {
        axios({
            method: 'post',
            url: Constants.API_URL + 'user_c/cCity/',
            data: {
                state_id: state_identification,
            },
            /*params: {
                state_id: state_identification,
            },*/
            responseType: 'json',
            headers: {
                'X-API-KEY': Constants.API_KEY,
                'Authorization': keyValue,
            },
        })
            .then(function (response) {
                console.log('Response City Data: ', response.data.all_city);
                self.setState({
                    pickerValueState: state_identification,
                    dataCity: response.data.all_city,
                    isLoading: false,
                });
            })
            .catch(function (error) {
                console.log('Error (1st): ', error);
            });
    }, (error) => {
        console.log('Error (2nd): ', error) //Display error
    });
}

stateList() {
    return (
        <View>
            <Text h4 h4Style={{ textAlign: 'center' }}>Select Location</Text>
            <Text h4 h4Style={styles.location}>State</Text>
            <View style={styles.pickerContainer}>
                <Picker
                    mode="dropdown"
                    selectedValue={this.state.pickerValueState}
                    //onValueChange={(itemValue, itemIndex) => this.setState({ pickerValueState: itemValue })}
                    onValueChange={(itemValue, itemIndex) => {
                        /*this.setState({ pickerValueState: itemValue },
                            () => {
                                this.apiCity(this.state.pickerValueState, itemValue);
                                console.log('State selected: ', (this.state.pickerValueState))
                            }
                        )*/
                        this.apiCity(itemValue)
                    }}
                >
                    {
                        this.state.dataState.map((item, key) => (
                            <Picker.Item label={item.state_desc} value={item.state} key={key} />)
                        )
                    }
                </Picker>
            </View>
        </View>
    );
}

cityList() {
    return (
        <View>
            <Text h4 h4Style={styles.location}>City</Text>
            <View style={styles.pickerContainer}>
                <Picker
                    mode="dropdown"
                    selectedValue={this.state.pickerValueCity}
                    onValueChange={(itemValue, itemIndex) => {
                        this.setState({ pickerValueCity: itemValue },
                            () => {
                                console.log('City selected: ', (this.state.pickerValueCity))
                            }
                        )
                    }}
                >
                    {
                        this.state.dataCity.map((item, key) => (
                            <Picker.Item label={item.city_desc} value={item.city} key={key} />)
                        )
                    }
                </Picker>
            </View>
        </View>
    );
}

render() {
    if (this.state.isLoading) {
        return (
            <View style={{ flex: 1, justifyContent: 'center' }}>
                <ActivityIndicator size="large" color="#0000ff" />
            </View>
        );
    } else {
        return (
            <View style={styles.container}>
                <View style={styles.locationContainer}>
                    {this.stateList()}
                    {this.cityList()}
                </View>
            </View>
        );
    }
}
}

Before I continue here's what the JSON data and the relation between State and City looks like:

//Lists of states:

{
    "state": [
        {
            "state": "14",
            "state_desc": "Kuala Lumpur"
        },
        {
            "state": "10",
            "state_desc": "Selangor"
        }
    ]
}

//if "state":"14" is selected, these cities are rendered in the picker
{
    "all_city": [
        {
            "city": "262",
            "city_desc": "Kuala Lumpur"
        },
        {
            "city": "263",
            "city_desc": "Sungai Besi"
        }
    ]
}

//if "state":"10" is selected, these cities are rendered in the picker
{
    "all_city": [
        {
            "city": "256",
            "city_desc": "Puchong"
        }
    ]
}

I am facing several issues with my code and these are:

1. ArrayIndexOutOfBoundsExeception: length=1;index=1 (screenshot provided below):

By following this sequence the app crashes 100% of the time:

select "state":"10"

then change to select "state":"14" and "city":"263"

then finally select "state":"10" again

the app immediately crashes.

2. Problem with loading values:

When the app initially loads, "state": "14" is auto-selected BUT the City picker remains empty / doesn't display the label.

Then if I select "state":"10", the City picker loads the value "city": "256" ( and shows the value on the console.log) and it displays the label "city_desc": "Puchong".

However, when I select "state": "14" again, the City picker doesn't load the value (doesn't show the value on the console.log) but only displays the label "city_desc": "Kuala Lumpur". It only starts loading the value once I start interchanging between "city_desc": "Kuala Lumpur" and "city_desc": "Sungai Besi"

FINALLY, when I select "state":"10" AGAIN, the City picker doesn't load the value (doesn't show the value on the console.log) but only displays the label "city_desc": "Puchong".

Lastly, I have tried the following solution(i.e key={item.length}) from here but it didn't work.

Body:
with this:

 this.setState({ pickerValueState: itemValue },
                        () => {
                            this.apiCity(this.state.pickerValueState);
                            console.log('State selected: ', (this.state.pickerValueState))
                        }
                    )

you have a period where the state have the new state, but the old city. which cause your exception. try to set state of the new state in the response of the city api. so you set the new state and new city at the same time. which probably mean you should pass to the apiCity function the new state as a parameter, then you use it in the api response.

So in the change event just do:

this.apiCity(this.state.pickerValueState, itemValue);

and in the apiCityFunction, after fetch in setState for both together - city and state:

 self.setState({
       pickerValueState: state,
       dataCity: response.data.all_city,
       isLoading: false,
 });


问:
Sql Query Puzzling
My SQL Query errors stating:

```<code>Msg 537, Level 16, State 2, Line 1 Invalid length parameter passed to the LEFT or SUBSTRING function.
</code>```

BELOW is the query that doesn't work, but as soon as I replace
  "Select" with "Select top 100" on the inner query (OQry), it works
  (this is marked in the comments of the code).  The error looks to be
  inappropriate.  Any ideas?:

```<code>Select distinct OQry.Create_tstamp, OQry.LDC_Account_Num, OQry.Territory_code, Replace(LEFT(OQry.Customer_Name,CHARINDEX(' ',OQry.Customer_Name)-1),'-','') as LastName,
trim(Replace(Right(OQry.Customer_Name, Len(OQry.Customer_Name) - Len(Replace(LEFT(OQry.Customer_Name,CHARINDEX(' ',OQry.Customer_Name)-1),'-','') )),'-','')) as FirstName,
OQry.Commodity,OQry.confirmed_start_date,OQry.confirmed_drop_date,OQry.Market_status_desc,OQry.Reason_code,OQry.Flow_direction_Desc,OQry.AGENT_CODE,Da.AGENT_CODE as [Sub Agent]
from
(
select --This doesn't work but If I replace this with "Select top 100" then it works....  WHAT?!
d.Create_tstamp, d.customer_tkn,
right('00000000'+d.customer_tkn,8) + '-' + right('00'+d.customer_acct_tkn,2) + '-' +  right('0000'+d.account_pkg_tkn,4) as [Account Number], a.AGENT_CODE,
dl.LDC_Account_Num, d.Territory_code, Customer_Name, da.account_pkg_desc as Commodity, da.confirmed_start_date, da.confirmed_drop_date, d.Reason_code, d.Flow_direction_Desc,
d.Market_status_desc
from
datamart_market_detail d
left outer join datamart_ldc dl on dl.Customer_Tkn = d.Customer_tkn
and dl.Customer_Acct_Tkn = d.Customer_Acct_Tkn and dl.Account_Pkg_Tkn = d.Account_Pkg_Tkn
left join datamart_accounts da on d.Customer_tkn = da.customer_tkn and d.Customer_Acct_Tkn = da.customer_acct_tkn and d.Account_Pkg_Tkn = da.account_pkg_tkn
left outer join datamart_agent a on a.CUSTOMER_TKN = da.customer_tkn
where Market_status_desc like '%Drop%'
) OQry
left join
datamart_agent Da
on OQry.customer_tkn = Da.customer_tkn and OQry.[Account Number] = (right('00000000'+da.customer_tkn,8) + '-' + right('00'+da.customer_acct_tkn,2) + '-' +  right('0000'+da.account_pkg_tkn,4))
</code>```

答:
You have a data problem, stemming from Falsehoods Programmers Believe About Names.

Somewhere in your data set, there's a value of OQry.Customer_Name that isn't structured the way you're expecting it to be in order for it to be the basis of a CHARINDEX function call.

Take a closer look at the data in that column.

```<code>SELECT
  *
FROM (...)  AS OQry
WHERE
  CHARINDEX(' ', OQry.Customer_Name) - 1 <= 0
</code>```

Title: Sql Query Puzzling

Body:
My SQL Query errors stating:

Msg 537, Level 16, State 2, Line 1 Invalid length parameter passed to the LEFT or SUBSTRING function.

BELOW is the query that doesn't work, but as soon as I replace
  "Select" with "Select top 100" on the inner query (OQry), it works
  (this is marked in the comments of the code).  The error looks to be
  inappropriate.  Any ideas?:

Select distinct OQry.Create_tstamp, OQry.LDC_Account_Num, OQry.Territory_code, Replace(LEFT(OQry.Customer_Name,CHARINDEX(' ',OQry.Customer_Name)-1),'-','') as LastName,
trim(Replace(Right(OQry.Customer_Name, Len(OQry.Customer_Name) - Len(Replace(LEFT(OQry.Customer_Name,CHARINDEX(' ',OQry.Customer_Name)-1),'-','') )),'-','')) as FirstName,
OQry.Commodity,OQry.confirmed_start_date,OQry.confirmed_drop_date,OQry.Market_status_desc,OQry.Reason_code,OQry.Flow_direction_Desc,OQry.AGENT_CODE,Da.AGENT_CODE as [Sub Agent]
from
(
select --This doesn't work but If I replace this with "Select top 100" then it works....  WHAT?!
d.Create_tstamp, d.customer_tkn,
right('00000000'+d.customer_tkn,8) + '-' + right('00'+d.customer_acct_tkn,2) + '-' +  right('0000'+d.account_pkg_tkn,4) as [Account Number], a.AGENT_CODE,
dl.LDC_Account_Num, d.Territory_code, Customer_Name, da.account_pkg_desc as Commodity, da.confirmed_start_date, da.confirmed_drop_date, d.Reason_code, d.Flow_direction_Desc,
d.Market_status_desc
from
datamart_market_detail d
left outer join datamart_ldc dl on dl.Customer_Tkn = d.Customer_tkn
and dl.Customer_Acct_Tkn = d.Customer_Acct_Tkn and dl.Account_Pkg_Tkn = d.Account_Pkg_Tkn
left join datamart_accounts da on d.Customer_tkn = da.customer_tkn and d.Customer_Acct_Tkn = da.customer_acct_tkn and d.Account_Pkg_Tkn = da.account_pkg_tkn
left outer join datamart_agent a on a.CUSTOMER_TKN = da.customer_tkn
where Market_status_desc like '%Drop%'
) OQry
left join
datamart_agent Da
on OQry.customer_tkn = Da.customer_tkn and OQry.[Account Number] = (right('00000000'+da.customer_tkn,8) + '-' + right('00'+da.customer_acct_tkn,2) + '-' +  right('0000'+da.account_pkg_tkn,4))

Body:
You have a data problem, stemming from Falsehoods Programmers Believe About Names.

Somewhere in your data set, there's a value of OQry.Customer_Name that isn't structured the way you're expecting it to be in order for it to be the basis of a CHARINDEX function call.

Take a closer look at the data in that column.

SELECT
  *
FROM (...)  AS OQry
WHERE
  CHARINDEX(' ', OQry.Customer_Name) - 1 <= 0


问:
I need to filter the yui datatable which has inline cell editing. and the data is coming from the groovy controller in key:value pair form. as JSON
hi i am also facing the data error problem. i wanted to filter the data coming from json result from the groovy controller in key:value pair. even if i chage the TYPE_JSON to TYPE_JSARRAY,i am getting NoRecordas found in data table but the json result has the data.

please can u correct me.

Thanks in advance!!

答:
```<code>dobMenuButton.subscribe("selectedMenuItemChange",function(e) {
    var value =e.newValue.value;
    if(YAHOO.lang.isValue(value)) {
        myDataTable.getDataSource().sendRequest(null, {
            success:function(request, response, payload) {
                this.initializeTable();
                var rs = response.results;
                var filtered = [];
                for(var i = 0; i < rs.length; i++) {
                    if(((rs[i].dateOfBirth).format("MM/dd/yyyy")) == value) {
                        filtered[filtered.length] = rs[i];
                    }
                }
                this.getRecordSet().reset();
                MCMPagination.paginatorvar.setTotalRecords(filtered.length,true);
                this.getRecordSet().setRecords(filtered, 0);
                this.render();
        },
        scope:myDataTable,
            argument:myDataTable.getState()
        });
    }
});
</code>```


问:
Postgres count rows where value transitions from : A -> B -> A
I need to find the count of records where position of a person_id changes from 1 -> 2 -> 1
 The transitions needs to be sorted in ascending order depending on the timestamp

Table Structure

```<code>timestamp  | person_id | position
--------------------------------
2020-01-01 | 5         |  1
2020-01-03 | 4         |  2
2020-02-04 | 7         |  1
2020-02-05 | 5         |  2
2020-02-06 | 7         |  2
2020-02-09 | 5         |  1
</code>```

Here, the output will be 1, since person_id:5 transitions from 1 -> 2 -> 1

select count(*)
from table_name t1
join table_name t2
  on t1.person_id = t2.person_id
 and t1.position = 1
 and t2.position = 2
 and t1.timestamp < t2.timestamp;
```

Using this query I can find transition from 1 -> 2
But I can't figure out how to again search for the transition to 1

答:
Looks like a good use case for the LEAD window function.

Edited:

```<code>SELECT count(*) FROM(
SELECT position as p1, lead(position) OVER (PARTITION BY person_id ORDER BY timestamp) as p2, lead(position, 2) OVER (PARTITION BY person_id ORDER BY timestamp) as p3
FROM table_name) qry where qry.p1=1 and qry.p2=2 and qry.p3=1
</code>```

Body:
I need to find the count of records where position of a person_id changes from 1 -> 2 -> 1
 The transitions needs to be sorted in ascending order depending on the timestamp

Table Structure

timestamp  | person_id | position
--------------------------------
2020-01-01 | 5         |  1
2020-01-03 | 4         |  2
2020-02-04 | 7         |  1
2020-02-05 | 5         |  2
2020-02-06 | 7         |  2
2020-02-09 | 5         |  1

Here, the output will be 1, since person_id:5 transitions from 1 -> 2 -> 1

select count(*)
from table_name t1
join table_name t2
  on t1.person_id = t2.person_id
 and t1.position = 1
 and t2.position = 2
 and t1.timestamp < t2.timestamp;

Using this query I can find transition from 1 -> 2
But I can't figure out how to again search for the transition to 1

Body:
Looks like a good use case for the LEAD window function.

Edited:

SELECT count(*) FROM(
SELECT position as p1, lead(position) OVER (PARTITION BY person_id ORDER BY timestamp) as p2, lead(position, 2) OVER (PARTITION BY person_id ORDER BY timestamp) as p3
FROM table_name) qry where qry.p1=1 and qry.p2=2 and qry.p3=1


问:
C++: create a pointer in a program and access that location in another program
So, is it possible to create a pointer in C++ like this, and print it out:

```<code>#include <iostream>
int main() {
    int* ptr = new int;
    (*ptr) = 3;
    std::cout << ptr << '\n';
}
</code>```

And then run it, copy the value of ptr, and in another program, while this is running, do this:

```<code>#include <iostream>
#include <cstring>
int main() {
    long long pointer;
    std::cin >> pointer;
    int* ptr = nullptr;
    std::memcpy(&ptr, &pointer, sizeof(pointer));
    std::cout << *ptr << '\n';
}
</code>```

And get 3 printed out? Is it possible, or if not, then exactly why?

答: This is not possible in standard c++. This is because the program memory are virtual, and you can’t access other program’s memories because they are in a separate virtual memory. A pipe would work for what you want.</p>

Body:
So, is it possible to create a pointer in C++ like this, and print it out:

#include <iostream>
int main() {
    int* ptr = new int;
    (*ptr) = 3;
    std::cout << ptr << '\n';
}

And then run it, copy the value of ptr, and in another program, while this is running, do this:

#include <iostream>
#include <cstring>
int main() {
    long long pointer;
    std::cin >> pointer;
    int* ptr = nullptr;
    std::memcpy(&ptr, &pointer, sizeof(pointer));
    std::cout << *ptr << '\n';
}

And get 3 printed out? Is it possible, or if not, then exactly why?


问:
Proving General Associativity in Groups
For a project I'm coding group theory through Coq, obviously associatvity of 3 elements is a given, however I'm struggling to prove it holds for a string of length n. That is, (x1 * ... * xn) is always the same regardless of how many brackets are in there, or there placement.
The relevant group code is

```<code>Structure group :=
{
  e : G;
  Op : G -> G -> G;
  Inv : G -> G;

  Associativity : forall (x y z : G), Op x (Op y z) = Op (Op x y) z;
  LeftInverse : forall (x : G), Op (Inv x) x = e;
  LeftIdentity : forall (x : G), Op e x = x;
}.
</code>```

It's not the proof itself I have the issue with but how to code it. I can see at the very least I'll need a further function that allows me to operate on strings rather than just elements, but i've no idea how to get started. Any pointers?

答:
Operating on strings directly is certainly possible, but cumbersome.  When reasoning about languages, it is much more convenient to use abstract syntax trees instead.  For your statement, we only want to consider combinations of elements with some binary operation, so a binary tree suffices:

```<code>Inductive tree T :=
| Leaf : T -> tree T
| Node : tree T -> tree T -> tree T.
</code>```

For concreteness, I'll only consider the natural numbers under addition, but this generalizes to any other monoid (and thus any other group).  We can write a function that sums all the elements of a tree:

```<code>Fixpoint sum_tree t : nat :=
  match t with
  | Leaf n => n
  | Node t1 t2 => sum_tree t1 + sum_tree t2
  end.
</code>```

We can also write a function that flattens the tree, collecting all of its elements in a list

```<code>Fixpoint elements {T} (t : tree T) : list T :=
  match t with
  | Leaf x => [x]
  | Node t1 t2 => elements t1 ++ elements t2
  end.
</code>```

With these ingredients, we can formulate the statement that you were looking for: if two trees (that is, two ways of putting parenthesis in an expression) have the same sequences of elements, then they must add up to the same number.

```<code>Lemma eq_sum_tree t1 t2 :
  elements t1 = elements t2 -> sum_tree t1 = sum_tree t2.
</code>```

I'll leave the proof of this statement to you. ;)

Title: Proving General Associativity in Groups

Body:
For a project I'm coding group theory through Coq, obviously associatvity of 3 elements is a given, however I'm struggling to prove it holds for a string of length n. That is, (x1 * ... * xn) is always the same regardless of how many brackets are in there, or there placement.
The relevant group code is

Structure group :=
{
  e : G;
  Op : G -> G -> G;
  Inv : G -> G;

  Associativity : forall (x y z : G), Op x (Op y z) = Op (Op x y) z;
  LeftInverse : forall (x : G), Op (Inv x) x = e;
  LeftIdentity : forall (x : G), Op e x = x;
}.

It's not the proof itself I have the issue with but how to code it. I can see at the very least I'll need a further function that allows me to operate on strings rather than just elements, but i've no idea how to get started. Any pointers?

Body:
Operating on strings directly is certainly possible, but cumbersome.  When reasoning about languages, it is much more convenient to use abstract syntax trees instead.  For your statement, we only want to consider combinations of elements with some binary operation, so a binary tree suffices:

Inductive tree T :=
| Leaf : T -> tree T
| Node : tree T -> tree T -> tree T.

For concreteness, I'll only consider the natural numbers under addition, but this generalizes to any other monoid (and thus any other group).  We can write a function that sums all the elements of a tree:

Fixpoint sum_tree t : nat :=
  match t with
  | Leaf n => n
  | Node t1 t2 => sum_tree t1 + sum_tree t2
  end.

We can also write a function that flattens the tree, collecting all of its elements in a list

Fixpoint elements {T} (t : tree T) : list T :=
  match t with
  | Leaf x => [x]
  | Node t1 t2 => elements t1 ++ elements t2
  end.

With these ingredients, we can formulate the statement that you were looking for: if two trees (that is, two ways of putting parenthesis in an expression) have the same sequences of elements, then they must add up to the same number.

Lemma eq_sum_tree t1 t2 :
  elements t1 = elements t2 -> sum_tree t1 = sum_tree t2.

I'll leave the proof of this statement to you. ;)


问:
Setting up line-height via TinyMCE
Is there a way to give user possibility to easily changing line-height attribute of paragraph in tinyMCE editor? Something like its native "Font size" or "Format" <select> or anything else. I know I can use "edit CSS" functionality and set it up there. I'm looking for something more user-friendly.

I can't find it anywhere.

答:
Indeed, TinyMCE doesn't have line-height control as it has for font names or font sizes, but you can easily add it with the style_formats. I used this config:

// custom formatting is under Format > formats, so make sure it's in your menu (it is, by default)
const editorOptions = {
  // Notice that it overrides Format > formats
  style_formats: [
      {
          title: 'Line height',
          items: [
            {
              title: 'Default',
              inline: 'span',
              // `inline-block` because CSS `line-height` doesn't affect multiline `span`
              styles: { 'line-height': 'normal', display: 'inline-block' }
            },
            {
              title: '40px',
              inline: 'span',
              styles: { 'line-height': '40px', display: 'inline-block' }
            },
            // add as more as you need
          ]
      },
      // ...
  ]
}
```

Working example on codepen

TinyMCE style_formats doc

Title: Setting up line-height via TinyMCE

Body:
Indeed, TinyMCE doesn't have line-height control as it has for font names or font sizes, but you can easily add it with the style_formats. I used this config:

// custom formatting is under Format > formats, so make sure it's in your menu (it is, by default)
const editorOptions = {
  // Notice that it overrides Format > formats
  style_formats: [
      {
          title: 'Line height',
          items: [
            {
              title: 'Default',
              inline: 'span',
              // `inline-block` because CSS `line-height` doesn't affect multiline `span`
              styles: { 'line-height': 'normal', display: 'inline-block' }
            },
            {
              title: '40px',
              inline: 'span',
              styles: { 'line-height': '40px', display: 'inline-block' }
            },
            // add as more as you need
          ]
      },
      // ...
  ]
}

Working example on codepen

TinyMCE style_formats doc


问:
how to figure out your p12 password made in openssl when publishing for iOS in flash CS5.5?
I've finished up development in flash for my iphone app, payed for the dev license, and used this tutorial to use openSSL to make my p12 file.  I have the provisioning profile downloaded from apple and the p12 done, but I have no clue how to figure out the password of the p12.  When I publish flash tells me "could not load keystore files (password may be incorrect).  So basically I need to know how to figure out the password.  I'm completely new to openssl so I'm not sure if there's something I need to add in the code or what?</p>

答: The easiest way is just to export your certificate from your "Keychain Access" application. When you export it (in .p12 format) you have to add a password which you will use in flash. This option is available only if you are using MAC OS. </p>


问:
C# Encode.<format>.GetBytes() returning different data to that input
From the docs, Encode should provide a way to convert bytes to a string and back again. However, this test case gives very different results after the decode. The input data 'bytes' is 6 elements, but the output data 'outputData' is 17 elements. Why is this? </p>

```<code>    byte[] bytes = new byte[] { 24, 48, 49, 127, 250, 255, 1 };

    char[] charData = Encoding.UTF7.GetChars(bytes);
    byte[] outputData = Encoding.UTF7.GetBytes(charData);
</code>```

答:
From Damien_The_Unbeliever's suggestion, found Convert instead</p>

```<code>    byte[] bytes = new byte[] { 24, 48, 49, 127, 250, 255, 1 };

    // encode
    string byteString = Convert.ToBase64String(bytes);
    byte[] byteList = Convert.FromBase64String(byteString);
</code>```

Body:
From the docs, Encode should provide a way to convert bytes to a string and back again. However, this test case gives very different results after the decode. The input data 'bytes' is 6 elements, but the output data 'outputData' is 17 elements. Why is this?

    byte[] bytes = new byte[] { 24, 48, 49, 127, 250, 255, 1 };

    char[] charData = Encoding.UTF7.GetChars(bytes);
    byte[] outputData = Encoding.UTF7.GetBytes(charData);

Body:
From Damien_The_Unbeliever's suggestion, found Convert instead

    byte[] bytes = new byte[] { 24, 48, 49, 127, 250, 255, 1 };

    // encode
    string byteString = Convert.ToBase64String(bytes);
    byte[] byteList = Convert.FromBase64String(byteString);


问:
How to test admin change views?
I got a rather complex admin change view for my Django model.

There is a lot of resources about how to test the admin list views (e.g. here), but not for the change view.

How can I create a test cases for it?

答:
You can test the admin change view of any model with Django's test client.

For that you will need the specific view URL for your model, which can be generated as described in the docs.

Here is an example how to run a simple "loads normally" test for the Group model:

```<code>from django.contrib.auth.models import User, Group
from django.test import TestCase, Client
from django.urls import reverse

def get_admin_change_view_url(obj: object) -> str:
    return reverse(
        'admin:{}_{}_change'.format(
            obj._meta.app_label,
            type(obj).__name__.lower()
        ),
        args=(obj.pk,)
    )

class TestGroupAdmin(TestCase):

    def test_change_view_loads_normally(self):
        # prepare client
        User.objects.create_superuser(
            username='superuser', password='secret', email='admin@example.com'
        )
        c = Client()
        c.login(username='superuser', password='secret')

        # create test data
        my_group = Group.objects.create(name='Test Group')

        # run test
        response = c.get(get_admin_change_view_url(my_group))
        self.assertEqual(response.status_code, 200)

</code>```

Title: How to test admin change views?

Body:
You can test the admin change view of any model with Django's test client.

For that you will need the specific view URL for your model, which can be generated as described in the docs.

Here is an example how to run a simple "loads normally" test for the Group model:

from django.contrib.auth.models import User, Group
from django.test import TestCase, Client
from django.urls import reverse

def get_admin_change_view_url(obj: object) -> str:
    return reverse(
        'admin:{}_{}_change'.format(
            obj._meta.app_label,
            type(obj).__name__.lower()
        ),
        args=(obj.pk,)
    )

class TestGroupAdmin(TestCase):

    def test_change_view_loads_normally(self):
        # prepare client
        User.objects.create_superuser(
            username='superuser', password='secret', email='admin@example.com'
        )
        c = Client()
        c.login(username='superuser', password='secret')

        # create test data
        my_group = Group.objects.create(name='Test Group')

        # run test
        response = c.get(get_admin_change_view_url(my_group))
        self.assertEqual(response.status_code, 200)


问:
How to fix Error: [Errno 2] No such file or directory: 'C:\\Program Files\\Python37\\lib\\venv\\scripts\\nt\\python_d.exe'
I'm using the latest version of Python on Windows and I'm trying to use venv with the following code:

```<code>C:\envs> py -m venv test
</code>```

Even if it actually creates the venv, it returns this error and I don't understand why.
Moreover I can't activate the venv, the code

```<code>C:\envs> C:\envs\test\Scripts\activate.bat
</code>```

returns

"C:\envs\test\Scripts\activate.bat" is not recognized as an internal or external command, operable program or batch file.

答:
These steps worked for me</p>

```<code>conda update --force conda
conda update python
conda list --show-channel-urls | findstr python
python -m venv venv
</code>```

Body:
I'm using the latest version of Python on Windows and I'm trying to use venv with the following code:

C:\envs> py -m venv test

Even if it actually creates the venv, it returns this error and I don't understand why.
Moreover I can't activate the venv, the code

C:\envs> C:\envs\test\Scripts\activate.bat

returns

"C:\envs\test\Scripts\activate.bat" is not recognized as an internal or external command, operable program or batch file.

Body:
These steps worked for me

conda update --force conda
conda update python
conda list --show-channel-urls | findstr python
python -m venv venv


问:
How to decrypt .pgp file stored in Google cloud storage?
I have a .pgp file stored in bucket in Google cloud storage.
I want to decrypt it with private key and store it back to new target folder in GCS.
is there a way we can do this?</p>

答:
Is not possible to make changes directly on Google Cloud Storage (GCS), to decrypt and save your files is necessary download your file, decrypt locally and upload the decrypted file.

i think that this code will be useful for your use case:

```<code>from google.cloud import storage

def download_blob(bucket_name, source_blob_name, local_file, destination_blob_name):
   #bucket_name = "your-bucket-name"
   #source_blob_name = "storage-object.pgp"
   #local_file = "local/storage-object.pgp"

   #Download your file from your bucket
   storage_client = storage.Client()

   bucket = storage_client.bucket(bucket_name)
   blob = bucket.blob(source_blob_name)
   blob.download_to_filename(local_file)

   # put your code to decrypt your file

   #Upload your decrypted file from local
   destination_blob_name= "/decrypted_files/storage-object.pgp"
   blob = bucket.blob(destination_blob_name)
   blob.upload_from_filename(local_file)
</code>```

Body:
Is not possible to make changes directly on Google Cloud Storage (GCS), to decrypt and save your files is necessary download your file, decrypt locally and upload the decrypted file.

i think that this code will be useful for your use case:

from google.cloud import storage

def download_blob(bucket_name, source_blob_name, local_file, destination_blob_name):
   #bucket_name = "your-bucket-name"
   #source_blob_name = "storage-object.pgp"
   #local_file = "local/storage-object.pgp"

   #Download your file from your bucket
   storage_client = storage.Client()

   bucket = storage_client.bucket(bucket_name)
   blob = bucket.blob(source_blob_name)
   blob.download_to_filename(local_file)

   # put your code to decrypt your file

   #Upload your decrypted file from local
   destination_blob_name= "/decrypted_files/storage-object.pgp"
   blob = bucket.blob(destination_blob_name)
   blob.upload_from_filename(local_file)


问:
Minimap do not show 2D view
I following this tuttorial to load the Autodesk.AEC.Minimap3DExtension to my viewer, but can not see the 2D plan view on the minimap. I'm also try to set generateMasterViews to true in the option of translation process but nothing better.
Can you please help ? Thank in advance.

```<code>   formats: [
      {
        type: "svf",
        views: ["2d", "3d"],
        advanced: {
            "generateMasterViews": true
          }
      }
    ]
</code>```

答:
to access the 2D view in the minimap you need to have the AEC data. after loading the document you must download the AECdata through the downloadAecModelData () method.</p>

```<code>Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);

function onDocumentLoadSuccess(viewerDocument) {
  var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
  viewer.loadDocumentNode(viewerDocument, defaultModel);
  viewerDocument.downloadAecModelData();
}
</code>```

Title: Minimap do not show 2D view

Body:
I following this tuttorial to load the Autodesk.AEC.Minimap3DExtension to my viewer, but can not see the 2D plan view on the minimap. I'm also try to set generateMasterViews to true in the option of translation process but nothing better.
Can you please help ? Thank in advance.

   formats: [
      {
        type: "svf",
        views: ["2d", "3d"],
        advanced: {
            "generateMasterViews": true
          }
      }
    ]

Body:
to access the 2D view in the minimap you need to have the AEC data. after loading the document you must download the AECdata through the downloadAecModelData () method.

Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);

function onDocumentLoadSuccess(viewerDocument) {
  var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
  viewer.loadDocumentNode(viewerDocument, defaultModel);
  viewerDocument.downloadAecModelData();
}


问:
How to push data in MongoDB's array with mongoose
I have an empty array in MongoDB

And I want to push the Id in it.

```<code>router.put(
  "/like/:id",
  (req, res) => {
    User.findOne({ _id: req.user._id }).then(data => {
      if (data) {
        Post.update(
          { _id: ObjectId(req.params.id) },
          { $push: { likes: req.user._id } }
        );
      }
    });
  }
);
</code>```

This code is not working on how I achieve this.

答:
```<code>router.put (
  "/addlike/:id",
  passport.authenticate("jwt", {
    session: false
  }),
  (req, res) => {

   // use try-catch
   try {
    User.findOne({ _id: req.user._id }).then(data => {
      if (data) {
        Post.findOneAndUpdate(
          { _id: ObjectId(req.params.id) },
          { $push: { likes: req.user._id },
          { "new": true, "upsert": true} }
        );
      }
    });
   } catch(err){
    // handle error
    console.log('Error => ', err);
   }
  }
);
</code>```

I have tested this in my local system ... working fine

Body:
I have an empty array in MongoDB

And I want to push the Id in it.

router.put(
  "/like/:id",
  (req, res) => {
    User.findOne({ _id: req.user._id }).then(data => {
      if (data) {
        Post.update(
          { _id: ObjectId(req.params.id) },
          { $push: { likes: req.user._id } }
        );
      }
    });
  }
);

This code is not working on how I achieve this.

Body:
router.put (
  "/addlike/:id",
  passport.authenticate("jwt", {
    session: false
  }),
  (req, res) => {

   // use try-catch
   try {
    User.findOne({ _id: req.user._id }).then(data => {
      if (data) {
        Post.findOneAndUpdate(
          { _id: ObjectId(req.params.id) },
          { $push: { likes: req.user._id },
          { "new": true, "upsert": true} }
        );
      }
    });
   } catch(err){
    // handle error
    console.log('Error => ', err);
   }
  }
);

I have tested this in my local system ... working fine


问:
How can we change spider chart background color?
Refer this image to see what i am looking at:

With this code :

const colors = [ColorRGBA(0, 255, 125, 0), ColorRGBA(255, 125, 0, 0)]
const fillStyles = colors.map((color) => new SolidFill({ color: color.setA(150) }))

const chart = db.createSpiderChart({
  columnIndex: 1,
  rowIndex: 0,
  columnSpan: 1,
  rowSpan: 2
})
  .setTitle('Spider chart')
  .setBackgroundFillStyle(fillStyles[0])
```

I am getting this result :

答:
You can change the background color of the chart by using the method  setChartBackgroundFillStyle with the wanted FillStyle

For example:

```<code>const colors = [ColorRGBA(0, 255, 125, 0), ColorRGBA(255, 125, 0, 0)]
const fillStyles = colors.map((color) => new SolidFill({ color: color.setA(150) }))

const chart = db.createSpiderChart({
  columnIndex: 1,
  rowIndex: 0,
  columnSpan: 1,
  rowSpan: 2
})
  .setTitle('Spider chart')
  .setBackgroundFillStyle(fillStyles[0])
  .setChartBackgroundFillStyle(fillStyles[1])
</code>```

Body:
Refer this image to see what i am looking at:

With this code :

const colors = [ColorRGBA(0, 255, 125, 0), ColorRGBA(255, 125, 0, 0)]
const fillStyles = colors.map((color) => new SolidFill({ color: color.setA(150) }))

const chart = db.createSpiderChart({
  columnIndex: 1,
  rowIndex: 0,
  columnSpan: 1,
  rowSpan: 2
})
  .setTitle('Spider chart')
  .setBackgroundFillStyle(fillStyles[0])

I am getting this result :

Body:
You can change the background color of the chart by using the method  setChartBackgroundFillStyle with the wanted FillStyle

For example:

const colors = [ColorRGBA(0, 255, 125, 0), ColorRGBA(255, 125, 0, 0)]
const fillStyles = colors.map((color) => new SolidFill({ color: color.setA(150) }))

const chart = db.createSpiderChart({
  columnIndex: 1,
  rowIndex: 0,
  columnSpan: 1,
  rowSpan: 2
})
  .setTitle('Spider chart')
  .setBackgroundFillStyle(fillStyles[0])
  .setChartBackgroundFillStyle(fillStyles[1])