答:
Here, you can create a character list to keep track of the characters that have already occurred in S.

Have a look at the code below, hope it helps:>

```<code>def repfree(S):
    freq = []
    for char in S:
        # if the character is already in list that means S contains repeated char
        if char in freq:
            return False
        else:
            freq.append(char)

    return True
</code>```

Body:
Here, you can create a character list to keep track of the characters that have already occurred in S.

Have a look at the code below, hope it helps:>

def repfree(S):
    freq = []
    for char in S:
        # if the character is already in list that means S contains repeated char
        if char in freq:
            return False
        else:
            freq.append(char)

    return True


来源: stackexchange

问:
Access structure members by using structure name only
I  don't know what type on question i am asking.but i only need suggestion or idea to find the way.

I have many structure with large number of members like below

```<code>typedef struct _Bank0
{
unsigned char main_control_char;
unsigned short input_port_short;
:
:
}Pack Bank0;

typedef struct _Bank1
{
unsigned char ddr3_control_char;
unsigned char ddl_control_char;
:
:
}Pack Bank1;
</code>```

I want to write a test function for this register bank, if i give bank number (that is structure name) it should display all the register in that bank.

i just have to avoid repeat programing for testing register, i am trying in following way

```<code>select register bank= Bank1(* user  will enter this value) //
//now i want to show all register name in bank 1 for example//
ddr3_control_char
ddl_control_char
</code>```

after this i want to send data to the selected register.
can any one suggest me any idea.i just don't want to copy paste register name again because the length of my code will be to more so to avoid it i want suggestion.

答:
You can implement this functionality for every Bank type individually and then use inheritance, e.g.

```<code>using ValueType = size_t;
using Dump = std::unordered_map<std::string, Value_type>;
struct Bank {
    virtual Dump dump() const = 0;
};
struct Bank0 : public Bank {
    Dump dump() const override {
        return Dump();
    }
};
struct Bank1 : public Bank {
    Dump dump() const override {
        return Dump();
    }
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I  don't know what type on question i am asking.but i only need suggestion or idea to find the way.

I have many structure with large number of members like below

typedef struct _Bank0
{
unsigned char main_control_char;
unsigned short input_port_short;
:
:
}Pack Bank0;

typedef struct _Bank1
{
unsigned char ddr3_control_char;
unsigned char ddl_control_char;
:
:
}Pack Bank1;

I want to write a test function for this register bank, if i give bank number (that is structure name) it should display all the register in that bank.

i just have to avoid repeat programing for testing register, i am trying in following way

select register bank= Bank1(* user  will enter this value) //
//now i want to show all register name in bank 1 for example//
ddr3_control_char
ddl_control_char

after this i want to send data to the selected register.
can any one suggest me any idea.i just don't want to copy paste register name again because the length of my code will be to more so to avoid it i want suggestion.

Body:
You can implement this functionality for every Bank type individually and then use inheritance, e.g.

using ValueType = size_t;
using Dump = std::unordered_map<std::string, Value_type>;
struct Bank {
    virtual Dump dump() const = 0;
};
struct Bank0 : public Bank {
    Dump dump() const override {
        return Dump();
    }
};
struct Bank1 : public Bank {
    Dump dump() const override {
        return Dump();
    }
};


问:
Parameters Framework for C++
I'm trying to find a parameters framework in C++ to synchronize parameters and variant types between a client/server.  I've tried googling around, but I think I don't have the right search terms.

Example: An object on the server could have the following parameters defined and mapped to the member variables:

```<code>"name":  std::string,
"alpha": float,
"mask":  uint
</code>```

Where these parameters could then be queried by the client and their values adjusted.

Is there something similar to this that exists in the open source world?

Edit for clarification:

The server I've created is a video application, where a video is displayed with N number of filters.  The filters have N number of parameters, and are of different types.  I want the client to be able to query for: # of filters, the filter parameters, and those parameters types.

答:
Let me rephrase.

What you want is a data exchange format between clients and servers written in C++ that lets you pass around structures known to both sides in an efficient and easy to process way, that hopefully lets you be upwards compatible so that you can upgrade server and client separately.

If so then http://code.google.com/p/protobuf/ is Google's solution for this exact problem, used extensively internally.

ContentLicense: CC BY-SA 3.0

Title: Parameters Framework for C++

Body:
I'm trying to find a parameters framework in C++ to synchronize parameters and variant types between a client/server.  I've tried googling around, but I think I don't have the right search terms.

Example: An object on the server could have the following parameters defined and mapped to the member variables:

"name":  std::string,
"alpha": float,
"mask":  uint

Where these parameters could then be queried by the client and their values adjusted.

Is there something similar to this that exists in the open source world?

Edit for clarification:

The server I've created is a video application, where a video is displayed with N number of filters.  The filters have N number of parameters, and are of different types.  I want the client to be able to query for: # of filters, the filter parameters, and those parameters types.


问:
Put items in list box- What does it mean to say "opt as opt for opt in months" in Angularjs?
https://angularjsaz.blogspot.com/2015/09/tutorial-28-angularjs-listbox-example.html

That shows:

<select style="width: 100%;" size="7" ng-model="currentItems" multiple
         ng-multiple="true"
         ng-options="opt as opt for opt in months">
</select>
```

<p>This works. I want to understand what does this statement do: <strong>opt as opt for opt in months</strong></p>

<p>I also know that <strong>ng-repeat</strong> takes <strong>car in cars</strong>. Why can't I use such a thing here?</p>

<p>In my case, cars was: </p>

```cars = [
    {make: 'Mazda', model: 'Miata', year: 2001},
    {make: 'Toyota', model: 'Prius', year: 2013},
]
```

<p>In their case, months is:</p>

```months = ['January','February','March','April']
```

答:
I also know that ng-repeat takes car in cars. Why can't I use such a thing here?

Yes, one can use ng-repeat to generate options:

<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  <option ng-repeat="option in data.availableOptions" value="{{option.id}}">
    {{option.name}}
  </option>
</select>
```

For more information, see

AngularJS <select> Directive API Reference — Using ngRepeat to generate <select> options

Body:
https://angularjsaz.blogspot.com/2015/09/tutorial-28-angularjs-listbox-example.html

That shows:

<select style="width: 100%;" size="7" ng-model="currentItems" multiple
         ng-multiple="true"
         ng-options="opt as opt for opt in months">
</select>

This works. I want to understand what does this statement do: opt as opt for opt in months

I also know that ng-repeat takes car in cars. Why can't I use such a thing here?

In my case, cars was:

cars = [
    {make: 'Mazda', model: 'Miata', year: 2001},
    {make: 'Toyota', model: 'Prius', year: 2013},
]

In their case, months is:

months = ['January','February','March','April']

Body:
I also know that ng-repeat takes car in cars. Why can't I use such a thing here?

Yes, one can use ng-repeat to generate options:

<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  <option ng-repeat="option in data.availableOptions" value="{{option.id}}">
    {{option.name}}
  </option>
</select>

For more information, see

AngularJS <select> Directive API Reference — Using ngRepeat to generate <select> options


问:
Two dimensional product flavors, Android studio?
In my game I have the two different configurations: 1- Characters 2-Markets. Each character represents a cartoon character and each market represents a local market to use their billing/advertising capabilities.

I have 20 characters and 4 markets. Both characters and markets need their own set of configuration in code and xml files.

The method I have implemented to manage this situation is to use one flavor per character per market in my app-level build.gradle:

```<code>productFlavors {
    character1_market1 {flavorDimensions "in_1"}
    character1_market2 {flavorDimensions "in_2"}
    character1_market3 {flavorDimensions "in_3"}
    character1_market3 {flavorDimensions "in_3"}
    ...
    charactern_market1 {flavorDimensions "in_65"}
    charactern_market2 {flavorDimensions "in_66"}
    charactern_market3 {flavorDimensions "in_67"}
    charactern_market4 {flavorDimensions "in_68"}
}
</code>```

Which clearly adds a lot of boilerplate code and resource to manage. For example for each set of characters I need a custom drawable folder. But now the same drawable folder of each character is going to be repeated for each market variation (4 times). Or I need a custom AndroidManifest.xml file for each market (4 different manifest files). But now I have to repeat these AndroidManifest.xml files for each character-market flavor.

How can I manage this in a more efficient way so I can have different set of market configurations and character configurations without having repeated code and resource? The ultimate result I want to reach is at release time, when I choose a flavor concerning a specific character and a specific market, the configuration for each is applied automatically.

答:
You can create different dimension file for each flavor

For Example if you have flavor flavor_a, flavor_b

Create folder inside src folder with flavor name.You already having main folder(it's should contain common files) and you should follow same folder names inside folder flavor_a and flavor_b

dimension path for flavor_a is app/src/flavor_a/res/values/dimens.xml
dimension path for flavor_b is app/src/flavor_b/res/values/dimens.xml

You can follow for all resources for your flavors.

Body:
In my game I have the two different configurations: 1- Characters 2-Markets. Each character represents a cartoon character and each market represents a local market to use their billing/advertising capabilities.

I have 20 characters and 4 markets. Both characters and markets need their own set of configuration in code and xml files.

The method I have implemented to manage this situation is to use one flavor per character per market in my app-level build.gradle:

productFlavors {
    character1_market1 {flavorDimensions "in_1"}
    character1_market2 {flavorDimensions "in_2"}
    character1_market3 {flavorDimensions "in_3"}
    character1_market3 {flavorDimensions "in_3"}
    ...
    charactern_market1 {flavorDimensions "in_65"}
    charactern_market2 {flavorDimensions "in_66"}
    charactern_market3 {flavorDimensions "in_67"}
    charactern_market4 {flavorDimensions "in_68"}
}

Which clearly adds a lot of boilerplate code and resource to manage. For example for each set of characters I need a custom drawable folder. But now the same drawable folder of each character is going to be repeated for each market variation (4 times). Or I need a custom AndroidManifest.xml file for each market (4 different manifest files). But now I have to repeat these AndroidManifest.xml files for each character-market flavor.

How can I manage this in a more efficient way so I can have different set of market configurations and character configurations without having repeated code and resource? The ultimate result I want to reach is at release time, when I choose a flavor concerning a specific character and a specific market, the configuration for each is applied automatically.


问:
How to repeat elements in list n times?
How do I repeat each element of a list n times and form a new list? For example:

```<code>x=[1,2,3,4]
n=3
</code>```

Looking for:

```<code>[1,1,1,2,2,2,3,3,3,4,4,4]
</code>```

答:
Also list comprehension:</p>

```<code>x = [1,2,3,4]
n = 3
result = [i for i in x for j in 1:n]
</code>```

Title: How to repeat elements in list n times?

Body:
How do I repeat each element of a list n times and form a new list? For example:

x=[1,2,3,4]
n=3

Looking for:

[1,1,1,2,2,2,3,3,3,4,4,4]

Body:
Also list comprehension:

x = [1,2,3,4]
n = 3
result = [i for i in x for j in 1:n]


问:
Hide and Show angular 4 component depending on route
Hi there Im not sure if this is possible... basically I want to be able to show a component but only if the route matches and hide a component if the route matches Ive tried this app-header-home shows when the route is '/'which is good but app-header doesnt show at all even when the route inst '/' how can I fix this?

app.component.html

```<code><app-header *ngIf="router.url == '/'"><app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home> //component I want hidden unless url '/'
<router-outlet></router-outlet>
<app-footer></app-footer>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';

  constructor(
    private router: Router
  ) {

  }
}
</code>```

Thanks

答:
This is in reference to the comment posted by SUNIL JADHAV. Instead of exposing the router handle on the templates we can define it inside a function and call it in the template.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {

  constructor(
    private router: Router,
  ) {}

  ngOnInit() {
  }

  /**
   * Check if the router url contains the specified route
   *
   * @param {string} route
   * @returns
   * @memberof MyComponent
   */
  hasRoute(route: string) {
    return this.router.url.includes(route);
  }
}

```

<p>Then in the html file we can use it like so</p>

<pre class="lang-html prettyprint-override"><code><!-- First view -->
<div *ngIf="hasRoute('home')">
    First View
</div>

<!-- Second view activated when the route doesn't contain the home route -->
<div *ngIf="!hasRoute('home')">
    Second View
</div>
</code>```

Body:
Hi there Im not sure if this is possible... basically I want to be able to show a component but only if the route matches and hide a component if the route matches Ive tried this app-header-home shows when the route is '/'which is good but app-header doesnt show at all even when the route inst '/' how can I fix this?

app.component.html

<app-header *ngIf="router.url == '/'"><app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home> //component I want hidden unless url '/'
<router-outlet></router-outlet>
<app-footer></app-footer>

app.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';

  constructor(
    private router: Router
  ) {

  }
}

Thanks

Body:
This is in reference to the comment posted by SUNIL JADHAV. Instead of exposing the router handle on the templates we can define it inside a function and call it in the template.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {

  constructor(
    private router: Router,
  ) {}

  ngOnInit() {
  }

  /**
   * Check if the router url contains the specified route
   *
   * @param {string} route
   * @returns
   * @memberof MyComponent
   */
  hasRoute(route: string) {
    return this.router.url.includes(route);
  }
}

Then in the html file we can use it like so

<!-- First view -->
<div *ngIf="hasRoute('home')">
    First View
</div>

<!-- Second view activated when the route doesn't contain the home route -->
<div *ngIf="!hasRoute('home')">
    Second View
</div>


问:
friendly_id gem, smaller hash?
Given that my slug candidate is my title, and it is already used, the slug will return something like: my-title-49c9938b-ece5-4175-a4a4-0bb2b0f26a27

Is it possible to have friendly_id return a smaller hash? Like: my-title-705d62eea60a

答:
In that case you can create your own method, which you can pass then to friendly_id. There you can define what are going to be the combinations that FriendlyId will use in order to assign a unique identifier to your record as a slug.

For example:

```<code>friendly_id :column_candidates, use: :slugged

def column_candidates
  [
    :name,
    [:name, :another_column],
    [...more columns combinated as a fallback]
  ]
end
</code>```

If FriendlyId can't create a unique record (by slug) after every combination of columns in column_candidates is evaluated, then it's going to append a UUID anyway.

You're free to add the objects you want to column_candidates, being strings, procs, lambdas or symbols. Also the method name doesn't have to be exactly that, you can modify it as needed.

As a last resource, and if a unique identifier can't be created, you can rely on creating your own short and always able to not be unique hash using Digest::SHA1:

```<code>...
[-> { Digest::SHA1.hexdigest(name).chars.sample(6).join }]
</code>```

Title: friendly_id gem, smaller hash?

Body:
In that case you can create your own method, which you can pass then to friendly_id. There you can define what are going to be the combinations that FriendlyId will use in order to assign a unique identifier to your record as a slug.

For example:

friendly_id :column_candidates, use: :slugged

def column_candidates
  [
    :name,
    [:name, :another_column],
    [...more columns combinated as a fallback]
  ]
end

If FriendlyId can't create a unique record (by slug) after every combination of columns in column_candidates is evaluated, then it's going to append a UUID anyway.

You're free to add the objects you want to column_candidates, being strings, procs, lambdas or symbols. Also the method name doesn't have to be exactly that, you can modify it as needed.

As a last resource, and if a unique identifier can't be created, you can rely on creating your own short and always able to not be unique hash using Digest::SHA1:

...
[-> { Digest::SHA1.hexdigest(name).chars.sample(6).join }]


问:
Convert complex string to array, multiple times by multiple delimiters
I have a string

```<code>Label 1|80|default
Label 2|100|default
---
Frontend|80|red
Backend|20|red
---
Another Item 1|20|blue
Another Item 2|20|blue
-
And another Item|20|blue
</code>```

which should be converted to the following array

```<code>Array
(
[0] => Array
    (
        [items] => Array
            (
                [0] => Array
                    (
                        [label] => Label 1
                        [value] => 80
                        [color] => default
                    )

                [1] => Array
                    (
                        [label] => Label 2
                        [value] => 100
                        [color] => default
                    )

            )

    )

[1] => Array
    (
        [items] => Array
            (
                [0] => Array
                    (
                        [label] => Frontend
                        [value] => 80
                        [color] => red
                    )

                [1] => Array
                    (
                        [label] => Backend
                        [value] => 20
                        [color] => red
                    )

            )

    )

[2] => Array
    (
        [items] => Array
            (
                [0] => Array
                    (
                        [label] => And another Item
                        [value] => 20
                        [color] => blue
                    )

            )

    )
)
</code>```

to be converted into json:

```<code>[{"items":[{"label":"Label 1","value":"80","color":"default"},{"label":"Label 2","value":"100","color":"default"}]},{"items":[{"label":"Frontend","value":"80","color":"red"},{"label":"Backend","value":"20","color":"red"}]},{"items":[{"label":"And another Item","value":"20","color":"blue"}]}]
</code>```

Currently, my way of doing that string splitting to multiple arrays seems a bit complicated to me. At least, it is hard to read.

```<code>protected function convertPartsToObject($parts): array
{
    $return = [];
    $arr1 = explode("---", trim($parts));
    foreach ($arr1 as $arr1Item) {
        $arr2 = explode("-", trim($arr1Item));
        foreach ($arr2 as $arr2Item) {
            $arr3 = explode("\n", trim($arr2Item));
            $group = [];
            foreach ($arr3 as $arr3Item) {
                $arr4 = explode("|", trim($arr3Item));
                $item = [
                    'label' => $arr4[0],
                    'value' => $arr4[1],
                    'color' => $arr4[2]
                ];
                $group['items'][] = $item;
            }
        }
        $return[] = $group;
    }
    return $return;
}
</code>```

Question:

Is there a better / more readable way to convert strings by multiple delimiters to an associative array? Maybe with a nested regex?

Background, just as an info:
This is part of a content management system, where I need some data as json in frontend (for react). And I don't want the editors to learn the json syntax...

答:
This is an alternative to your current code.  Instead of the nested explode() it just splits the input into lines and then processes the lines.  For --- it just adds the current data into the result, - removes the current stored data(not sure if it should), else it extracts the data (I've used the ability to explode to an associative array as a shorthand, depends if you like it or not you can use your current method)...

```<code>function convertPartsToObject ( $parts ) : array {
    $return = [];
    $buffer = [];
    foreach ( explode( PHP_EOL, $parts ) as $line ) {
        if ( trim($line) == "---" ) {
            $return[]['items'] = $buffer;
            $buffer =  [];
        }
        elseif ( trim($line) == "-" ) {
            $buffer = [];
        }
        else    {
            [$arr4['label'], $arr4['value'], $arr4['color']] = explode("|", trim($line));
            $buffer[] = $arr4;
        }
    }
    // Add last items
    $return[]['items'] = $buffer;

    return $return;
}
</code>```

Body:
I have a string

Label 1|80|default
Label 2|100|default
---
Frontend|80|red
Backend|20|red
---
Another Item 1|20|blue
Another Item 2|20|blue
-
And another Item|20|blue

which should be converted to the following array

Array
(
[0] => Array
    (
        [items] => Array
            (
                [0] => Array
                    (
                        [label] => Label 1
                        [value] => 80
                        [color] => default
                    )

                [1] => Array
                    (
                        [label] => Label 2
                        [value] => 100
                        [color] => default
                    )

            )

    )

[1] => Array
    (
        [items] => Array
            (
                [0] => Array
                    (
                        [label] => Frontend
                        [value] => 80
                        [color] => red
                    )

                [1] => Array
                    (
                        [label] => Backend
                        [value] => 20
                        [color] => red
                    )

            )

    )

[2] => Array
    (
        [items] => Array
            (
                [0] => Array
                    (
                        [label] => And another Item
                        [value] => 20
                        [color] => blue
                    )

            )

    )
)

to be converted into json:

[{"items":[{"label":"Label 1","value":"80","color":"default"},{"label":"Label 2","value":"100","color":"default"}]},{"items":[{"label":"Frontend","value":"80","color":"red"},{"label":"Backend","value":"20","color":"red"}]},{"items":[{"label":"And another Item","value":"20","color":"blue"}]}]

Currently, my way of doing that string splitting to multiple arrays seems a bit complicated to me. At least, it is hard to read.

protected function convertPartsToObject($parts): array
{
    $return = [];
    $arr1 = explode("---", trim($parts));
    foreach ($arr1 as $arr1Item) {
        $arr2 = explode("-", trim($arr1Item));
        foreach ($arr2 as $arr2Item) {
            $arr3 = explode("\n", trim($arr2Item));
            $group = [];
            foreach ($arr3 as $arr3Item) {
                $arr4 = explode("|", trim($arr3Item));
                $item = [
                    'label' => $arr4[0],
                    'value' => $arr4[1],
                    'color' => $arr4[2]
                ];
                $group['items'][] = $item;
            }
        }
        $return[] = $group;
    }
    return $return;
}

Question:

Is there a better / more readable way to convert strings by multiple delimiters to an associative array? Maybe with a nested regex?

Background, just as an info:
This is part of a content management system, where I need some data as json in frontend (for react). And I don't want the editors to learn the json syntax...

Body:
This is an alternative to your current code.  Instead of the nested explode() it just splits the input into lines and then processes the lines.  For --- it just adds the current data into the result, - removes the current stored data(not sure if it should), else it extracts the data (I've used the ability to explode to an associative array as a shorthand, depends if you like it or not you can use your current method)...

function convertPartsToObject ( $parts ) : array {
    $return = [];
    $buffer = [];
    foreach ( explode( PHP_EOL, $parts ) as $line ) {
        if ( trim($line) == "---" ) {
            $return[]['items'] = $buffer;
            $buffer =  [];
        }
        elseif ( trim($line) == "-" ) {
            $buffer = [];
        }
        else    {
            [$arr4['label'], $arr4['value'], $arr4['color']] = explode("|", trim($line));
            $buffer[] = $arr4;
        }
    }
    // Add last items
    $return[]['items'] = $buffer;

    return $return;
}


问:
cannot import name 'HTMLField' from 'tinymce'
I am getting below error message at the time of makemigrations. Can anybody please suggest.

from tinymce import HTMLField

ImportError: cannot import name 'HTMLField' from 'tinymce' (F:\Blog\bootstrap-blog-1-2-1\distribution\env\lib\site-packages\tinymce__init__.py)]

答:
if this is not working then just replace this line

from tinymce import HTMLField

into

from tinymce.models import HTMLField

and it will be work fine...


问:
Problems using Common LISP running a hill-climbing search
This is code from my book that I need to use to run a hill-climb search using our predefined nodes. I was able to run a few other search functions successfully such as Best-first-- (which "looks" similar). Upon running this hill-climb search, it failed to run. I'm new to lisp so I don't understand why this is happening. Just as a side note Im running Allegro CL. The function is below;

```<code>    ;; A simple hill-climbing search example adapted from Winston & Horn

(setf (get 's 'neighbors) '(a b)
      (get 'a 'neighbors) '(s c d)
      (get 'b 'neighbors) '(s e)
      (get 'c 'neighbors) '(a d e)
      (get 'd 'neighbors) '(a c e)
      (get 'e 'neighbors) '(b c)
      (get 'f 'neighbors) '(d))
;; I added this for distance assuming that it uses straight line distance in order to
   search.. not sure if that is correct
(setf (get 's 'distance) 65
      (get 'a 'distance) 50
      (get 'b 'distance) 48
      (get 'c 'distance) 45
      (get 'd 'distance) 30
      (get 'e 'distance) 28
      (get 'f 'distance) 0)

(defun straight-line-distance (node-1 node-2)
    (let ((coordinates-1 (get node-1 'coordinates))
              (coordinates-2 (get node-2 'coordinates)))
           (sqrt (+ (expt (- (first coordinates-1)
                             (first coordinates-2))
                           2)
                     (expt (- (second coordinates-1)
                              (second coordinates-2))
                           2)))))

(defun closerp (path-1 path-2 target-node)
    (< (straight-line-distance (first path-1) target-node)
           (straight-line-distance (first path-2) target-node)))

(defun hill-climb (start finish &optional
                       (queue (list (list start))))
     (cond ((endp queue) nil)
       ((equal finish (first (first queue)))
           (reverse (first queue)))
       (t (hill-climb start finish
                      (append (sort (extend (first queue))
                                   #'(lambda (p1 p2) (closerp p1 p2 finish)))
                              (rest queue))))))

(defun extend (path)
    (print (reverse path))
    (mapcar #'(lambda (new-node) (cons new-node path))
             (remove-if #'(lambda (neighbor) (member neighbor path))
                        (get (first path) 'neighbors))))
</code>```

The function im calling looks like this (hill-climb 's 'd)

The errors that I get are as followed;

```<code>Error: attempt to call `CLOSERP' which is an undefined function.
[condition type: UNDEFINED-FUNCTION]
</code>```

答:
I fixed it by editing the (defun straight-line-distance (node-1 node-2) function. There must have been an error... I rewrote it and used this;

```<code>(defun straight-line-distance (node-1 node-2)
    (let ((coordinates-1 (get node-1 'coordinates))
                (coordinates-2 (get node-2 'coordinates)))
             (sqrt (+ (expt (- (first coordinates-1)
                               (first coordinates-2))
                             2)
                       (expt (- (second coordinates-1)
                                (second coordinates-2))
                             2)))))
</code>```

Body:
This is code from my book that I need to use to run a hill-climb search using our predefined nodes. I was able to run a few other search functions successfully such as Best-first-- (which "looks" similar). Upon running this hill-climb search, it failed to run. I'm new to lisp so I don't understand why this is happening. Just as a side note Im running Allegro CL. The function is below;

    ;; A simple hill-climbing search example adapted from Winston & Horn

(setf (get 's 'neighbors) '(a b)
      (get 'a 'neighbors) '(s c d)
      (get 'b 'neighbors) '(s e)
      (get 'c 'neighbors) '(a d e)
      (get 'd 'neighbors) '(a c e)
      (get 'e 'neighbors) '(b c)
      (get 'f 'neighbors) '(d))
;; I added this for distance assuming that it uses straight line distance in order to
   search.. not sure if that is correct
(setf (get 's 'distance) 65
      (get 'a 'distance) 50
      (get 'b 'distance) 48
      (get 'c 'distance) 45
      (get 'd 'distance) 30
      (get 'e 'distance) 28
      (get 'f 'distance) 0)

(defun straight-line-distance (node-1 node-2)
    (let ((coordinates-1 (get node-1 'coordinates))
              (coordinates-2 (get node-2 'coordinates)))
           (sqrt (+ (expt (- (first coordinates-1)
                             (first coordinates-2))
                           2)
                     (expt (- (second coordinates-1)
                              (second coordinates-2))
                           2)))))

(defun closerp (path-1 path-2 target-node)
    (< (straight-line-distance (first path-1) target-node)
           (straight-line-distance (first path-2) target-node)))

(defun hill-climb (start finish &optional
                       (queue (list (list start))))
     (cond ((endp queue) nil)
       ((equal finish (first (first queue)))
           (reverse (first queue)))
       (t (hill-climb start finish
                      (append (sort (extend (first queue))
                                   #'(lambda (p1 p2) (closerp p1 p2 finish)))
                              (rest queue))))))

(defun extend (path)
    (print (reverse path))
    (mapcar #'(lambda (new-node) (cons new-node path))
             (remove-if #'(lambda (neighbor) (member neighbor path))
                        (get (first path) 'neighbors))))

The function im calling looks like this (hill-climb 's 'd)

The errors that I get are as followed;

Error: attempt to call `CLOSERP' which is an undefined function.
[condition type: UNDEFINED-FUNCTION]

Body:
I fixed it by editing the (defun straight-line-distance (node-1 node-2) function. There must have been an error... I rewrote it and used this;

(defun straight-line-distance (node-1 node-2)
    (let ((coordinates-1 (get node-1 'coordinates))
                (coordinates-2 (get node-2 'coordinates)))
             (sqrt (+ (expt (- (first coordinates-1)
                               (first coordinates-2))
                             2)
                       (expt (- (second coordinates-1)
                                (second coordinates-2))
                             2)))))


问:
How do I populate a dropdown menu based on the user selection in a different dropdown menu in ASP.NET Core MVC?
For example:

Dropdown A lists animal types: mammals, reptiles, fish.
Then dropdown B would list animals available for a selected type.
If you select mammals then dropdown B would show: cat, dog, horse.

This is known as a conditional dropdown or cascading dropdown.

答:
So I've learned that dynamic behaviour, in the sense of interacting with the server without reloading the page, requires the use of javascript. Here's my solution which was cobbled together from multiple examples and tutorials:

Model:

public class MyModel
{
  public string IndependentProperty { get; set; }
  public string DependentProperty { get; set; }
}
```

<p>ViewModel:</p>

<pre class="lang-cs prettyprint-override"><code>public class MyViewModel
{
  public MyModel Model { get; set; }
  public IEnumerable<SelectListItem> IndependentOptions { get; set; }
}
</code>```

View:

@using MyViewModel

<form method="post">
  <select id="independentOption"
    asp-for="Model.IndependentProperty"
    asp-items="Model.IndependentOptions"
    onchange="updateDependentOptions()">
    <option value="" selected="true">Select</option>
  </select>

  <select id="dependentOption"
    asp-for="Model.DependentProperty">
    <option value="" selected="true">Select</option>
  </select>
</form>

```

<p>Controller:</p>

<pre class="lang-cs prettyprint-override"><code>[HttpGet]
public ActionResult Index()
{
  // populate the viewmodel
  return View(viewmodel);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
  // Use model binding to
  // get user input.
  // Then save the changes.
  // Return some action
}

[HttpGet]
public JsonResult GetDependentOptions(string independentOption)
{
  var result = new List<string>();

  result.Add("Select"); // optional

  // logic to populate the dependent dropdown
  // based on the choice made in the independent
  // dropdown.

  return Json(result);
}
</code>```

Body:
So I've learned that dynamic behaviour, in the sense of interacting with the server without reloading the page, requires the use of javascript. Here's my solution which was cobbled together from multiple examples and tutorials:

Model:

public class MyModel
{
  public string IndependentProperty { get; set; }
  public string DependentProperty { get; set; }
}

ViewModel:

public class MyViewModel
{
  public MyModel Model { get; set; }
  public IEnumerable<SelectListItem> IndependentOptions { get; set; }
}

View:

@using MyViewModel

<form method="post">
  <select id="independentOption"
    asp-for="Model.IndependentProperty"
    asp-items="Model.IndependentOptions"
    onchange="updateDependentOptions()">
    <option value="" selected="true">Select</option>
  </select>

  <select id="dependentOption"
    asp-for="Model.DependentProperty">
    <option value="" selected="true">Select</option>
  </select>
</form>

<script type="text/javascript">
  function updateDependentOptions() {
    var independentOption = $('#independentOption').val();

    ajaxCall(
      '/MyController/GetDependentOptions?independentOption=',
      independentOption
    ).done(
      function (response) {
        $('#dependentOption').empty();

        if (response.length > 0) {
          var options = '';

          for (var i = 0; i < response.length; i++) {
            options += '<option value="'
              + response[i] + '">' + response[i] + '</option>';
          }

          $('#dependentOption').append(options);
        }
      }
    );
  }

  function ajaxCall(url, data) {
    return $.ajax({
      url: url + data,
      data: '',
      type: 'GET',
      contentType: 'application/json; charset=utf-8'
    });
  }
</script>

Controller:

[HttpGet]
public ActionResult Index()
{
  // populate the viewmodel
  return View(viewmodel);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
  // Use model binding to
  // get user input.
  // Then save the changes.
  // Return some action
}

[HttpGet]
public JsonResult GetDependentOptions(string independentOption)
{
  var result = new List<string>();

  result.Add("Select"); // optional

  // logic to populate the dependent dropdown
  // based on the choice made in the independent
  // dropdown.

  return Json(result);
}


问:
Django Model with out auto generated id field
 --

basically a "product(Rodamiento)" can have one, none or many "equivalents(Equivalente)"

when I create the "equivalent" class, Django auto generates an "id" field.
¿is there a way to avoid that?, I need to transfer data from another DB, that "id" field makes it harder to do it

I'm using SQLite DB and SQLiteStudio

答:
If you create a new model it by default id field with primary key you just add the another field as primary keyso django not create a id fields with primary key

at list one fields have in model that have a primary key if you not specify any it take id so add another fields with primary key here i give a link to see
auto add id fields

You can create a model without an auto-increment primary key false it may work easy to transfer, but you cannot create one without a primary key.


问:
How to get unsampled data from Google Analytics API in a specific day
I am building a package that uses the Google Analytics API for Python.

But, in severous cases when I have multiple dimensions the extraction by day is sampled.

I know that if I use sampling_level = LARGE will use a sample more accurate.

But, somebody knows if has a way to reduce a request that you can extract one day without sampling?

Grateful

答: there are several tactics of building unsampled reports, most popular is splitting your report into shorter time ranges up to hours. Mark Edmondson did a great work on anti-sampling in his R package so you might find it useful. You may start with this blog post https://code.markedmondson.me/anti-sampling-google-analytics-api/</p>


问:
Convert between UIImage and Base64 string
Does anyone know how to convert a UIImage to a Base64 string, and then reverse it?

I have the below code; the original image before encoding is good, but I only get a blank image after I encode and decode it.

```<code>NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];
</code>```

答:
For the Base64 code like:

"data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAAB9klEQVR42u2YQYorMQxEBbqWQFc36FoG/6pyOpNZ/J20mGGaTiftF2hbLpWU2PnfYX/k55Jl5vhUVTu8luUdaCeFcydejjdwDUyQ5XV2JOcSZnkHZgiejusK51QGycrl2yIR1BwjjKivSFz8YC7fY91GKIj6PL5pp4/wWL54t3MHt/AjFxoJwmkYwosbh6/UEHE817hvi/vGex8gEkTdVRo1/55BM7kjUIgpoMW1DxB6kD+GtCX4PUFws40OwcUm0/lRYjOB3pG9YcguBFQuO0ISJ9UIrUP5CKy/MriXHDkETYmLDax1+RkgWBglQgUyq6T/HCAHBq7iJHd9KWWAlIKoGpiLc6HNDhDkETNYwqeVhym72snKKxA6BJL4UPM5QPYtgGwZeNZ5O0UvgSb0VGdcmVfJCQwQrM+pRiGnYJ497SUlv2NOYfOCX3qU2Equ7W3JAslsN7oDBDWWojcZq+KbEwQRdRYl1wD3ML52rpGc6w24qCXaKh4DRHWJbUPemqtEGyBMKC4Q/QmWiDWzRxkgO1UtSLh3svMaILeDpEGwrwvZ4Bkg9LynK1Y1LJWQdqKGnm3K7VTCz7vS9hIuUyYRd/xKcYRIHGqAViisQ4S/Uozmqo41Pn6bNRI1xS/fk2fMEKpDZYkpjP6B1T0HyN9/Nb+M/AORXDdE4Lb/mQAAAABJRU5ErkJggg=="

Use Swift5.0 code like:

```<code>func imageFromBase64(_ base64: String) -> UIImage? {
    if let url = URL(string: base64), let data = try? Data(contentsOf: url) {
        return UIImage(data: data)
    }
    return nil
}
</code>```

Body:
Does anyone know how to convert a UIImage to a Base64 string, and then reverse it?

I have the below code; the original image before encoding is good, but I only get a blank image after I encode and decode it.

NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];

Body:
For the Base64 code like:

"data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAAB9klEQVR42u2YQYorMQxEBbqWQFc36FoG/6pyOpNZ/J20mGGaTiftF2hbLpWU2PnfYX/k55Jl5vhUVTu8luUdaCeFcydejjdwDUyQ5XV2JOcSZnkHZgiejusK51QGycrl2yIR1BwjjKivSFz8YC7fY91GKIj6PL5pp4/wWL54t3MHt/AjFxoJwmkYwosbh6/UEHE817hvi/vGex8gEkTdVRo1/55BM7kjUIgpoMW1DxB6kD+GtCX4PUFws40OwcUm0/lRYjOB3pG9YcguBFQuO0ISJ9UIrUP5CKy/MriXHDkETYmLDax1+RkgWBglQgUyq6T/HCAHBq7iJHd9KWWAlIKoGpiLc6HNDhDkETNYwqeVhym72snKKxA6BJL4UPM5QPYtgGwZeNZ5O0UvgSb0VGdcmVfJCQwQrM+pRiGnYJ497SUlv2NOYfOCX3qU2Equ7W3JAslsN7oDBDWWojcZq+KbEwQRdRYl1wD3ML52rpGc6w24qCXaKh4DRHWJbUPemqtEGyBMKC4Q/QmWiDWzRxkgO1UtSLh3svMaILeDpEGwrwvZ4Bkg9LynK1Y1LJWQdqKGnm3K7VTCz7vS9hIuUyYRd/xKcYRIHGqAViisQ4S/Uozmqo41Pn6bNRI1xS/fk2fMEKpDZYkpjP6B1T0HyN9/Nb+M/AORXDdE4Lb/mQAAAABJRU5ErkJggg=="

Use Swift5.0 code like:

func imageFromBase64(_ base64: String) -> UIImage? {
    if let url = URL(string: base64), let data = try? Data(contentsOf: url) {
        return UIImage(data: data)
    }
    return nil
}


问:
Retrieving records from other table column
I created a view where there are multiple column. I need to retrieve some data from an external table.

```<code>cte4 as (
SELECT *,
case
    when roadName=roadNameUserData then sec1
else 'x'
end as roadCrossSection1

FROM dbo.roadSectionAndPavementUserData,cte3
    )

--"roadName" is from cte computed column view
--"roadNameUserData" is from other table("dbo.roadSectionAndPavementUserData") where records are to be extracted
--sec1 is the column in table "dbo.roadSectionAndPavementUserData" where the results coming from

-----final view
SELECT roadName,
sum(roadLength) as sumRoadLength,roadCrossSection1

FROM cte4
group by roadName
order by roadName
</code>```

When i execute the query, it came with the following error

"Column 'cte4.roadCrossSection1' is invalid in the select list because
  it is not contained in either an aggregate function or the GROUP BY
  clause."

This is the result after adding additional groupby statement. The correct records are the lesser values of sumRoadLength.

答: Error says if you want roadCrossSection1 in select clause either you have to apply any aggregate function e.g MIN, Max, Sum, Avg on roadCrossSection1 or you have to put it in group by clause because roadCrossSection1 might have multiple values for same road name but at same time you are evaluating only one value for roadLength by calling aggregate function on roadLength</p>

Body:
I created a view where there are multiple column. I need to retrieve some data from an external table.

cte4 as (
SELECT *,
case
    when roadName=roadNameUserData then sec1
else 'x'
end as roadCrossSection1

FROM dbo.roadSectionAndPavementUserData,cte3
    )

--"roadName" is from cte computed column view
--"roadNameUserData" is from other table("dbo.roadSectionAndPavementUserData") where records are to be extracted
--sec1 is the column in table "dbo.roadSectionAndPavementUserData" where the results coming from

-----final view
SELECT roadName,
sum(roadLength) as sumRoadLength,roadCrossSection1

FROM cte4
group by roadName
order by roadName

When i execute the query, it came with the following error

"Column 'cte4.roadCrossSection1' is invalid in the select list because
  it is not contained in either an aggregate function or the GROUP BY
  clause."

This is the result after adding additional groupby statement. The correct records are the lesser values of sumRoadLength.


问:
How to find functions which are not executed?
I have a MS Visual Studio 2005 workspace, all C code. I want to find all the functions in that code, which are not called/executed when a certain test case is executed.

What is the way to get that using

1.) MS VS 2005 itself or MSVC6.0 ?

2.) Using some other tool?

-AD

答:
Assuming your test case is in a VS2005 test project, you should be able to use the 'code coverage' feature.

On the menu choose Test->Edit Test Run Configuration ()

From here select CodeCoverage tab to the left, then check the DLLs or EXEs that contain the code you wish profiled.

Next run your test, and on completion, you should be able to select Test->Windows->Code Coverage

This gives you some metrics on the coverage such as lines executed, and you call also double click entries, to jump in to a file and have onscreen highlighting of the code that was or was note executed

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: MattH


问:
UTF8 Encoding not working within CakePHP Shell
I have a CakePHP site that is working fine (in terms of encoding)...but a shell script is not encoding data correctly when saving data.  The website and shell are using the same connection string...but the UTF8 encoding is not be respected by the shell program. (1 odd thing to note:  if I remove the 'encoding' element from the connection string and run the shell program is saves the data as expected...but I would like to re-use the same connection string).

mysql database:

```<code>CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci
</code>```

cakephp mysql connection string:

```<code>var $default = array(
    'driver' => 'mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'user',
    'password' => 'mypassword',
    'database' => 'dbname',
    'prefix' => '',
            'encoding' => 'utf8'
);
</code>```

答:
in your shell script, try running the following query immediately after the connection:</p>

```<code>SET NAMES 'utf8'
</code>```

Body:
I have a CakePHP site that is working fine (in terms of encoding)...but a shell script is not encoding data correctly when saving data.  The website and shell are using the same connection string...but the UTF8 encoding is not be respected by the shell program. (1 odd thing to note:  if I remove the 'encoding' element from the connection string and run the shell program is saves the data as expected...but I would like to re-use the same connection string).

mysql database:

CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci

cakephp mysql connection string:

var $default = array(
    'driver' => 'mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'user',
    'password' => 'mypassword',
    'database' => 'dbname',
    'prefix' => '',
            'encoding' => 'utf8'
);

Body:
in your shell script, try running the following query immediately after the connection:

SET NAMES 'utf8'


问:
want to create excel file in C# by preserving all rows and columns in text format
I am creating a C# application where data needs to be pasted to an Excel file in text format. I am successfully able to generate the Excel file but I cannot format all the rows and columns to text format.

I tried using this code, but it doesn't work:

```<code>string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
</code>```

Here is my code which generates the Excel file:

```<code>SqlConnection con = new SqlConnection(ConnectionString);
DataSet dt = new DataSet();

SqlDataAdapter sda = new SqlDataAdapter("select * from company where 1=2", con);

con.Open();
sda.Fill(dt);

ViewState["DataTable"] = dt.Tables[0];

GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();

con.Close();

DataTable dta = (DataTable)ViewState["DataTable"];

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=FileFormatforData.xls");
Response.ContentType = "application/vnd.ms-excel";
//string style = @"<style> .textmode { mso-number-format:\@; } </style>"; //format row and cols
//Response.Write(style);
string space = "";

foreach (DataColumn col in dta.Columns)
{
     Response.Write(space + col.ColumnName);
     space = "\t";
}

Response.Write("\n");

int countcolumn;

foreach (DataRow dr in dta.Rows)
{
    space = "";

    for (countcolumn = 0; countcolumn < dta.Columns.Count; countcolumn++)
    {
        Response.Write(space + dr[countcolumn].ToString());
        space = "\t";
    }

    Response.Write("\n");
}

Response.End();
</code>```

Can someone please help me?

Thanks in advance.

答:
Try to use any Excel output library. As an example mine SwiftExcel:</p>

```<code>using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
    int col = 1;
    int row = 1;

    foreach (DataColumn col in dta.Columns)
    {
        ew.Write(col.ColumnName, col++, row);
    }

    foreach (DataRow dr in dta.Rows)
    {
        ++row;
        for (col = 1; col <= dta.Columns.Count; col++)
        {
            ew.Write(dr[col-1].ToString(), col, row);
        }
    }
}
</code>```

Body:
I am creating a C# application where data needs to be pasted to an Excel file in text format. I am successfully able to generate the Excel file but I cannot format all the rows and columns to text format.

I tried using this code, but it doesn't work:

string style = @"";
Response.Write(style);

Here is my code which generates the Excel file:

SqlConnection con = new SqlConnection(ConnectionString);
DataSet dt = new DataSet();

SqlDataAdapter sda = new SqlDataAdapter("select * from company where 1=2", con);

con.Open();
sda.Fill(dt);

ViewState["DataTable"] = dt.Tables[0];

GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();

con.Close();

DataTable dta = (DataTable)ViewState["DataTable"];

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=FileFormatforData.xls");
Response.ContentType = "application/vnd.ms-excel";
//string style = @""; //format row and cols
//Response.Write(style);
string space = "";

foreach (DataColumn col in dta.Columns)
{
     Response.Write(space + col.ColumnName);
     space = "\t";
}

Response.Write("\n");

int countcolumn;

foreach (DataRow dr in dta.Rows)
{
    space = "";

    for (countcolumn = 0; countcolumn < dta.Columns.Count; countcolumn++)
    {
        Response.Write(space + dr[countcolumn].ToString());
        space = "\t";
    }

    Response.Write("\n");
}

Response.End();

Can someone please help me?

Thanks in advance.

Body:
Try to use any Excel output library. As an example mine SwiftExcel:

using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
    int col = 1;
    int row = 1;

    foreach (DataColumn col in dta.Columns)
    {
        ew.Write(col.ColumnName, col++, row);
    }

    foreach (DataRow dr in dta.Rows)
    {
        ++row;
        for (col = 1; col <= dta.Columns.Count; col++)
        {
            ew.Write(dr[col-1].ToString(), col, row);
        }
    }
}


问:
Want to add regex in SQL Server check constraints to input only characters not any number even not include any number in character
I want to add a regex to a SQL Server check constraint to input only characters not any number even not include any number in character. Actually I want to input only [a-zA-Z] without mixing or including any numbers.

Please help anybody to provide that regex.

答:
You can add a CHECK constraint that verifies there are no non-alphabetic characters using:

```<code>CHECK (col NOT LIKE '%[^a-zA-Z]%')
</code>```

This constraint will fail for any value that has a character in it that is not a letter.

Demo on dbfiddle

Note that your column/table/database collation may be case-insensitive (e.g. latin1_swedish_ci) in which case you can get away with

```<code>CHECK (col NOT LIKE '%[^A-Z]%')
</code>```

Body:
You can add a CHECK constraint that verifies there are no non-alphabetic characters using:

CHECK (col NOT LIKE '%[^a-zA-Z]%')

This constraint will fail for any value that has a character in it that is not a letter.

Demo on dbfiddle

Note that your column/table/database collation may be case-insensitive (e.g. latin1_swedish_ci) in which case you can get away with

CHECK (col NOT LIKE '%[^A-Z]%')


问:
azcopy in cloud shell fails attempting to copy source storage account contents to target storage account
error is 'failed to perform copy command due to error: no SAS token or OAuth token is present and the resource is not public'

command is formed per the MS doc page.

azcopy copy "http://source.blob.core.windows.net?sv=2019-02-02&ss=bfqt&srt=sco&sp=rwdlacup&se=2020-02-15T02:43:29Z&st=2020-02-14T18:43:29Z&spr=https&sig=Jojd%2FWIfjCza7yNtkt%2FeaFOepyxaunBnjH6O3xCKOto%3D" "http://target.blob.core.windows.net" --recursive

SAS token was generated within minutes of attempted execution, public access on source storage account is set to container, not private.  Command syntax is identical to that in the MS documentation.

I'm thinking that I have overlooked something basic, probably staring me in the face, anyone see anything obvious?

答:
If you're following this section, then please specify sas token for the target storage url.

Here is the test with the latest version of azcopy v10.3.4.

The command:

```<code>azcopy copy "https://yy7.blob.core.windows.net/?sasToken" "https://yy88.blob.core.windows.net/?sasToken" --recursive
</code>```

The test result:

Body:
If you're following this section, then please specify sas token for the target storage url.

Here is the test with the latest version of azcopy v10.3.4.

The command:

azcopy copy "https://yy7.blob.core.windows.net/?sasToken" "https://yy88.blob.core.windows.net/?sasToken" --recursive

The test result:


问:
How find bin directory in ASP.NET Core 3.1?
My EF project is in one project and my ASP.NET Core project in another project ,

D:\AspProjects\DatabaseHafez>        <=== my ef model is in this folder

D:\AspProjects\Hafez>                <=== my aspnet core 3 is in this folder

so each project has one bin folder.

The below builder(ConfigurationBuilder) should have the path of appsettings.json file for reading connections string.so the below has this path =>

D:\AspProjects\DatabaseHafez\bin\Debug\netcoreapp3.1\appsettings.json

but my appsettins.json file in my asp.net core project so after bulilding is will copy to output folder   =>

D:\AspProjects\Hafez\bin\Debug\netcoreapp3.1\appsettings.json

so How can i find the output folder path?

```<code>public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    AppDbContext IDesignTimeDbContextFactory<AppDbContext>.CreateDbContext(string[] args)
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        IConfigurationRoot configuration = builder.Build();

        var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();

        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));

        var context = new AppDbContext(optionsBuilder.Options);

        context.Database.EnsureCreated();
        return context;
    }
}
</code>```

Now I want to add migrations But I get an error

```<code>D:\AspProjects\DatabaseHafez>dotnet ef migrations add changed98112601

Build started...
Build succeeded.
</code>```

System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'D:\AspProjects\DatabaseHafez\bin\Debug\netcoreapp3.1\appsettings.json'.

at Microsoft.Extensions.Configuration.FileConfigurationProvider.HandleException(ExceptionDispatchInfo info)

  at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)

  at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()

  at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList1 providers)

  at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()

  at DatabaseHafez.AppDbContextFactory.Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory<DatabaseHafez.AppDbContext>.CreateDbContext(String[] args) in D:\AspProjects\DatabaseHafez\AppDbContextFactory.cs:line 27

  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContextFromFactory(Type factory)

  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_1.<FindContextTypes>b__9()

  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func1 factory)

  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)

  at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0()
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'D:\AspProjects\DatabaseHafez\bin\Debug\netcoreapp3.1\appsettings.json'.

Now I want to know how can I find the bin folder of my ASP.NET Core project?

答:
Try to get it line this:

```<code>var runDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
</code>```

GetCurrentDirectory might also work, but there is this bug here: https://github.com/dotnet/project-system/issues/589 so I would avoid it.

Body:
My EF project is in one project and my ASP.NET Core project in another project ,

D:\AspProjects\DatabaseHafez>        <=== my ef model is in this folder

D:\AspProjects\Hafez>                <=== my aspnet core 3 is in this folder

so each project has one bin folder.

The below builder(ConfigurationBuilder) should have the path of appsettings.json file for reading connections string.so the below has this path =>

D:\AspProjects\DatabaseHafez\bin\Debug\netcoreapp3.1\appsettings.json

but my appsettins.json file in my asp.net core project so after bulilding is will copy to output folder   =>

D:\AspProjects\Hafez\bin\Debug\netcoreapp3.1\appsettings.json

so How can i find the output folder path?

public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    AppDbContext IDesignTimeDbContextFactory<AppDbContext>.CreateDbContext(string[] args)
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        IConfigurationRoot configuration = builder.Build();

        var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();

        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));

        var context = new AppDbContext(optionsBuilder.Options);

        context.Database.EnsureCreated();
        return context;
    }
}

Now I want to add migrations But I get an error

D:\AspProjects\DatabaseHafez>dotnet ef migrations add changed98112601

Build started...
Build succeeded.

System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'D:\AspProjects\DatabaseHafez\bin\Debug\netcoreapp3.1\appsettings.json'.

at Microsoft.Extensions.Configuration.FileConfigurationProvider.HandleException(ExceptionDispatchInfo info)

  at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)

  at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()

  at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList1 providers)

  at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()

  at DatabaseHafez.AppDbContextFactory.Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory<DatabaseHafez.AppDbContext>.CreateDbContext(String[] args) in D:\AspProjects\DatabaseHafez\AppDbContextFactory.cs:line 27

  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContextFromFactory(Type factory)

  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_1.<FindContextTypes>b__9()

  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func1 factory)

  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)

  at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0()
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'D:\AspProjects\DatabaseHafez\bin\Debug\netcoreapp3.1\appsettings.json'.

Now I want to know how can I find the bin folder of my ASP.NET Core project?

Body:
Try to get it line this:

var runDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)

GetCurrentDirectory might also work, but there is this bug here: https://github.com/dotnet/project-system/issues/589 so I would avoid it.


问:
Invalid object name 'information_schema.columns' in SQL Server
The following query used to work:

```<code>select * from information_schema.columns where column_name like ...
</code>```

But now it's throwing an error:

```<code>Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'information_schema.columns'.
</code>```

The application was upgraded but the view still has to exist in the database.

答:
Either:

The database has a case-sensitive collation (try all upper case INFORMATION_SCHEMA.COLUMNS)

Or you don't have permission.

Body:
The following query used to work:

select * from information_schema.columns where column_name like ...

But now it's throwing an error:

Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'information_schema.columns'.

The application was upgraded but the view still has to exist in the database.


问:
MongoDB How to replace array item by index
How would I replace a value at a specific index in an array using MongoDB?

Lets say a collection for movie reviews has a rating array with individual numbers and I wanted to replace one with a new rating using only Indexes

let array = [1, 5, 3, 7]

How do I replace 5 with 4? Once again only using Indexes

答:
Suppose, you have a document

```<code>{
    "_id" : 1,
    "array" :  [1, 5, 3, 7]
}
</code>```

then, you can update array value at specific index using dot operator
i.e, array.<index>
with $set operator

```<code>db.collection.update(
  { /*match query*/ },
  { $set: { "array.1": 4 } }  // array.index where index=0,1,2,...
)
</code>```

The Updated Document becomes,

```<code>{
    "_id" : 1,
    "array" :  [1, 4, 3, 7]
}
</code>```

You need to concatenate the index in key. Try this

```<code> { _id: editedObj.id }, // Match id.
{ $set: { [`reviews.${index}`]: editedObj.reviews}})
</code>```

Body:
Suppose, you have a document

{
    "_id" : 1,
    "array" :  [1, 5, 3, 7]
}

then, you can update array value at specific index using dot operator
i.e, array.<index>
with $set operator

db.collection.update(
  { /*match query*/ },
  { $set: { "array.1": 4 } }  // array.index where index=0,1,2,...
)

The Updated Document becomes,

{
    "_id" : 1,
    "array" :  [1, 4, 3, 7]
}

You need to concatenate the index in key. Try this

 { _id: editedObj.id }, // Match id.
{ $set: { [`reviews.${index}`]: editedObj.reviews}})


问:
Python code to check repetition in a string
I'm trying to build logic in programming. I need to write a python function that takes string as input and checks whether any character appears more than once. The function should return True if there are no repetitions and False otherwise. I have searched online and found several examples related to it. I wrote the code and it seemed fine initially but then I realized my mistake and now I'm not getting how should I go about it. Please guide</p>

```<code>def repfree(S):
    for char in S:
        if S.count(char) > 1:
            return True
    return False
</code>```

答:
This should be done using set data structure of python, set is having a property where it will always have unique characters only.</p>

```<code>string="country"
def repetion(string):
    if len(set(string)) == len(string):
       print("string is having unique chars")
    else:
       print("chars are different")
</code>```

Body:
I'm trying to build logic in programming. I need to write a python function that takes string as input and checks whether any character appears more than once. The function should return True if there are no repetitions and False otherwise. I have searched online and found several examples related to it. I wrote the code and it seemed fine initially but then I realized my mistake and now I'm not getting how should I go about it. Please guide

def repfree(S):
    for char in S:
        if S.count(char) > 1:
            return True
    return False

Body:
This should be done using set data structure of python, set is having a property where it will always have unique characters only.

string="country"
def repetion(string):
    if len(set(string)) == len(string):
       print("string is having unique chars")
    else:
       print("chars are different")


问:
How does Spring decide which bean to inject when there is two candidates defined with @Qualifier?
Suppose that I have two beans defined like this:

```<code>@Configuration
public class ConfigurationA {

    @Bean
    @Qualifier("restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}
</code>```

```<code>@Configuration
public class ConfigurationB {

    @Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}
</code>```

When I autowire restTemplate without providing @Qualifier, which bean will be injected? How is it decided?

```<code>@Service
public class someClass {

    @Autowired
    private RestTemplate restTemplate;

}
</code>```

Note:When I test, one of the bean is injected. It didn't lead any exception.

Note2: I know I can use @Qualifier to inject the bean that I want or I can use @Primary to avoid ambiguity. But I just want to understand why it is valid for Spring.

Note3: When I changed the method name in class ConfigurationB to restTemplateB, bean defined in ConfigurationA is injected. Again it didnt' lead any exception.

I tried this in Spring Boot version 1.4.4

答:
Case1: Same method (bean) names in configuration classes.

```<code>@Configuration
public class ConfigurationA {

    @Bean
    @Qualifier("restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

@Configuration
public class ConfigurationB {

    @Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}
</code>```

Result: restTemplate in ConfigrationB is injected. restTemplate in ConfiguratioA is overridden by restTemplate in ConfigurationB as can be found in the logs:

o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition
  for bean 'restTemplate' with a different definition: replacing ...

Important Note: Bean overriding is disabled by default from spring boot version 2.1 (you can check this link)

Case2: Changing method name in ConfigurationB to restTemplateB.

```<code>@Configuration
public class ConfigurationA {

    @Bean
    @Qualifier("restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

@Configuration
public class ConfigurationB {

    @Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplateB() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}
</code>```

Result: Both beans in ConfigurationA an ConfigurationB are created. Bean in ConfigurationA is injected. Because bean name will be used if a by-type autowiring doesn't find a single matching bean. Check this for more information

Body:
Suppose that I have two beans defined like this:

@Configuration
public class ConfigurationA {

    @Bean
    @Qualifier("restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

@Configuration
public class ConfigurationB {

    @Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

When I autowire restTemplate without providing @Qualifier, which bean will be injected? How is it decided?

@Service
public class someClass {

    @Autowired
    private RestTemplate restTemplate;

}

Note:When I test, one of the bean is injected. It didn't lead any exception.

Note2: I know I can use @Qualifier to inject the bean that I want or I can use @Primary to avoid ambiguity. But I just want to understand why it is valid for Spring.

Note3: When I changed the method name in class ConfigurationB to restTemplateB, bean defined in ConfigurationA is injected. Again it didnt' lead any exception.

I tried this in Spring Boot version 1.4.4

Body:
Case1: Same method (bean) names in configuration classes.

@Configuration
public class ConfigurationA {

    @Bean
    @Qualifier("restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

@Configuration
public class ConfigurationB {

    @Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

Result: restTemplate in ConfigrationB is injected. restTemplate in ConfiguratioA is overridden by restTemplate in ConfigurationB as can be found in the logs:

o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition
  for bean 'restTemplate' with a different definition: replacing ...

Important Note: Bean overriding is disabled by default from spring boot version 2.1 (you can check this link)

Case2: Changing method name in ConfigurationB to restTemplateB.

@Configuration
public class ConfigurationA {

    @Bean
    @Qualifier("restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

@Configuration
public class ConfigurationB {

    @Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplateB() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

Result: Both beans in ConfigurationA an ConfigurationB are created. Bean in ConfigurationA is injected. Because bean name will be used if a by-type autowiring doesn't find a single matching bean. Check this for more information


问:
how do i search for part of a string in python
I have someone search a string that is a key in a dictionary and i want to search for it but if he puts only part of the string it dosen't find it.

this is the code:(i already have ometz = 0524667997 in the dictionary)

```<code>everything = {ometz: 0524667997}
pick = raw_input('what are you searching for? ')
if pick == 'l':
    check = raw_input('what is the name? ')
    if check in everything:
        print everything[check]
</code>```

so if i will search 'omet' it won't work

答: Substring checking will not work against dict key.</p>

Body:
I have someone search a string that is a key in a dictionary and i want to search for it but if he puts only part of the string it dosen't find it.

this is the code:(i already have ometz = 0524667997 in the dictionary)

everything = {ometz: 0524667997}
pick = raw_input('what are you searching for? ')
if pick == 'l':
    check = raw_input('what is the name? ')
    if check in everything:
        print everything[check]

so if i will search 'omet' it won't work


问:
sed command is not working properly when using wildcard
I am trying to use 'sed' command to delete the last line of the files that matches the wildcard pattern given as command line argument and the move the file from that directory to the present directory. The code is as follow:

```<code>DIR="/home/usr_name/trash/"
for file in "$@"
    do
        if [ $file != "-h" ] //ignore this line
        then
            temp="$DIR$file"
            sed '$d' "$DIR$file"
            mv $temp .
        fi
    done
</code>```

The code is moving the file but its not executing the 'sed' command to delete the last line. Giving the wildcard as ab* , it gives the following error:

```<code>sed: can't read /home/usr_name/trash/ab*: No such file or directory
</code>```

Help me to figure out this situation.

答:
If you need wildcards, the simplest solution would be to use find:

```<code>find "$DIR" -name "$file" \
   -exec sed -i '$d' {} \;
   -exec mv {} "$DEST" \;
</code>```

-name "$file" - this will tell find to search for files matching the wildcard

-exec sed -i '$d' {} \;- execute sed on each file found {} represents the file

-exec mv {} "$DEST" \; - move the file

note that the order of execs mater, after the move the file will not be available in the old location.

Edit: I initially assumed that the 'ab*' was given as a quoted parameter to the entire script. This answer reminded me of another possibility: you run the script from a directory where there aren't any files starting with 'ab', in which case 'ab*' doesn't get expanded, and mv will work in your script, but sed not (since you quote the "$DIR$file", see the debugging output of bash:

```<code>sorin@testvm ~/tmp $ seq 1 2 > src/ab1
sorin@testvm ~/tmp $ seq 1 4 > src/ab5
sorin@testvm ~/tmp $ seq 1 3 > src/ab3
sorin@testvm ~/tmp $ bash -x test.sh ab*
+ DIR=src/
+ for file in '"$@"'
+ '[' 'ab*' '!=' -h ']'
+ temp='src/ab*'
+ sed '$d' 'src/ab*'
sed: can't read src/ab*: No such file or directory
+ mv src/ab1 src/ab3 src/ab5 .
sorin@testvm ~/tmp $
</code>```

This covers exactly the scenario described in your question.

Body:
I am trying to use 'sed' command to delete the last line of the files that matches the wildcard pattern given as command line argument and the move the file from that directory to the present directory. The code is as follow:

DIR="/home/usr_name/trash/"
for file in "$@"
    do
        if [ $file != "-h" ] //ignore this line
        then
            temp="$DIR$file"
            sed '$d' "$DIR$file"
            mv $temp .
        fi
    done

The code is moving the file but its not executing the 'sed' command to delete the last line. Giving the wildcard as ab* , it gives the following error:

sed: can't read /home/usr_name/trash/ab*: No such file or directory

Help me to figure out this situation.

Body:
If you need wildcards, the simplest solution would be to use find:

find "$DIR" -name "$file" \
   -exec sed -i '$d' {} \;
   -exec mv {} "$DEST" \;

-name "$file" - this will tell find to search for files matching the wildcard

-exec sed -i '$d' {} \;- execute sed on each file found {} represents the file

-exec mv {} "$DEST" \; - move the file

note that the order of execs mater, after the move the file will not be available in the old location.

Edit: I initially assumed that the 'ab*' was given as a quoted parameter to the entire script. This answer reminded me of another possibility: you run the script from a directory where there aren't any files starting with 'ab', in which case 'ab*' doesn't get expanded, and mv will work in your script, but sed not (since you quote the "$DIR$file", see the debugging output of bash:

sorin@testvm ~/tmp $ seq 1 2 > src/ab1
sorin@testvm ~/tmp $ seq 1 4 > src/ab5
sorin@testvm ~/tmp $ seq 1 3 > src/ab3
sorin@testvm ~/tmp $ bash -x test.sh ab*
+ DIR=src/
+ for file in '"$@"'
+ '[' 'ab*' '!=' -h ']'
+ temp='src/ab*'
+ sed '$d' 'src/ab*'
sed: can't read src/ab*: No such file or directory
+ mv src/ab1 src/ab3 src/ab5 .
sorin@testvm ~/tmp $

This covers exactly the scenario described in your question.


问:
(React Navigation 5): Cannot read property 'replace' of undefined
I use version 5 React Navigation.

And according to the React Navigation documentation  I use the replace as below

import { StackActions } from '@react-navigation/native';

navigation.dispatch(
  StackActions.replace('Profile', {
    user: 'jane',
  })
);
```

But I get following error

Cannot read property 'replace' of undefined

答:
Just change StackActions import source

import { StackActions } from "@react-navigation/routers/src/StackRouter";
```

Body:
I use version 5 React Navigation.

And according to the React Navigation documentation  I use the replace as below

import { StackActions } from '@react-navigation/native';

navigation.dispatch(
  StackActions.replace('Profile', {
    user: 'jane',
  })
);

But I get following error

Cannot read property 'replace' of undefined


问:
Creating Facebook share button that is accessibility friendly
Im trying to create a facebook share button for my page that is accessibe by tab-indexing and pressing enter (for accessibility). A lot of the solutions I had created were using javascript and wouldn't load my script until after tabbing out of the share button.

So far I have created this button.

```<code><a tabindex="0" class="fb-share-button" href="javascript:window.location=%22http://www.facebook.com/sharer.php?u=%22+encodeURIComponent(document.location)+%22&t=%22+encodeURIComponent(document.title)" data-layout="button_count">
       <img src="/sites/all/themes/saralee/images/icon-facebook.png" alt="facebook icon">
</a>
</code>```

This almost gives the desired outcome except I need it to open in either a new tab or an iframe. Which I haven't been able to do with keeping a valid url. (since the above button parses the current url). using target="_blank" doesnt work.

答:
Quick Note - The best option would be to build the URL on the server and serve it as part of the HTML, use the JavaScript option below if you are unable to do that for any reason.

All other points other than the URL below are important to make your share 'button' accessible.

Instead of using an inline function on the button, build the URL in a separate JavaScript function and then apply it on document load.

JS

```<code>var URL = "http://www.facebook.com/sharer.php?u=%22+encodeURIComponent(document.location)+%22&t=%22+encodeURIComponent(document.title)";
var elements = document.getElementsByClassName("fb-share-button");
elements[0].setAttribute("href", URL); //using [0] to get first element, would be better to use an ID or simply **build the URL on the server before loading the page** and serve it as part of the HTML.
</code>```

HTML

```<code><a target="_blank" class="fb-share-button" href="fallback URL In Case Of JS Failure" data-layout="button_count">
       <img src="/sites/all/themes/saralee/images/icon-facebook.png" alt=""/>
       <span class="visually-hidden">Share This Page on Facebook (opens in new window)</span>
</a>
</code>```

CSS

```<code>.visually-hidden {
    position: absolute !important;
    height: 1px;
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px, 1px, 1px, 1px);
    white-space: nowrap; /* added line */
}
</code>```

Because you are no longer setting window.location using target="_blank" will work as expected (window.location was overriding the functionality of the link).

Also notice that I removed the tabindex as links are focusable by default (so it isn't needed).

I also changed the alt description to "" and added a 'visually hidden'  containing the purpose of the link.

I have included the CSS to make something 'visually-hidden' by applying that class to an item, as it is a useful tool to have in your accessibility toolkit!

Note how I indicated the link 'opens in a new window' within brackets to let screen readers know the behaviour of this link.

An empty alt tag is used to mark an image as decorative (make sure it is empty and not null, i.e. alt="" NOT alt).

Visually Hidden text is still accessible to screen readers but will not show visually.

Body:
Im trying to create a facebook share button for my page that is accessibe by tab-indexing and pressing enter (for accessibility). A lot of the solutions I had created were using javascript and wouldn't load my script until after tabbing out of the share button.

So far I have created this button.

This almost gives the desired outcome except I need it to open in either a new tab or an iframe. Which I haven't been able to do with keeping a valid url. (since the above button parses the current url). using target="_blank" doesnt work.

Body:
Quick Note - The best option would be to build the URL on the server and serve it as part of the HTML, use the JavaScript option below if you are unable to do that for any reason.

All other points other than the URL below are important to make your share 'button' accessible.

Instead of using an inline function on the button, build the URL in a separate JavaScript function and then apply it on document load.

JS

var URL = "http://www.facebook.com/sharer.php?u=%22+encodeURIComponent(document.location)+%22&#38;t=%22+encodeURIComponent(document.title)";
var elements = document.getElementsByClassName("fb-share-button");
elements[0].setAttribute("href", URL); //using [0] to get first element, would be better to use an ID or simply **build the URL on the server before loading the page** and serve it as part of the HTML.

HTML

<a target="_blank" class="fb-share-button" href="fallback URL In Case Of JS Failure" data-layout="button_count">
       <img src="/sites/all/themes/saralee/images/icon-facebook.png" alt=""/>
       <span class="visually-hidden">Share This Page on Facebook (opens in new window)</span>
</a>

CSS

.visually-hidden {
    position: absolute !important;
    height: 1px;
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px, 1px, 1px, 1px);
    white-space: nowrap; /* added line */
}

Because you are no longer setting window.location using target="_blank" will work as expected (window.location was overriding the functionality of the link).

Also notice that I removed the tabindex as links are focusable by default (so it isn't needed).

I also changed the alt description to "" and added a 'visually hidden' <span> containing the purpose of the link.

I have included the CSS to make something 'visually-hidden' by applying that class to an item, as it is a useful tool to have in your accessibility toolkit!

Note how I indicated the link 'opens in a new window' within brackets to let screen readers know the behaviour of this link.

An empty alt tag is used to mark an image as decorative (make sure it is empty and not null, i.e. alt="" NOT alt).

Visually Hidden text is still accessible to screen readers but will not show visually.


问:
Idiom for handling size_t underflow in loop condition
In C and C++, size_t is an unsigned type that is used for expressing size. It expresses intent and somewhat simplifies range assertions (len < upper_bound vs len >= 0 && len < upper_bound for signed integers).

(In all the examples below len means the length of the array a).

The idiom for a for loop is: for (i = 0; i < len; i++). The idiom for  a backward for loop is for (i = len-1; i >= 0; i--). But having unsigned loop indices introduces subtle bugs, and every so often I mess up the edge cases.

First, the backwards for loop. This code underflows for len=0.

```<code>for (size_t i = len-1; i >= 0; i--) { // Bad: Underflows for len=0
    use(a[i]);
}
</code>```

There's the --> "operator" trick, which looks strange if you're not used to it.

```<code>for (size_t i = len; i--> 0;) {
    use(a[i]);
}
</code>```

You can use a signed type for the loop index variable, but that overflows if len > INT_MAX. Many people and organizations considers that risk so minimal that they just stick to int.

```<code>for (int i = len-1; i >= 0; i--) {  // BAD: overflows for len < INT_MAX
    use(a[i]);
}
</code>```

So I've settled for this construct, since it's closest to the canonical for-loop form and has the simplest expressions.

```<code>for (size_t i = len; i > 0; i--) {
    size_t pos = i-1;
    use(a[pos]);
}
</code>```

My problem iterating from 0 to len-1

That is, looping over the range [0, len-1). This loop underflows when len=0.

```<code>for (size_t i = 0; i < len-1; i++) {   // BAD: Underflows for len=0.
    use(a[i]);
}
</code>```

As for the iterating backwards case, you can use signed integers but that may cause overflows.

```<code>for (int i = 0; i < len-1; i++) {    // BAD: Will overflow if len > INT_MAX
    use(a[i]);
}
</code>```

I tend to add another expression to the loop condition, checking for len > 0, but that feels clumsy.

```<code>for (size_t i = 0; len > 0 && i < len-1; i++) {
    use(a[i]);
}
</code>```

I can add an if statement before the loop, but that also feels clumsy.

Is there a less bulky way of writing a for loop with unsigned index variables looping from 0 to len-1?

答:
There are two cases here.

Iterating forward from 0 to len - 2 inclusive

```<code>for (size_t i = 0; i + 1 < len; ++i) {
    size_t index = i;
    // use index here
}
</code>```

Iterating backward from len - 2 to 0 inclusive

```<code>for (size_t i = len; i > 1; --i) {
    size_t index = i - 2;
    // use index here
}
</code>```

Body:
In C and C++, size_t is an unsigned type that is used for expressing size. It expresses intent and somewhat simplifies range assertions (len < upper_bound vs len >= 0 && len < upper_bound for signed integers).

(In all the examples below len means the length of the array a).

The idiom for a for loop is: for (i = 0; i < len; i++). The idiom for  a backward for loop is for (i = len-1; i >= 0; i--). But having unsigned loop indices introduces subtle bugs, and every so often I mess up the edge cases.

First, the backwards for loop. This code underflows for len=0.

for (size_t i = len-1; i >= 0; i--) { // Bad: Underflows for len=0
    use(a[i]);
}

There's the --> "operator" trick, which looks strange if you're not used to it.

for (size_t i = len; i--> 0;) {
    use(a[i]);
}

You can use a signed type for the loop index variable, but that overflows if len > INT_MAX. Many people and organizations considers that risk so minimal that they just stick to int.

for (int i = len-1; i >= 0; i--) {  // BAD: overflows for len < INT_MAX
    use(a[i]);
}

So I've settled for this construct, since it's closest to the canonical for-loop form and has the simplest expressions.

for (size_t i = len; i > 0; i--) {
    size_t pos = i-1;
    use(a[pos]);
}

My problem iterating from 0 to len-1

That is, looping over the range [0, len-1). This loop underflows when len=0.

for (size_t i = 0; i < len-1; i++) {   // BAD: Underflows for len=0.
    use(a[i]);
}

As for the iterating backwards case, you can use signed integers but that may cause overflows.

for (int i = 0; i < len-1; i++) {    // BAD: Will overflow if len > INT_MAX
    use(a[i]);
}

I tend to add another expression to the loop condition, checking for len > 0, but that feels clumsy.

for (size_t i = 0; len > 0 && i < len-1; i++) {
    use(a[i]);
}

I can add an if statement before the loop, but that also feels clumsy.

Is there a less bulky way of writing a for loop with unsigned index variables looping from 0 to len-1?

Body:
There are two cases here.

Iterating forward from 0 to len - 2 inclusive

for (size_t i = 0; i + 1 < len; ++i) {
    size_t index = i;
    // use index here
}

Iterating backward from len - 2 to 0 inclusive

for (size_t i = len; i > 1; --i) {
    size_t index = i - 2;
    // use index here
}


问:
How to make the cursor in a JTextField span multiple rows in FlowLayout?

How can I make the cursor start at the top left of the JTextField? The text just stays centered when I adjust the height with .setPreferredSize(). Here is the code for the fields and buttons.

```<code>public class GUIWindow extends JFrame{

    private JTextField inputBox = new JTextField(20);
    private JTextField outputBox = new JTextField(20);
    private JButton encodeButton = new JButton("Encode");
    private JButton decodeButton = new JButton("Decode");

    public GUIWindow(){
        JPanel mainPanel = new JPanel(new FlowLayout());
        outputBox.setPreferredSize(new Dimension(80, 80));
        inputBox.setPreferredSize(new Dimension(80, 80));
        outputBox.setEditable(false);
        mainPanel.add(inputBox);
        mainPanel.add(encodeButton);
        mainPanel.add(decodeButton);
        mainPanel.add(outputBox);
        Container container = getContentPane();
        container.add(mainPanel);
    }
}
</code>```

答: If you are looking for a multiline control then you should use a JTextArea instead of JTextField.</p>

Body:
How can I make the cursor start at the top left of the JTextField? The text just stays centered when I adjust the height with .setPreferredSize(). Here is the code for the fields and buttons.

public class GUIWindow extends JFrame{

    private JTextField inputBox = new JTextField(20);
    private JTextField outputBox = new JTextField(20);
    private JButton encodeButton = new JButton("Encode");
    private JButton decodeButton = new JButton("Decode");

    public GUIWindow(){
        JPanel mainPanel = new JPanel(new FlowLayout());
        outputBox.setPreferredSize(new Dimension(80, 80));
        inputBox.setPreferredSize(new Dimension(80, 80));
        outputBox.setEditable(false);
        mainPanel.add(inputBox);
        mainPanel.add(encodeButton);
        mainPanel.add(decodeButton);
        mainPanel.add(outputBox);
        Container container = getContentPane();
        container.add(mainPanel);
    }
}


问:
Autowire not working with controller Spring Boot
Whenever I am trying to autowire a custom repository implementing JPA Repository within my controller class it is unable to do so and throwing a no bean def found error whereas if I am doing the same with any Service Class its working fine. Can anyone please explain to me why is it so?</p>

```<code>
Spring Boot
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2020-02-15 13:01:50.169 ERROR 16304 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field customerRepo in Controllers.MainController required a bean of type 'Repository.CustomerRepo' that could not be found.

    The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)

    Action:

    Consider defining a bean of type 'Repository.CustomerRepo' in your configuration.

    ```
    @SpringBootApplication
    @ComponentScan(basePackages = "Controllers")
    public class DemoApplication {

        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }

    }
    ``````````````````
    @RestController
    @RequestMapping("/")
    public class MainController {

        @Autowired
        private CustomerRepo customerRepo;

        @RequestMapping(value = "/home", method = RequestMethod.GET)
        public String homePage() {
            Customer testCustomer = new Customer();
            testCustomer.setFirstName("csdcsdccs");
            testCustomer.setLastName("csdcsdccs");
            testCustomer.setMiddleName("csdcsdccs");
            testCustomer.setAddressLine("csdcsdccs");
            testCustomer.setCountry("csdcsdccs");
            testCustomer.setPincode(713201);
            testCustomer.setState("csdcsdccs");
            testCustomer.setDateOfBirth(new Date(2019, 5, 13));

            customerRepo.save(testCustomer);

            return "inserted";
        }
    }

    `````````````
    @Repository
    public interface CustomerRepo extends CrudRepository<Customer, Long> {

    }
    ``````````````````````````

</code>```

答:
Spring application is unable to scan the repository. Could you please check if the repository is defined defined under the base package otherwise add Repository repository package also in @ComponentScan there. </p>

```<code>@SpringBootApplication
@ComponentScan(basePackages = {"Controllers","Repository"})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
</code>```

Body:
Whenever I am trying to autowire a custom repository implementing JPA Repository within my controller class it is unable to do so and throwing a no bean def found error whereas if I am doing the same with any Service Class its working fine. Can anyone please explain to me why is it so?

Spring Boot
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2020-02-15 13:01:50.169 ERROR 16304 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field customerRepo in Controllers.MainController required a bean of type 'Repository.CustomerRepo' that could not be found.

    The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)

    Action:

    Consider defining a bean of type 'Repository.CustomerRepo' in your configuration.

    ```
    @SpringBootApplication
    @ComponentScan(basePackages = "Controllers")
    public class DemoApplication {

        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }

    }
    ``````````````````
    @RestController
    @RequestMapping("/")
    public class MainController {

        @Autowired
        private CustomerRepo customerRepo;

        @RequestMapping(value = "/home", method = RequestMethod.GET)
        public String homePage() {
            Customer testCustomer = new Customer();
            testCustomer.setFirstName("csdcsdccs");
            testCustomer.setLastName("csdcsdccs");
            testCustomer.setMiddleName("csdcsdccs");
            testCustomer.setAddressLine("csdcsdccs");
            testCustomer.setCountry("csdcsdccs");
            testCustomer.setPincode(713201);
            testCustomer.setState("csdcsdccs");
            testCustomer.setDateOfBirth(new Date(2019, 5, 13));

            customerRepo.save(testCustomer);

            return "inserted";
        }
    }

    `````````````
    @Repository
    public interface CustomerRepo extends CrudRepository<Customer, Long> {

    }
    ``````````````````````````

Body:
Spring application is unable to scan the repository. Could you please check if the repository is defined defined under the base package otherwise add Repository repository package also in @ComponentScan there.

@SpringBootApplication
@ComponentScan(basePackages = {"Controllers","Repository"})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}


问:
vim set ex range to current paragraph without visual/mark etc
I'm wanting to apply a command to the currect paragraph but I'd like to automate it so I don't need to visually select/mark the paragraph before-hand.

I want something like

```<code>:{,}s/this isn't/important/g
</code>```

to specify the range to apply 's' (in this case) to.

Eventually I'm wanting to using range-accepting-commands to reformat a paragraph.

Does anyone know how to do this? Is there a better approach that I'm missing?

答:
If you want to exclude the first and last empty lines around the paragraph — just like the text-object "v_ip" — you can use this:

```<code>:'{+1,'}-1
</code>```

For something like :sort, this will not add the last line to the top. I use this mapping to sort the current paragraph by length:

```<code>nn <leader>s mx:'{+1,'}-1!awk '{print length(), $0\|"sort -n"}'\|cut -d' ' -f2-<cr>`x
</code>```

Body:
I'm wanting to apply a command to the currect paragraph but I'd like to automate it so I don't need to visually select/mark the paragraph before-hand.

I want something like

:{,}s/this isn't/important/g

to specify the range to apply 's' (in this case) to.

Eventually I'm wanting to using range-accepting-commands to reformat a paragraph.

Does anyone know how to do this? Is there a better approach that I'm missing?

Body:
If you want to exclude the first and last empty lines around the paragraph — just like the text-object "v_ip" — you can use this:

:'{+1,'}-1

For something like :sort, this will not add the last line to the top. I use this mapping to sort the current paragraph by length:

nn <leader>s mx:'{+1,'}-1!awk '{print length(), $0\|"sort -n"}'\|cut -d' ' -f2-<cr>`x


答:
How about

for (size_t i = 0; i+1 < len; i++) {
    use(a[i]);
}
```

Title: Idiom for handling size_t underflow in loop condition