问:
How to remove spaces in a string?
I have code where the user inputs a string and I need the spaces to be removed in the middle of multiple words.

Here is what I have:

```<code>`System.out.println("Enter your choice:\n"
            + "Type 'Player Name' to search for a player based off their name.\n"
            + "Type 'Player School' to search for a player based off their school\n"
            + "Type 'Team Location' to search for a team based off their location.\n"
            + "Type 'Team Mascot' to search for a team based off their mascot.\n");
    String choice = input.next();
    choice = choice.replaceAll("\\s+", "");
    System.out.println(choice);
    switch(choice.toLowerCase()){
    case "playername":
        searchPlayer();
        break;
    case "playerschool":
        searchSchool();
        break;
    case "teamlocation":
        searchLocation();
        break;
    case "teammascot":
        searchMascot();
        break;
    default:
        System.out.println("Yet to be implemented");
        break;
    }`
</code>```

This gives me no errors however it always returns the default case when I include spaces.
I put the line to print the choice to see why it wasn't working and when I run this it only keeps the first word.
For example if I type "Player Name" it will return "player".

答: Change input.next() with input.nextLine() to take whole line of input into consideration. input.next() saves an input to the place of delimiter, which by default is one or more spaces.

Title: How to remove spaces in a string?

Body:
I have code where the user inputs a string and I need the spaces to be removed in the middle of multiple words.

Here is what I have:

`System.out.println("Enter your choice:\n"
            + "Type 'Player Name' to search for a player based off their name.\n"
            + "Type 'Player School' to search for a player based off their school\n"
            + "Type 'Team Location' to search for a team based off their location.\n"
            + "Type 'Team Mascot' to search for a team based off their mascot.\n");
    String choice = input.next();
    choice = choice.replaceAll("\\s+", "");
    System.out.println(choice);
    switch(choice.toLowerCase()){
    case "playername":
        searchPlayer();
        break;
    case "playerschool":
        searchSchool();
        break;
    case "teamlocation":
        searchLocation();
        break;
    case "teammascot":
        searchMascot();
        break;
    default:
        System.out.println("Yet to be implemented");
        break;
    }`

This gives me no errors however it always returns the default case when I include spaces.
I put the line to print the choice to see why it wasn't working and when I run this it only keeps the first word.
For example if I type "Player Name" it will return "player".


来源: stackexchange

问:
SQL query to select dates between two dates
I have a start_date and end_date. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.

```<code>select Date,TotalAllowance
from Calculation
where EmployeeId=1
  and Date between 2011/02/25 and 2011/02/27
</code>```

Here Date is a datetime variable.

答:
we can use between to show two dates data but this will search the whole data and compare so it will make our process slow for huge data, so i suggest everyone to use datediff:

```<code>qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "
</code>```

here calender is the Table, dt as the starting date variable and dt2 is the finishing date variable.

ContentLicense: CC BY-SA 3.0

Body:
I have a start_date and end_date. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.

select Date,TotalAllowance
from Calculation
where EmployeeId=1
  and Date between 2011/02/25 and 2011/02/27

Here Date is a datetime variable.

Body:
we can use between to show two dates data but this will search the whole data and compare so it will make our process slow for huge data, so i suggest everyone to use datediff:

qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "

here calender is the Table, dt as the starting date variable and dt2 is the finishing date variable.


问:
Run mysql script through docker?

Hi there,
I'm trying to create a docker container that will run a mysql script which generates a database and then table.  My Dockerfile looks like this:

```<code>FROM mysql:latest

WORKDIR /

ADD . /

EXPOSE 3306

CMD mysql -u "root" -proot < "schema.sql"
</code>```

I create the image through this:

```<code>docker build -t database .
</code>```

And then I run it through this:

```<code>docker run -d -p 3306:3306 database
</code>```

At this point the script should be run- however instead I just get this random line in the terminal:

```<code> 0b2503b42482a4fa840351925845392e1abdf6022b23447187ff49ed4f0fa05b
</code>```

Grateful for your help!

答:
don't worry, this is 0b2503b42482a4fa840351925845392e1abdf6022b23447187ff49ed4f0fa05b ID from container.

You can use id to stop or check status or collect information of container. if you want check your command is work or not, you can run with this command docker run -it database bash or docker run -it database sh

Hope this helps.

Best Regards

Title: Run mysql script through docker?

Body:
Hi there,
I'm trying to create a docker container that will run a mysql script which generates a database and then table.  My Dockerfile looks like this:

FROM mysql:latest

WORKDIR /

ADD . /

EXPOSE 3306

CMD mysql -u "root" -proot < "schema.sql"

I create the image through this:

docker build -t database .

And then I run it through this:

docker run -d -p 3306:3306 database

At this point the script should be run- however instead I just get this random line in the terminal:

 0b2503b42482a4fa840351925845392e1abdf6022b23447187ff49ed4f0fa05b

Grateful for your help!


问:
How do I merge two csv files based on the words in a given list?
I have two csv files, each of them are in this format,

```<code>file1
zip     name    score
23431   david   12
23231   rob     45
33441   hary    23
98901   rgrg    55

file2
zip1    name1   score1
23433   david   12
23245   stel    45
33478   hary    23
98988   rob     55
12121   jass    33
</code>```

and I have a list that has the names, like this

```<code>lista = ['harry', 'rob', 'wine', 'david', 'jass']
</code>```

The final csv file should look like this:

```<code>name    zip     score       zip1     score1
harry   x       x           x           x
rob     23231   45          98988       55
wine    x       x           x           x
david   23431   12          23433       12
jass    x       x           12121       33
</code>```

that means, if any name from the list lies in either of the csv files, than we should include it in the new csv file along with its zip and score. Otherwise we should print 'x' in it.

This is what I have done so far:

```<code>import csv
with open('file1.csv', 'r') as input1, open('file2.csv', 'r') as input2, open('merge_final.csv', 'w') as output:
    writer = csv.writer(output)
    reader1 = csv.reader(input1)
    eader2 = csv.reader(input2)

    lista = ['harry', 'rob', 'wine', 'david', 'jass']
    writer.writerow(['name','zip','score','zip1','score'])

        for i in lista:
            for row in list(reader1):
                rev = row[1]
                if i in rev:
                    score = row[2]
                    zip = row[0]
                else:
                    score = 'x'
                    zip = 'x'
            for row in list(reader2):
                rev = row[1]
                if i in rev:
                    score1 = row[2]
                    zip1 = row[0]
                else:
                    score1 = 'x'
                    zip1 = 'x'
            writer.writerow([i, score, zip, score1, zip1])
</code>```

This code is not working as expected. This is the output I got using this code.

```<code>name    zip     score       zip1     score1
harry   x       x           x           x
rob     x      x            x            x
wine    x       x           x           x
david   x       x           x           x
jass    x       x           x           x
</code>```

Even thought there are many common words, only 'x' gets printed in the final merged csv file. I think the problem is with the loops. But, I don't seem to figure out the issue.

答:
First, the first call of list(readerX) exhausts the iterator that is the file handle.

Secondly, rev is supposed to be the name already, so check for equality not contains: if name == rev.

Thirdly, you'd mostly get 'x's except for the last names in each file since you iterate the files to the end and only the last row will really matter. You should break the inner loops as soon as you find a name, but set the default values only after you iterated the entire file without finding the name.

Also, it is very bad performance-wise to repeatedly iterate both files. You better load the two files into a permanent data structure with faster lookup like a nested dict with names as keys:

```<code>d1 = {row[1]: {'zip': row[0], 'score': row[2]} for row in reader1}
d2 = {row[1]: {'zip': row[0], 'score': row[2]} for row in reader2}
#   {'david': {'zip': 23431, 'score: 12, ...}

for name in lista:
    if name in d1 or name in d2:
        writer.writerow([
            name,
            d1.get(name, {}).get('zip', 'x'),
            d1.get(name, {}).get('score', 'x'),
            d2.get(name, {}).get('zip', 'x'),
            d2.get(name, {}).get('score', 'x'),
        ])
</code>```

To make your own approach work, change as follows, but note that this has terrible performance for larger data because of the nested loops:

```<code># next(reader1)  # skip the header line if necessary
lst1 = list(reader1)  # load all the data into a list beforehand ...
for i in lista:
    for row in lst1:  # ... that you can repeatedly iterate
        rev = row[1]
        if i == rev:  # compare for equality
            score = row[2]
            zip = row[0]
            break  # <- you found the name, so end the loop!
    else:  # note the indentation: this is a for-else-loop, not an if-else
        # the else-part is only executed if the for loop was NOT break'ed
        score = 'x'
        zip = 'x'
</code>```

Body:
I have two csv files, each of them are in this format,

file1
zip     name    score
23431   david   12
23231   rob     45
33441   hary    23
98901   rgrg    55

file2
zip1    name1   score1
23433   david   12
23245   stel    45
33478   hary    23
98988   rob     55
12121   jass    33

and I have a list that has the names, like this

lista = ['harry', 'rob', 'wine', 'david', 'jass']

The final csv file should look like this:

name    zip     score       zip1     score1
harry   x       x           x           x
rob     23231   45          98988       55
wine    x       x           x           x
david   23431   12          23433       12
jass    x       x           12121       33

that means, if any name from the list lies in either of the csv files, than we should include it in the new csv file along with its zip and score. Otherwise we should print 'x' in it.

This is what I have done so far:

import csv
with open('file1.csv', 'r') as input1, open('file2.csv', 'r') as input2, open('merge_final.csv', 'w') as output:
    writer = csv.writer(output)
    reader1 = csv.reader(input1)
    eader2 = csv.reader(input2)

    lista = ['harry', 'rob', 'wine', 'david', 'jass']
    writer.writerow(['name','zip','score','zip1','score'])

        for i in lista:
            for row in list(reader1):
                rev = row[1]
                if i in rev:
                    score = row[2]
                    zip = row[0]
                else:
                    score = 'x'
                    zip = 'x'
            for row in list(reader2):
                rev = row[1]
                if i in rev:
                    score1 = row[2]
                    zip1 = row[0]
                else:
                    score1 = 'x'
                    zip1 = 'x'
            writer.writerow([i, score, zip, score1, zip1])

This code is not working as expected. This is the output I got using this code.

name    zip     score       zip1     score1
harry   x       x           x           x
rob     x      x            x            x
wine    x       x           x           x
david   x       x           x           x
jass    x       x           x           x

Even thought there are many common words, only 'x' gets printed in the final merged csv file. I think the problem is with the loops. But, I don't seem to figure out the issue.

Body:
First, the first call of list(readerX) exhausts the iterator that is the file handle.

Secondly, rev is supposed to be the name already, so check for equality not contains: if name == rev.

Thirdly, you'd mostly get 'x's except for the last names in each file since you iterate the files to the end and only the last row will really matter. You should break the inner loops as soon as you find a name, but set the default values only after you iterated the entire file without finding the name.

Also, it is very bad performance-wise to repeatedly iterate both files. You better load the two files into a permanent data structure with faster lookup like a nested dict with names as keys:

d1 = {row[1]: {'zip': row[0], 'score': row[2]} for row in reader1}
d2 = {row[1]: {'zip': row[0], 'score': row[2]} for row in reader2}
#   {'david': {'zip': 23431, 'score: 12, ...}

for name in lista:
    if name in d1 or name in d2:
        writer.writerow([
            name,
            d1.get(name, {}).get('zip', 'x'),
            d1.get(name, {}).get('score', 'x'),
            d2.get(name, {}).get('zip', 'x'),
            d2.get(name, {}).get('score', 'x'),
        ])

To make your own approach work, change as follows, but note that this has terrible performance for larger data because of the nested loops:

# next(reader1)  # skip the header line if necessary
lst1 = list(reader1)  # load all the data into a list beforehand ...
for i in lista:
    for row in lst1:  # ... that you can repeatedly iterate
        rev = row[1]
        if i == rev:  # compare for equality
            score = row[2]
            zip = row[0]
            break  # <- you found the name, so end the loop!
    else:  # note the indentation: this is a for-else-loop, not an if-else
        # the else-part is only executed if the for loop was NOT break'ed
        score = 'x'
        zip = 'x'


问:
Laravel Delete function not work
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

```<code> public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}
</code>```

Model  :

```<code>protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}
</code>```

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

```<code>Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });
</code>```

答:
In your table, For example:</p>

```<code>$table->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade');
</code>```

Title: Laravel Delete function not work

Body:
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

 public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}

Model  :

protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });

Body:
In your table, For example:

$table->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade');


问:
What is the purpose of .to in Chai Library?
I don't get the purpose of to in chai api.
For example, I found if I didn't use to my cases still pass. So is it just added to improve readability? I guess my question is, is it the only purpose?

```<code>//use to
expect(result).to.equal('baba');
expect(result).to.have.property('baba');

//do not use to.
//As a non-native English speaker, I prefer typing less
expect(result).equal('baba');
expect(result).have.property('baba');
</code>```

答:
The following are provided as chainable getters to improve the
  readability of your assertions. to, be, been, is,...

Yes this .to is for the readability and specially those are chainable, it means there is no difference of

```<code>expect(result).to.equal('baba'); // with .to

expect(result).to.to.to.to.to.equal('baba'); // with .to x 5

expect(result).equal('baba'); // without .to
</code>```

Since .to doesn't change object properties

Hope you got the idea

Body:
I don't get the purpose of to in chai api.
For example, I found if I didn't use to my cases still pass. So is it just added to improve readability? I guess my question is, is it the only purpose?

//use to
expect(result).to.equal('baba');
expect(result).to.have.property('baba');

//do not use to.
//As a non-native English speaker, I prefer typing less
expect(result).equal('baba');
expect(result).have.property('baba');

Body:
The following are provided as chainable getters to improve the
  readability of your assertions. to, be, been, is,...

Yes this .to is for the readability and specially those are chainable, it means there is no difference of

expect(result).to.equal('baba'); // with .to

expect(result).to.to.to.to.to.equal('baba'); // with .to x 5

expect(result).equal('baba'); // without .to

Since .to doesn't change object properties

Hope you got the idea


问:
How is the Angular framework loaded into an application with Angular CLI?
I'm converting an existing AngularJS application to a hybrid application, to begin incrementally upgrading it to Angular 4. I want to understand how Angular 4 needs to be referenced in the existing AngularJS. In the existing AngularJS application, it's clear how the AngularJS framework is being loaded - it's simply an included script file:

```<code><script src="/angular/angular.js"></script>
</code>```

To familiarise myself with an up to date Angular version, I've created a separate 'quickstart' Angular 5 application using the Angular quickstart guide at https://angular.io/guide/quickstart, and I can run it using:

```<code>ng serve --open
</code>```

When I look at the project files though, I'm not seeing where the angular framework is actually being loaded. There is no script being included anywhere in the src/index.html file for that application, it simply declares an  directive for a component (app.component.ts) that looks like this:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Test Angular 5 app';
}
</code>```

Where does the import actually import from? The Angular documentation says about the index.html file that it is:

The main HTML page that is served when someone visits your site. Most
  of the time you'll never need to edit it. The CLI automatically adds
  all js and css files when building your app so you never need to add
  any  or  tags here manually.

So what is happening here? How is @angular/core actually being referenced?

答:
When using Angular CLI, we have a lot of moving parts. To really understand what's happening, we should review some of the core technologies used in Angular CLI as they relate to output files and module resolution:

TypeScript -- will transpile your TypeScript code to ES5 or ES6 (most commonly ES5). The transpiled code will use CommonJS modules by default if the target is ES5. If the target is ES6, then ES6 modules will be used.

Webpack -- will take your transpiled TypeScript code and build a dependency graph of your import / exports based on the entry points defined in webpack.config.js. This dependency graph will include all of your modules and it will package these modules into 1+ bundles, depending on the configuration. This is the step where the @angular/core dependency (which lives in node_modules/@angular/core) is processed by Webpack and added to a bundle that can be accessed at runtime.

You can load the generated bundles into the page by including the generated files in your HTML. In the case of JS files, you load them using the script tag like you did with AngularJS.

Because we are using Angular CLI, there are a lot of configurations within Webpack that are set up by default, so we will have multiple generated bundles.

I just created an empty Angular CLI project and inspected the HTML to see the 5  generated bundles:

At the core of the complexity when comparing Angular project files with AngularJS files is that Angular code is transformed through multiple build steps, while AngularJS code is normally used out-of-the-box with ES5. If you were to add Webpack and TypeScript to your AngularJS build, you would see something very similar to the Angular output.

Where is Webpack Configured in Angular CLI?

Under the hood, Angular CLI uses Webpack to build your project and bundle your files.

The Angular team chose not to expose a configurable Webpack configuration file for Angular CLI, but they did add ng eject, which generates a webpack.config.js that matches the Webpack build of your project. The downside of ejecting is that you will no longer use ng serve to serve your project. Instead, you'll use npm run build && npm run start (you'll see these scripts added to your package.json after you eject), which will build and serve your project based on the generated webpack.config.js file.

This feature is essential if you need to make custom modifications to the default Webpack build.

Read more about ng eject here.

Where are the generated bundles?

If you are using ng serve, you won't see any of your generated files because these are being served from memory and not from disk (to speed up development when files are constantly changing), so your generated files are not located in any folder.

If you want to see your generated files, you can run ng build, which will create a dist folder with the index.html and associated assets/bundles.

Note that by default, all commands that build or serve your project will delete your dist folder unless you pass the --no-delete-output-path when building/serving.

Body:
I'm converting an existing AngularJS application to a hybrid application, to begin incrementally upgrading it to Angular 4. I want to understand how Angular 4 needs to be referenced in the existing AngularJS. In the existing AngularJS application, it's clear how the AngularJS framework is being loaded - it's simply an included script file:

To familiarise myself with an up to date Angular version, I've created a separate 'quickstart' Angular 5 application using the Angular quickstart guide at https://angular.io/guide/quickstart, and I can run it using:

ng serve --open

When I look at the project files though, I'm not seeing where the angular framework is actually being loaded. There is no script being included anywhere in the src/index.html file for that application, it simply declares an  directive for a component (app.component.ts) that looks like this:

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

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

Where does the import actually import from? The Angular documentation says about the index.html file that it is:

The main HTML page that is served when someone visits your site. Most
  of the time you'll never need to edit it. The CLI automatically adds
  all js and css files when building your app so you never need to add
  any  or  tags here manually.

So what is happening here? How is @angular/core actually being referenced?


问:
Why won't my program terminate when i input END?
I am trying to terminate my code when "END" is input into the console, however my code wont play fair and I can't seem to see where it is going wrong, btw I haven't learnt how to debug as of yet so this has largely got to do with why i can't figure it out. please do help if you can. </p>

```<code>import java.util.*;
class Main
{
public static void main(String args[])
{
    int j = 0;
    while (j++ <= 3) {
        // Create Scanner object to take input from command prompt
        Scanner s=new Scanner(System.in);
        // Take input from the user and store it in st
        String st = "";
        while (!st.equals("END")) {
            {
                st=s.nextLine();
                // Initialize the variable count to 0
                int count=0;
                // Convert String st to char array
                char[] c=st.toCharArray();
                // Loop till end of string
                for(int i=0;i<st.length();i++)

                // If character at index 'i' is not a space, then increment count
                    if(c[i]!=' ') count++;
                // Print no.of spaces
                System.out.printf("[%4d] spaces in ", +(st.length()-count));
                // Print no.of spaces
                System.out.println('"' + st + '"');

            }
            j++;
        }
    }
}
</code>```

答:
I have just add an if condition without using loop.

```<code>public static void main(String args[]) {
    int j = 0;
    while (j++ <= 3) {
        // Create Scanner object to take input from command prompt
        Scanner s = new Scanner(System.in);
        // Take input from the user and store it in st
        String st = "";

        st = s.nextLine();

        if (st.equalsIgnoreCase("END")) {
            j = 5;
        }
        // Initialize the variable count to 0
        int count = 0;
        // Convert String st to char array
        char[] c = st.toCharArray();
        // Loop till end of string
        for (int i = 0; i < st.length(); i++) // If character at index 'i' is not a space, then increment count
        {
            if (c[i] != ' ') {
                count++;
            }
        }
        // Print no.of spaces
        System.out.printf("[%4d] spaces in ", +(st.length() - count));
        // Print no.of spaces
        System.out.println('"' + st + '"');
        j++;
    }
}
</code>```

What I do basically when I get the input end I just change the value of j to 5 so that the first loop will be terminated. and stop taking inpu.

Do you want this type of solution or you want you need to take input 3 times?

Body:
I am trying to terminate my code when "END" is input into the console, however my code wont play fair and I can't seem to see where it is going wrong, btw I haven't learnt how to debug as of yet so this has largely got to do with why i can't figure it out. please do help if you can.

import java.util.*;
class Main
{
public static void main(String args[])
{
    int j = 0;
    while (j++ <= 3) {
        // Create Scanner object to take input from command prompt
        Scanner s=new Scanner(System.in);
        // Take input from the user and store it in st
        String st = "";
        while (!st.equals("END")) {
            {
                st=s.nextLine();
                // Initialize the variable count to 0
                int count=0;
                // Convert String st to char array
                char[] c=st.toCharArray();
                // Loop till end of string
                for(int i=0;i<st.length();i++)

                // If character at index 'i' is not a space, then increment count
                    if(c[i]!=' ') count++;
                // Print no.of spaces
                System.out.printf("[%4d] spaces in ", +(st.length()-count));
                // Print no.of spaces
                System.out.println('"' + st + '"');

            }
            j++;
        }
    }
}

Body:
I have just add an if condition without using loop.

public static void main(String args[]) {
    int j = 0;
    while (j++ <= 3) {
        // Create Scanner object to take input from command prompt
        Scanner s = new Scanner(System.in);
        // Take input from the user and store it in st
        String st = "";

        st = s.nextLine();

        if (st.equalsIgnoreCase("END")) {
            j = 5;
        }
        // Initialize the variable count to 0
        int count = 0;
        // Convert String st to char array
        char[] c = st.toCharArray();
        // Loop till end of string
        for (int i = 0; i < st.length(); i++) // If character at index 'i' is not a space, then increment count
        {
            if (c[i] != ' ') {
                count++;
            }
        }
        // Print no.of spaces
        System.out.printf("[%4d] spaces in ", +(st.length() - count));
        // Print no.of spaces
        System.out.println('"' + st + '"');
        j++;
    }
}

What I do basically when I get the input end I just change the value of j to 5 so that the first loop will be terminated. and stop taking inpu.

Do you want this type of solution or you want you need to take input 3 times?


问:
Display new items at the top of a ListView
I'm using a list to populate a ListView (). The user is able to add items to the list. However, I need the items to be displayed at the top of the ListView. How do I insert an item at the beginning of my list in order to display it in reverse order?</p>

答:
You can add element at the beginning of the list: like

```<code>arraylist.add(0, object)
</code>```

then it will always display the new element at the top.

Body:
You can add element at the beginning of the list: like

arraylist.add(0, object)

then it will always display the new element at the top.


问:
Make `git svn find-rev` search the whole repository
When I want to get a local hash of a commit based on SVN revision id, I usually run git svn find-rev. However, the one big inconvenience is that this command will only look for the commit in the current branch, or in the branch explicitly specified in the command after the revision.

Sometimes, I only know the revision id, and I want to find a local hash without knowing the branch name. Is there a way to do it with git svn find-rev? It would make sense, knowing that SVN revisions are unique.

EDIT:

Turns out, there is no good way to do it.
I accepted the answer, which provides a solution, but it takes too long to search a repository with huge number of branches, like mine. I ended up writing my own shell function and using a regular svn in combination with git svn, which works much faster:

```<code>gitrev()
{
  if [ -z "$1" ]; then
    echo "${FUNCNAME[0]} <revision> [git_args]"
    return 1
  fi
  local rev b
  rev="$1"
  shift
  b="$(svn log -v -c "$rev" "$SVN_BRANCHES_URL" | grep -m1 -Po '/branches/\K[^/]+')" &&
  git svn find-rev "r${rev#r}" "origin/$b" "$@"
}
</code>```

If you use it, you may need to replace grep -P part if you're not on GNU/Linux. Revision can be specified with or without "r" prefix.

答:
git svn find-rev does show the commit sha-1 value from the current branch. But you can use shell script to search the commit from the whole repo.

Such as if you want to get the corresponding commit from revision r9, then you can specify the variable rev value as r9 as below:

```<code>#!/bin/sh

rev="r9"
for branch in $(git branch -r)
do
{
  sha=$(git svn find-rev $rev $branch)
  if [ ! -z "$sha" ]; then
  {
    echo "The revision $rev has the corresponding commit is $sha. And the commit is on $branch branch."
    break
  }
  fi
}
done
</code>```

Body:
When I want to get a local hash of a commit based on SVN revision id, I usually run git svn find-rev. However, the one big inconvenience is that this command will only look for the commit in the current branch, or in the branch explicitly specified in the command after the revision.

Sometimes, I only know the revision id, and I want to find a local hash without knowing the branch name. Is there a way to do it with git svn find-rev? It would make sense, knowing that SVN revisions are unique.

EDIT:

Turns out, there is no good way to do it.
I accepted the answer, which provides a solution, but it takes too long to search a repository with huge number of branches, like mine. I ended up writing my own shell function and using a regular svn in combination with git svn, which works much faster:

gitrev()
{
  if [ -z "$1" ]; then
    echo "${FUNCNAME[0]} <revision> [git_args]"
    return 1
  fi
  local rev b
  rev="$1"
  shift
  b="$(svn log -v -c "$rev" "$SVN_BRANCHES_URL" | grep -m1 -Po '/branches/\K[^/]+')" &&
  git svn find-rev "r${rev#r}" "origin/$b" "$@"
}

If you use it, you may need to replace grep -P part if you're not on GNU/Linux. Revision can be specified with or without "r" prefix.

Body:
git svn find-rev does show the commit sha-1 value from the current branch. But you can use shell script to search the commit from the whole repo.

Such as if you want to get the corresponding commit from revision r9, then you can specify the variable rev value as r9 as below:

#!/bin/sh

rev="r9"
for branch in $(git branch -r)
do
{
  sha=$(git svn find-rev $rev $branch)
  if [ ! -z "$sha" ]; then
  {
    echo "The revision $rev has the corresponding commit is $sha. And the commit is on $branch branch."
    break
  }
  fi
}
done

ContentLicense: CC BY-SA 4.0


问:
Get the status of google cloud container cluster provisioning using api python client
I'm creating a container engine cluster using API python client for google cloud platform.I have done with container creation successfully, Now I need to apply some yaml configurations but before applying any kubernetes yaml configurations the cluster should be provisioned otherwise kubernetes API not available.
I need to do both(Container creation & Apply yaml configs) things in a single request.
How can i get the provision status of a cluster using api?

Here's what i have tried:

After cluster creation:
From views.py:

```<code>print('Fetching Cluster configs ....')
cc = subprocess.call(
                'gcloud container clusters get-credentials ' + deployment.deploymentName.lower() + ' --zone ' + deployment.region + ' --project ' + deployment.project,
                shell=True)
print(cc)
while cc == 1:
     cc = subprocess.call(
                    'gcloud container clusters get-credentials ' + deployment.deploymentName.lower() + ' --zone ' + deployment.region + ' --project ' + deployment.project,
                    shell=True)
     print(cc)
</code>```

Help me, please!

Thanks in Advance!

答: What you are looking for is the status of the operation whose ID is returned from the create cluster call. You then need to get the operation (via the container API, not the compute API) and check the status of the operation to see if it is DONE. Once it is done, you can determine if there was an error by looking at the status message in the operation. If it is blank, then the create cluster API call succeeded. If it is non-empty then the call failed and the status message will tell you why. Once the operation for creating the cluster is done the get-credentials call will succeed. </p>

Body:
I'm creating a container engine cluster using API python client for google cloud platform.I have done with container creation successfully, Now I need to apply some yaml configurations but before applying any kubernetes yaml configurations the cluster should be provisioned otherwise kubernetes API not available.
I need to do both(Container creation & Apply yaml configs) things in a single request.
How can i get the provision status of a cluster using api?

Here's what i have tried:

After cluster creation:
From views.py:

print('Fetching Cluster configs ....')
cc = subprocess.call(
                'gcloud container clusters get-credentials ' + deployment.deploymentName.lower() + ' --zone ' + deployment.region + ' --project ' + deployment.project,
                shell=True)
print(cc)
while cc == 1:
     cc = subprocess.call(
                    'gcloud container clusters get-credentials ' + deployment.deploymentName.lower() + ' --zone ' + deployment.region + ' --project ' + deployment.project,
                    shell=True)
     print(cc)

Help me, please!

Thanks in Advance!


问:
Creating an NSDate from an API's value
I have a (Ruby on Rails site's) API which returns JSON data with datetimes formatted like this:

```<code>2011-01-21T18:05:41Z
</code>```

I have this in an NSString, and I want to make an NSDate of it. How can I do this?

答:
Try:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSDate *theDate =  [dateFormatter dateFromString:@"2011-01-21T18:05:41Z"];

ContentLicense: CC BY-SA 2.5

Title: Creating an NSDate from an API's value

Body:
I have a (Ruby on Rails site's) API which returns JSON data with datetimes formatted like this:

2011-01-21T18:05:41Z

I have this in an NSString, and I want to make an NSDate of it. How can I do this?


问:
Email Template Link Color wont change
I have an email template in Jade which contains "links", or basically strings of text with .com such as www.site.com

They are not actually enclosed in anchor tags, however when the email is sent, they appear as links. I have tried styling the font, the anchors, and put them inline or in an internal style tag, but nothing seems to work.

This is what the code looks like:

!{site}

where the site would be a string like I described earlier. I have tried changing the font to an a, but it simply removes all the styles and makes the string a regular, unstyled text.

Any ideas on how to fix this would be greatly appreciated!

答:
After inspecting the element, I discovered that the email client was enclosing any string that looked like a link inside anchor tags.

What I did to fix this was instead of using a wrapper tag like font or span for the url string, I enclosed it directly in anchor tags and used inline styling for the color with !important

My final output looks like this:

a(href=site style={ color: '#e64e65 !important' }) !{site}

Title: Email Template Link Color wont change


问:
Select MKMarkerAnnotationView with custom callout after adding annotation
I have an MKMapView on which I would like to add annotations on a long press gesture. After adding the annotation, I would like to select the annotation view. Quite a simple request I assumed.

The problem is that I am using the new MKMarkerAnnotationView with a custom rightCalloutAccessoryView and a custom detailCalloutAccessoryView. It is not very well documented yet, but the WWDC 2017 Session 237 states that the callout will be displayed when there is more than a title/subtitle.

Unfortunately, this is not the case for me. When I programmatically (and manually) select the annotation, I get a weird double selected state where I can see the callout AND the marker:

Here is the annotation view code:

```<code>import Foundation
import MapKit

@available(iOS 11.0, *)
protocol TemporaryUserAnnotationViewDelegate: class {
    func temporaryUserAnnotationViewDidTapOk(title: String?, userAnnotationView: TemporaryUserAnnotationView)
}

@available(iOS 11.0, *)
class TemporaryUserAnnotationView: MKMarkerAnnotationView {

    weak var delegate: TemporaryUserAnnotationViewDelegate?
    var textField: UITextField!

    init(annotation: TemporaryUserAnnotation) {
        super.init(annotation: annotation, reuseIdentifier: TemporaryUserAnnotationMarkerAnnotationView.reuseIdentifier)
        markerTintColor = .lbc_blue
        canShowCallout = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configure(annotation: TemporaryUserAnnotation) {
        let detailView = UIView()
        detailView.translatesAutoresizingMaskIntoConstraints = false
        textField = UITextField()
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.placeholder = "Titre"
        detailView.addSubview(textField)
        detailView.heightAnchor.constraint(equalToConstant: 21).isActive = true
        detailView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        textField.centerXAnchor.constraint(equalTo: detailView.centerXAnchor).isActive = true
        textField.centerYAnchor.constraint(equalTo: detailView.centerYAnchor).isActive = true
        textField.heightAnchor.constraint(equalToConstant: 21).isActive = true
        textField.widthAnchor.constraint(equalToConstant: 100).isActive = true
        detailCalloutAccessoryView = detailView

        let rightView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 70)))
        rightView.backgroundColor = .lbc_blue
        let button = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 40)))
        button.setTitle("OK", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action: #selector(tapRightCalloutAccessoryViewButton), for: .touchUpInside)
        rightView.addSubview(button)
        rightCalloutAccessoryView = rightView
    }

    @objc func tapRightCalloutAccessoryViewButton() {
        delegate?.temporaryUserAnnotationViewDidTapOk(title: textField.text, userAnnotationView: self)
    }
}
</code>```

and here is the controller code:

```<code>func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    print(#function)
    if annotation is MKUserLocation { return nil }
    if #available(iOS 11.0, *) {
        switch annotation {
        case let temporarayUserAnnotation as TemporaryUserAnnotation:
            if let view = mapView.dequeue() as? TemporaryUserAnnotationView {
                view.annotation = annotation
                return view
            } else {
                let view = TemporaryUserAnnotationView(annotation: temporarayUserAnnotation)
                view.delegate = self
                view.configure(annotation: temporarayUserAnnotation)
                return view
            }
        default:
            return nil
        }
    } else {
        let identifier = "marker"
        if let view = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView {
            view.annotation = annotation
            return view
        } else {
            return MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        }
    }
}
</code>```

I simply add annotations this way:

```<code>func addUserAnnotation(coordinate: CLLocationCoordinate2D) {
    let annotation = TemporaryUserAnnotation(coordinate: coordinate)
    mapView.addAnnotation(annotation)
    mapView.selectAnnotation(annotation, animated: true)
}
</code>```

I also tried to implement the mapView(_:didAdd:) method but the result is even worse with the marker view in front of the callout.

Any help would be very appreciated! Thanks!

答:
I just encountered a similar problem because I had a UITapGestureRecognizer of my own competing with MKMapView's selection gesture recognizer. I created and selected the annotation on the tap event, but because both gesture recognizers were firing, and theirs was firing last, it was deselecting immediately.

My solution was to implement UIGestureRecognizerDelegate and become the delegate of my gesture recognizer, and implement the following:

```<code>public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}
</code>```

Body:
I have an MKMapView on which I would like to add annotations on a long press gesture. After adding the annotation, I would like to select the annotation view. Quite a simple request I assumed.

The problem is that I am using the new MKMarkerAnnotationView with a custom rightCalloutAccessoryView and a custom detailCalloutAccessoryView. It is not very well documented yet, but the WWDC 2017 Session 237 states that the callout will be displayed when there is more than a title/subtitle.

Unfortunately, this is not the case for me. When I programmatically (and manually) select the annotation, I get a weird double selected state where I can see the callout AND the marker:

Here is the annotation view code:

import Foundation
import MapKit

@available(iOS 11.0, *)
protocol TemporaryUserAnnotationViewDelegate: class {
    func temporaryUserAnnotationViewDidTapOk(title: String?, userAnnotationView: TemporaryUserAnnotationView)
}

@available(iOS 11.0, *)
class TemporaryUserAnnotationView: MKMarkerAnnotationView {

    weak var delegate: TemporaryUserAnnotationViewDelegate?
    var textField: UITextField!

    init(annotation: TemporaryUserAnnotation) {
        super.init(annotation: annotation, reuseIdentifier: TemporaryUserAnnotationMarkerAnnotationView.reuseIdentifier)
        markerTintColor = .lbc_blue
        canShowCallout = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configure(annotation: TemporaryUserAnnotation) {
        let detailView = UIView()
        detailView.translatesAutoresizingMaskIntoConstraints = false
        textField = UITextField()
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.placeholder = "Titre"
        detailView.addSubview(textField)
        detailView.heightAnchor.constraint(equalToConstant: 21).isActive = true
        detailView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        textField.centerXAnchor.constraint(equalTo: detailView.centerXAnchor).isActive = true
        textField.centerYAnchor.constraint(equalTo: detailView.centerYAnchor).isActive = true
        textField.heightAnchor.constraint(equalToConstant: 21).isActive = true
        textField.widthAnchor.constraint(equalToConstant: 100).isActive = true
        detailCalloutAccessoryView = detailView

        let rightView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 70)))
        rightView.backgroundColor = .lbc_blue
        let button = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 40)))
        button.setTitle("OK", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action: #selector(tapRightCalloutAccessoryViewButton), for: .touchUpInside)
        rightView.addSubview(button)
        rightCalloutAccessoryView = rightView
    }

    @objc func tapRightCalloutAccessoryViewButton() {
        delegate?.temporaryUserAnnotationViewDidTapOk(title: textField.text, userAnnotationView: self)
    }
}

and here is the controller code:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    print(#function)
    if annotation is MKUserLocation { return nil }
    if #available(iOS 11.0, *) {
        switch annotation {
        case let temporarayUserAnnotation as TemporaryUserAnnotation:
            if let view = mapView.dequeue() as? TemporaryUserAnnotationView {
                view.annotation = annotation
                return view
            } else {
                let view = TemporaryUserAnnotationView(annotation: temporarayUserAnnotation)
                view.delegate = self
                view.configure(annotation: temporarayUserAnnotation)
                return view
            }
        default:
            return nil
        }
    } else {
        let identifier = "marker"
        if let view = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView {
            view.annotation = annotation
            return view
        } else {
            return MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        }
    }
}

I simply add annotations this way:

func addUserAnnotation(coordinate: CLLocationCoordinate2D) {
    let annotation = TemporaryUserAnnotation(coordinate: coordinate)
    mapView.addAnnotation(annotation)
    mapView.selectAnnotation(annotation, animated: true)
}

I also tried to implement the mapView(_:didAdd:) method but the result is even worse with the marker view in front of the callout.

Any help would be very appreciated! Thanks!

Body:
I just encountered a similar problem because I had a UITapGestureRecognizer of my own competing with MKMapView's selection gesture recognizer. I created and selected the annotation on the tap event, but because both gesture recognizers were firing, and theirs was firing last, it was deselecting immediately.

My solution was to implement UIGestureRecognizerDelegate and become the delegate of my gesture recognizer, and implement the following:

public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}


问:
Unicode character range not being consumed by Regex

NOTE

Another question was asked C# Regular Expressions with \Uxxxxxxxx characters in the pattern already. This question differs in that it is not about how surrogate pairs are calculated, but how to express unicode planes higher than 0 in a regex. It should be clear from my question that I already understand why these code units are being expressed as 2 characters - they are surrogate pairs (which was what the other question is asking about). My question is how can I convert them generically (since I have no control over what the regex being fed to the program looks like) so they can be consumed by the .NET Regex engine.

Note I now have a way to do this and would like to add my answer to my question, but since this is now marked as a duplicate I cannot add my answer.

I have some test data that is being passed to a Java library that I am porting to c#. I have isolated a specific problem case as an example. The character class in the original was in UTF-32 = \U0001BCA0-\U0001BCA3, which is not readily consumable by .NET - we get an "Unrecognized escape sequence \U" error.

I attempted to convert to UTF-16 and I have confirmed the results for \U0001BCA0 and \U0001BCA3 are what should be expected.

```<code>UTF-32      | Codepoint   | High Surrogate  | Low Surrogate  | UTF-16
---------------------------------------------------------------------------
0x0001BCA0  | 113824      | 55343           | 56480          | \uD82F\uDCA0
0x0001BCA3  | 113827      | 55343           | 56483          | \uD82F\uDCA3
</code>```

However, when I pass the string "([\uD82F\uDCA0-\uD82F\uDCA3])" to the constructor of the Regex class, I get an exception "[x-y] range in reverse order".

Although it is pretty clear the characters are specified in the right order (it works in Java), I tried in reverse and got the same error message.

I also tried changing the UTF-32 characters from \U0001BCA0-\U0001BCA3 to \x01BCA0-\x01BCA3, but still get the exception "[x-y] range in reverse order".

So, how do I get the .NET Regex class to parse this character range successfully?

NOTE: I tried changing the code to generate a regex character class that includes all of the characters instead of a range and it seems to work, but that is going to turn my regexes that are a few dozen characters into several thousand characters, which surely isn't going to do wonders for performance.

Actual Regex Example

Again, the above is an isolated example of a failure in a much larger string. What I am looking for is a general way to convert regexes like these so they can be parsed by the .NET Regex class.

```<code>"([\\u0000-\\u0009\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F\\u00AD" +
"\\u061C\\u180E\\u200B\\u200E\\u200F\\u2028-\\u202E\\u2060-\\u206F\\uD800-" +
"\\uDFFF\\uFEFF\\uFFF0-\\uFFFB\\U0001BCA0-\\U0001BCA3\\U0001D173-" +
"\\U0001D17A\\U000E0000-\\U000E001F\\U000E0080-\\U000E00FF\\U000E01F0-\\U000E0FFF] " +
"| [\\u000D] | [\\u000A]) ()"
</code>```

答:
While the other contributors to this question provided some clues, I needed an answer. My test is a rules engine that is driven by a regex that is built up from file input, so hard coding the logic into C# is not an option.

However, I did learn here that

the .NET Regex class does not support surrogate pairs and

you can fake support for surrogate pair ranges by using regex alteration

But of course, in my data-driven case I can't manually change the regexes to a format that .NET will accept - I need to automate it. So, I created the below Utf32Regex class that accepts UTF32 characters directly in the constructor and internally converts them to regexes that .NET understands.

For example, it will convert the regex

```<code>"[abc\\U00011DEF-\\U00013E07]"
</code>```

To

```<code>"(?:[abc]|\\uD807[\\uDDEF-\\uDFFF]|[\\uD808-\\uD80E][\\uDC00-\\uDFFF]|\\uD80F[\\uDC00-\\uDE07])"
</code>```

Or

```<code>"([\\u0000-\\u0009\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F\\u00AD" +
"\\u061C\\u180E\\u200B\\u200E\\u200F\\u2028-\\u202E\\u2060-\\u206F\\uD800-" +
"\\uDFFF\\uFEFF\\uFFF0-\\uFFFB\\U0001BCA0-\\U0001BCA3\\U0001D173-" +
"\\U0001D17A\\U000E0000-\\U000E001F\\U000E0080-\\U000E00FF\\U000E01F0-\\U000E0FFF] " +
"| [\\u000D] | [\\u000A]) ()"
</code>```

To

```<code>"((?:[\\u0000-\\u0009\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F\\u00AD\\u061C\\u180E" +
"\\u200B\\u200E\\u200F\\u2028-\\u202E\\u2060-\\u206F\\uD800-\\uDFFF\\uFEFF\\uFFF0-\\uFFFB]|" +
"\\uD82F[\\uDCA0-\\uDCA3]|\\uD834[\\uDD73-\\uDD7A]|\\uDB40[\\uDC00-\\uDC1F]|" +
"\\uDB40[\\uDC80-\\uDCFF]|\\uDB40[\\uDDF0-\\uDFFF]|[\\uDB41-\\uDB42][\\uDC00-\\uDFFF]|" +
"\\uDB43[\\uDC00-\\uDFFF]) | [\\u000D] | [\\u000A]) ()"
</code>```

Utf32Regex.cs

```<code>using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// Patches the <see cref="Regex"/> class so it will automatically convert and interpret
/// UTF32 characters expressed like <c>\U00010000</c> or UTF32 ranges expressed
/// like <c>\U00010000-\U00010001</c>.
/// </summary>
public class Utf32Regex : Regex
{
    private const char MinLowSurrogate = '\uDC00';
    private const char MaxLowSurrogate = '\uDFFF';

    private const char MinHighSurrogate = '\uD800';
    private const char MaxHighSurrogate = '\uDBFF';

    // Match any character class such as [A-z]
    private static readonly Regex characterClass = new Regex(
        "(?<!\\\\)(\\[.*?(?<!\\\\)\\])",
        RegexOptions.Compiled);

    // Match a UTF32 range such as \U000E01F0-\U000E0FFF
    // or an individual character such as \U000E0FFF
    private static readonly Regex utf32Range = new Regex(
        "(?<begin>\\\\U(?:00)?[0-9A-Fa-f]{6})-(?<end>\\\\U(?:00)?[0-9A-Fa-f]{6})|(?<begin>\\\\U(?:00)?[0-9A-Fa-f]{6})",
        RegexOptions.Compiled);

    public Utf32Regex()
        : base()
    {
    }

    public Utf32Regex(string pattern)
        : base(ConvertUTF32Characters(pattern))
    {
    }

    public Utf32Regex(string pattern, RegexOptions options)
        : base(ConvertUTF32Characters(pattern), options)
    {
    }

    public Utf32Regex(string pattern, RegexOptions options, TimeSpan matchTimeout)
        : base(ConvertUTF32Characters(pattern), options, matchTimeout)
    {
    }

    private static string ConvertUTF32Characters(string regexString)
    {
        StringBuilder result = new StringBuilder();
        // Convert any UTF32 character ranges \U00000000-\U00FFFFFF to their
        // equivalent UTF16 characters
        ConvertUTF32CharacterClassesToUTF16Characters(regexString, result);
        // Now find all of the individual characters that were not in ranges and
        // fix those as well.
        ConvertUTF32CharactersToUTF16(result);

        return result.ToString();
    }

    private static void ConvertUTF32CharacterClassesToUTF16Characters(string regexString, StringBuilder result)
    {
        Match match = characterClass.Match(regexString); // Reset
        int lastEnd = 0;
        if (match.Success)
        {
            do
            {
                string characterClass = match.Groups[1].Value;
                string convertedCharacterClass = ConvertUTF32CharacterRangesToUTF16Characters(characterClass);

                result.Append(regexString.Substring(lastEnd, match.Index - lastEnd)); // Remove the match
                result.Append(convertedCharacterClass); // Append replacement

                lastEnd = match.Index + match.Length;
            } while ((match = match.NextMatch()).Success);
        }
        result.Append(regexString.Substring(lastEnd)); // Append tail
    }

    private static string ConvertUTF32CharacterRangesToUTF16Characters(string characterClass)
    {
        StringBuilder result = new StringBuilder();
        StringBuilder chars = new StringBuilder();

        Match match = utf32Range.Match(characterClass); // Reset
        int lastEnd = 0;
        if (match.Success)
        {
            do
            {
                string utf16Chars;
                string rangeBegin = match.Groups["begin"].Value.Substring(2);

                if (!string.IsNullOrEmpty(match.Groups["end"].Value))
                {
                    string rangeEnd = match.Groups["end"].Value.Substring(2);
                    utf16Chars = UTF32RangeToUTF16Chars(rangeBegin, rangeEnd);
                }
                else
                {
                    utf16Chars = UTF32ToUTF16Chars(rangeBegin);
                }

                result.Append(characterClass.Substring(lastEnd, match.Index - lastEnd)); // Remove the match
                chars.Append(utf16Chars); // Append replacement

                lastEnd = match.Index + match.Length;
            } while ((match = match.NextMatch()).Success);
        }
        result.Append(characterClass.Substring(lastEnd)); // Append tail of character class

        // Special case - if we have removed all of the contents of the
        // character class, we need to remove the square brackets and the
        // alternation character |
        int emptyCharClass = result.IndexOf("[]");
        if (emptyCharClass >= 0)
        {
            result.Remove(emptyCharClass, 2);
            // Append replacement ranges (exclude beginning |)
            result.Append(chars.ToString(1, chars.Length - 1));
        }
        else
        {
            // Append replacement ranges
            result.Append(chars.ToString());
        }

        if (chars.Length > 0)
        {
            // Wrap both the character class and any UTF16 character alteration into
            // a non-capturing group.
            return "(?:" + result.ToString() + ")";
        }
        return result.ToString();
    }

    private static void ConvertUTF32CharactersToUTF16(StringBuilder result)
    {
        while (true)
        {
            int where = result.IndexOf("\\U00");
            if (where < 0)
            {
                break;
            }
            string cp = UTF32ToUTF16Chars(result.ToString(where + 2, 8));
            result.Replace(where, where + 10, cp);
        }
    }

    private static string UTF32RangeToUTF16Chars(string hexBegin, string hexEnd)
    {
        var result = new StringBuilder();
        int beginCodePoint = int.Parse(hexBegin, NumberStyles.HexNumber);
        int endCodePoint = int.Parse(hexEnd, NumberStyles.HexNumber);

        var beginChars = char.ConvertFromUtf32(beginCodePoint);
        var endChars = char.ConvertFromUtf32(endCodePoint);
        int beginDiff = endChars[0] - beginChars[0];

        if (beginDiff == 0)
        {
            // If the begin character is the same, we can just use the syntax \uD807[\uDDEF-\uDFFF]
            result.Append("|");
            AppendUTF16Character(result, beginChars[0]);
            result.Append('[');
            AppendUTF16Character(result, beginChars[1]);
            result.Append('-');
            AppendUTF16Character(result, endChars[1]);
            result.Append(']');
        }
        else
        {
            // If the begin character is not the same, create 3 ranges
            // 1. The remainder of the first
            // 2. A range of all of the middle characters
            // 3. The beginning of the last

            result.Append("|");
            AppendUTF16Character(result, beginChars[0]);
            result.Append('[');
            AppendUTF16Character(result, beginChars[1]);
            result.Append('-');
            AppendUTF16Character(result, MaxLowSurrogate);
            result.Append(']');

            // We only need a middle range if the ranges are not adjacent
            if (beginDiff > 1)
            {
                result.Append("|");
                // We only need a character class if there are more than 1
                // characters in the middle range
                if (beginDiff > 2)
                {
                    result.Append('[');
                }
                AppendUTF16Character(result, (char)(Math.Min(beginChars[0] + 1, MaxHighSurrogate)));
                if (beginDiff > 2)
                {
                    result.Append('-');
                    AppendUTF16Character(result, (char)(Math.Max(endChars[0] - 1, MinHighSurrogate)));
                    result.Append(']');
                }
                result.Append('[');
                AppendUTF16Character(result, MinLowSurrogate);
                result.Append('-');
                AppendUTF16Character(result, MaxLowSurrogate);
                result.Append(']');
            }

            result.Append("|");
            AppendUTF16Character(result, endChars[0]);
            result.Append('[');
            AppendUTF16Character(result, MinLowSurrogate);
            result.Append('-');
            AppendUTF16Character(result, endChars[1]);
            result.Append(']');
        }
        return result.ToString();
    }

    private static string UTF32ToUTF16Chars(string hex)
    {
        int codePoint = int.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
        return UTF32ToUTF16Chars(codePoint);
    }

    private static string UTF32ToUTF16Chars(int codePoint)
    {
        StringBuilder result = new StringBuilder();
        UTF32ToUTF16Chars(codePoint, result);
        return result.ToString();
    }

    private static void UTF32ToUTF16Chars(int codePoint, StringBuilder result)
    {
        // Use regex alteration to on the entire range of UTF32 code points
        // to ensure each one is treated as a group.
        result.Append("|");
        AppendUTF16CodePoint(result, codePoint);
    }

    private static void AppendUTF16CodePoint(StringBuilder text, int cp)
    {
        var chars = char.ConvertFromUtf32(cp);
        AppendUTF16Character(text, chars[0]);
        if (chars.Length == 2)
        {
            AppendUTF16Character(text, chars[1]);
        }
    }

    private static void AppendUTF16Character(StringBuilder text, char c)
    {
        text.Append(@"\u");
        text.Append(Convert.ToString(c, 16).ToUpperInvariant());
    }
}
</code>```

StringBuilderExtensions.cs

```<code>public static class StringBuilderExtensions
{
    /// <summary>
    /// Searches for the first index of the specified character. The search for
    /// the character starts at the beginning and moves towards the end.
    /// </summary>
    /// <param name="text">This <see cref="StringBuilder"/>.</param>
    /// <param name="value">The string to find.</param>
    /// <returns>The index of the specified character, or -1 if the character isn't found.</returns>
    public static int IndexOf(this StringBuilder text, string value)
    {
        return IndexOf(text, value, 0);
    }

    /// <summary>
    /// Searches for the index of the specified character. The search for the
    /// character starts at the specified offset and moves towards the end.
    /// </summary>
    /// <param name="text">This <see cref="StringBuilder"/>.</param>
    /// <param name="value">The string to find.</param>
    /// <param name="startIndex">The starting offset.</param>
    /// <returns>The index of the specified character, or -1 if the character isn't found.</returns>
    public static int IndexOf(this StringBuilder text, string value, int startIndex)
    {
        if (text == null)
            throw new ArgumentNullException("text");
        if (value == null)
            throw new ArgumentNullException("value");

        int index;
        int length = value.Length;
        int maxSearchLength = (text.Length - length) + 1;

        for (int i = startIndex; i < maxSearchLength; ++i)
        {
            if (text[i] == value[0])
            {
                index = 1;
                while ((index < length) && (text[i + index] == value[index]))
                    ++index;

                if (index == length)
                    return i;
            }
        }

        return -1;
    }

    /// <summary>
    /// Replaces the specified subsequence in this builder with the specified
    /// string.
    /// </summary>
    /// <param name="text">this builder.</param>
    /// <param name="start">the inclusive begin index.</param>
    /// <param name="end">the exclusive end index.</param>
    /// <param name="str">the replacement string.</param>
    /// <returns>this builder.</returns>
    /// <exception cref="IndexOutOfRangeException">
    /// if <paramref name="start"/> is negative, greater than the current
    /// <see cref="StringBuilder.Length"/> or greater than <paramref name="end"/>.
    /// </exception>
    /// <exception cref="ArgumentNullException">if <paramref name="str"/> is <c>null</c>.</exception>
    public static StringBuilder Replace(this StringBuilder text, int start, int end, string str)
    {
        if (str == null)
        {
            throw new ArgumentNullException(nameof(str));
        }
        if (start >= 0)
        {
            if (end > text.Length)
            {
                end = text.Length;
            }
            if (end > start)
            {
                int stringLength = str.Length;
                int diff = end - start - stringLength;
                if (diff > 0)
                { // replacing with fewer characters
                    text.Remove(start, diff);
                }
                else if (diff < 0)
                {
                    // replacing with more characters...need some room
                    text.Insert(start, new char[-diff]);
                }
                // copy the chars based on the new length
                for (int i = 0; i < stringLength; i++)
                {
                    text[i + start] = str[i];
                }
                return text;
            }
            if (start == end)
            {

                text.Insert(start, str);
                return text;
            }
        }
        throw new IndexOutOfRangeException();
    }
}
</code>```

Do note this is not very well tested and probably not very robust, but for testing purposes it should be fine.

Body:
NOTE

Another question was asked C# Regular Expressions with \Uxxxxxxxx characters in the pattern already. This question differs in that it is not about how surrogate pairs are calculated, but how to express unicode planes higher than 0 in a regex. It should be clear from my question that I already understand why these code units are being expressed as 2 characters - they are surrogate pairs (which was what the other question is asking about). My question is how can I convert them generically (since I have no control over what the regex being fed to the program looks like) so they can be consumed by the .NET Regex engine.

Note I now have a way to do this and would like to add my answer to my question, but since this is now marked as a duplicate I cannot add my answer.

I have some test data that is being passed to a Java library that I am porting to c#. I have isolated a specific problem case as an example. The character class in the original was in UTF-32 = \U0001BCA0-\U0001BCA3, which is not readily consumable by .NET - we get an "Unrecognized escape sequence \U" error.

I attempted to convert to UTF-16 and I have confirmed the results for \U0001BCA0 and \U0001BCA3 are what should be expected.

UTF-32      | Codepoint   | High Surrogate  | Low Surrogate  | UTF-16
---------------------------------------------------------------------------
0x0001BCA0  | 113824      | 55343           | 56480          | \uD82F\uDCA0
0x0001BCA3  | 113827      | 55343           | 56483          | \uD82F\uDCA3

However, when I pass the string "([\uD82F\uDCA0-\uD82F\uDCA3])" to the constructor of the Regex class, I get an exception "[x-y] range in reverse order".

Although it is pretty clear the characters are specified in the right order (it works in Java), I tried in reverse and got the same error message.

I also tried changing the UTF-32 characters from \U0001BCA0-\U0001BCA3 to \x01BCA0-\x01BCA3, but still get the exception "[x-y] range in reverse order".

So, how do I get the .NET Regex class to parse this character range successfully?

NOTE: I tried changing the code to generate a regex character class that includes all of the characters instead of a range and it seems to work, but that is going to turn my regexes that are a few dozen characters into several thousand characters, which surely isn't going to do wonders for performance.

Actual Regex Example

Again, the above is an isolated example of a failure in a much larger string. What I am looking for is a general way to convert regexes like these so they can be parsed by the .NET Regex class.

"([\\u0000-\\u0009\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F\\u00AD" +
"\\u061C\\u180E\\u200B\\u200E\\u200F\\u2028-\\u202E\\u2060-\\u206F\\uD800-" +
"\\uDFFF\\uFEFF\\uFFF0-\\uFFFB\\U0001BCA0-\\U0001BCA3\\U0001D173-" +
"\\U0001D17A\\U000E0000-\\U000E001F\\U000E0080-\\U000E00FF\\U000E01F0-\\U000E0FFF] " +
"| [\\u000D] | [\\u000A]) ()"

Body:
While the other contributors to this question provided some clues, I needed an answer. My test is a rules engine that is driven by a regex that is built up from file input, so hard coding the logic into C# is not an option.

However, I did learn here that

the .NET Regex class does not support surrogate pairs and

you can fake support for surrogate pair ranges by using regex alteration

But of course, in my data-driven case I can't manually change the regexes to a format that .NET will accept - I need to automate it. So, I created the below Utf32Regex class that accepts UTF32 characters directly in the constructor and internally converts them to regexes that .NET understands.

For example, it will convert the regex

"[abc\\U00011DEF-\\U00013E07]"

To

"(?:[abc]|\\uD807[\\uDDEF-\\uDFFF]|[\\uD808-\\uD80E][\\uDC00-\\uDFFF]|\\uD80F[\\uDC00-\\uDE07])"

Or

"([\\u0000-\\u0009\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F\\u00AD" +
"\\u061C\\u180E\\u200B\\u200E\\u200F\\u2028-\\u202E\\u2060-\\u206F\\uD800-" +
"\\uDFFF\\uFEFF\\uFFF0-\\uFFFB\\U0001BCA0-\\U0001BCA3\\U0001D173-" +
"\\U0001D17A\\U000E0000-\\U000E001F\\U000E0080-\\U000E00FF\\U000E01F0-\\U000E0FFF] " +
"| [\\u000D] | [\\u000A]) ()"

To

"((?:[\\u0000-\\u0009\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F\\u00AD\\u061C\\u180E" +
"\\u200B\\u200E\\u200F\\u2028-\\u202E\\u2060-\\u206F\\uD800-\\uDFFF\\uFEFF\\uFFF0-\\uFFFB]|" +
"\\uD82F[\\uDCA0-\\uDCA3]|\\uD834[\\uDD73-\\uDD7A]|\\uDB40[\\uDC00-\\uDC1F]|" +
"\\uDB40[\\uDC80-\\uDCFF]|\\uDB40[\\uDDF0-\\uDFFF]|[\\uDB41-\\uDB42][\\uDC00-\\uDFFF]|" +
"\\uDB43[\\uDC00-\\uDFFF]) | [\\u000D] | [\\u000A]) ()"

Utf32Regex.cs

using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// Patches the <see cref="Regex"/> class so it will automatically convert and interpret
/// UTF32 characters expressed like <c>\U00010000</c> or UTF32 ranges expressed
/// like <c>\U00010000-\U00010001</c>.
/// </summary>
public class Utf32Regex : Regex
{
    private const char MinLowSurrogate = '\uDC00';
    private const char MaxLowSurrogate = '\uDFFF';

    private const char MinHighSurrogate = '\uD800';
    private const char MaxHighSurrogate = '\uDBFF';

    // Match any character class such as [A-z]
    private static readonly Regex characterClass = new Regex(
        "(?<!\\\\)(\\[.*?(?<!\\\\)\\])",
        RegexOptions.Compiled);

    // Match a UTF32 range such as \U000E01F0-\U000E0FFF
    // or an individual character such as \U000E0FFF
    private static readonly Regex utf32Range = new Regex(
        "(?<begin>\\\\U(?:00)?[0-9A-Fa-f]{6})-(?<end>\\\\U(?:00)?[0-9A-Fa-f]{6})|(?<begin>\\\\U(?:00)?[0-9A-Fa-f]{6})",
        RegexOptions.Compiled);

    public Utf32Regex()
        : base()
    {
    }

    public Utf32Regex(string pattern)
        : base(ConvertUTF32Characters(pattern))
    {
    }

    public Utf32Regex(string pattern, RegexOptions options)
        : base(ConvertUTF32Characters(pattern), options)
    {
    }

    public Utf32Regex(string pattern, RegexOptions options, TimeSpan matchTimeout)
        : base(ConvertUTF32Characters(pattern), options, matchTimeout)
    {
    }

    private static string ConvertUTF32Characters(string regexString)
    {
        StringBuilder result = new StringBuilder();
        // Convert any UTF32 character ranges \U00000000-\U00FFFFFF to their
        // equivalent UTF16 characters
        ConvertUTF32CharacterClassesToUTF16Characters(regexString, result);
        // Now find all of the individual characters that were not in ranges and
        // fix those as well.
        ConvertUTF32CharactersToUTF16(result);

        return result.ToString();
    }

    private static void ConvertUTF32CharacterClassesToUTF16Characters(string regexString, StringBuilder result)
    {
        Match match = characterClass.Match(regexString); // Reset
        int lastEnd = 0;
        if (match.Success)
        {
            do
            {
                string characterClass = match.Groups[1].Value;
                string convertedCharacterClass = ConvertUTF32CharacterRangesToUTF16Characters(characterClass);

                result.Append(regexString.Substring(lastEnd, match.Index - lastEnd)); // Remove the match
                result.Append(convertedCharacterClass); // Append replacement

                lastEnd = match.Index + match.Length;
            } while ((match = match.NextMatch()).Success);
        }
        result.Append(regexString.Substring(lastEnd)); // Append tail
    }

    private static string ConvertUTF32CharacterRangesToUTF16Characters(string characterClass)
    {
        StringBuilder result = new StringBuilder();
        StringBuilder chars = new StringBuilder();

        Match match = utf32Range.Match(characterClass); // Reset
        int lastEnd = 0;
        if (match.Success)
        {
            do
            {
                string utf16Chars;
                string rangeBegin = match.Groups["begin"].Value.Substring(2);

                if (!string.IsNullOrEmpty(match.Groups["end"].Value))
                {
                    string rangeEnd = match.Groups["end"].Value.Substring(2);
                    utf16Chars = UTF32RangeToUTF16Chars(rangeBegin, rangeEnd);
                }
                else
                {
                    utf16Chars = UTF32ToUTF16Chars(rangeBegin);
                }

                result.Append(characterClass.Substring(lastEnd, match.Index - lastEnd)); // Remove the match
                chars.Append(utf16Chars); // Append replacement

                lastEnd = match.Index + match.Length;
            } while ((match = match.NextMatch()).Success);
        }
        result.Append(characterClass.Substring(lastEnd)); // Append tail of character class

        // Special case - if we have removed all of the contents of the
        // character class, we need to remove the square brackets and the
        // alternation character |
        int emptyCharClass = result.IndexOf("[]");
        if (emptyCharClass >= 0)
        {
            result.Remove(emptyCharClass, 2);
            // Append replacement ranges (exclude beginning |)
            result.Append(chars.ToString(1, chars.Length - 1));
        }
        else
        {
            // Append replacement ranges
            result.Append(chars.ToString());
        }

        if (chars.Length > 0)
        {
            // Wrap both the character class and any UTF16 character alteration into
            // a non-capturing group.
            return "(?:" + result.ToString() + ")";
        }
        return result.ToString();
    }

    private static void ConvertUTF32CharactersToUTF16(StringBuilder result)
    {
        while (true)
        {
            int where = result.IndexOf("\\U00");
            if (where < 0)
            {
                break;
            }
            string cp = UTF32ToUTF16Chars(result.ToString(where + 2, 8));
            result.Replace(where, where + 10, cp);
        }
    }

    private static string UTF32RangeToUTF16Chars(string hexBegin, string hexEnd)
    {
        var result = new StringBuilder();
        int beginCodePoint = int.Parse(hexBegin, NumberStyles.HexNumber);
        int endCodePoint = int.Parse(hexEnd, NumberStyles.HexNumber);

        var beginChars = char.ConvertFromUtf32(beginCodePoint);
        var endChars = char.ConvertFromUtf32(endCodePoint);
        int beginDiff = endChars[0] - beginChars[0];

        if (beginDiff == 0)
        {
            // If the begin character is the same, we can just use the syntax \uD807[\uDDEF-\uDFFF]
            result.Append("|");
            AppendUTF16Character(result, beginChars[0]);
            result.Append('[');
            AppendUTF16Character(result, beginChars[1]);
            result.Append('-');
            AppendUTF16Character(result, endChars[1]);
            result.Append(']');
        }
        else
        {
            // If the begin character is not the same, create 3 ranges
            // 1. The remainder of the first
            // 2. A range of all of the middle characters
            // 3. The beginning of the last

            result.Append("|");
            AppendUTF16Character(result, beginChars[0]);
            result.Append('[');
            AppendUTF16Character(result, beginChars[1]);
            result.Append('-');
            AppendUTF16Character(result, MaxLowSurrogate);
            result.Append(']');

            // We only need a middle range if the ranges are not adjacent
            if (beginDiff > 1)
            {
                result.Append("|");
                // We only need a character class if there are more than 1
                // characters in the middle range
                if (beginDiff > 2)
                {
                    result.Append('[');
                }
                AppendUTF16Character(result, (char)(Math.Min(beginChars[0] + 1, MaxHighSurrogate)));
                if (beginDiff > 2)
                {
                    result.Append('-');
                    AppendUTF16Character(result, (char)(Math.Max(endChars[0] - 1, MinHighSurrogate)));
                    result.Append(']');
                }
                result.Append('[');
                AppendUTF16Character(result, MinLowSurrogate);
                result.Append('-');
                AppendUTF16Character(result, MaxLowSurrogate);
                result.Append(']');
            }

            result.Append("|");
            AppendUTF16Character(result, endChars[0]);
            result.Append('[');
            AppendUTF16Character(result, MinLowSurrogate);
            result.Append('-');
            AppendUTF16Character(result, endChars[1]);
            result.Append(']');
        }
        return result.ToString();
    }

    private static string UTF32ToUTF16Chars(string hex)
    {
        int codePoint = int.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
        return UTF32ToUTF16Chars(codePoint);
    }

    private static string UTF32ToUTF16Chars(int codePoint)
    {
        StringBuilder result = new StringBuilder();
        UTF32ToUTF16Chars(codePoint, result);
        return result.ToString();
    }

    private static void UTF32ToUTF16Chars(int codePoint, StringBuilder result)
    {
        // Use regex alteration to on the entire range of UTF32 code points
        // to ensure each one is treated as a group.
        result.Append("|");
        AppendUTF16CodePoint(result, codePoint);
    }

    private static void AppendUTF16CodePoint(StringBuilder text, int cp)
    {
        var chars = char.ConvertFromUtf32(cp);
        AppendUTF16Character(text, chars[0]);
        if (chars.Length == 2)
        {
            AppendUTF16Character(text, chars[1]);
        }
    }

    private static void AppendUTF16Character(StringBuilder text, char c)
    {
        text.Append(@"\u");
        text.Append(Convert.ToString(c, 16).ToUpperInvariant());
    }
}

StringBuilderExtensions.cs

public static class StringBuilderExtensions
{
    /// <summary>
    /// Searches for the first index of the specified character. The search for
    /// the character starts at the beginning and moves towards the end.
    /// </summary>
    /// <param name="text">This <see cref="StringBuilder"/>.</param>
    /// <param name="value">The string to find.</param>
    /// <returns>The index of the specified character, or -1 if the character isn't found.</returns>
    public static int IndexOf(this StringBuilder text, string value)
    {
        return IndexOf(text, value, 0);
    }

    /// <summary>
    /// Searches for the index of the specified character. The search for the
    /// character starts at the specified offset and moves towards the end.
    /// </summary>
    /// <param name="text">This <see cref="StringBuilder"/>.</param>
    /// <param name="value">The string to find.</param>
    /// <param name="startIndex">The starting offset.</param>
    /// <returns>The index of the specified character, or -1 if the character isn't found.</returns>
    public static int IndexOf(this StringBuilder text, string value, int startIndex)
    {
        if (text == null)
            throw new ArgumentNullException("text");
        if (value == null)
            throw new ArgumentNullException("value");

        int index;
        int length = value.Length;
        int maxSearchLength = (text.Length - length) + 1;

        for (int i = startIndex; i < maxSearchLength; ++i)
        {
            if (text[i] == value[0])
            {
                index = 1;
                while ((index < length) && (text[i + index] == value[index]))
                    ++index;

                if (index == length)
                    return i;
            }
        }

        return -1;
    }

    /// <summary>
    /// Replaces the specified subsequence in this builder with the specified
    /// string.
    /// </summary>
    /// <param name="text">this builder.</param>
    /// <param name="start">the inclusive begin index.</param>
    /// <param name="end">the exclusive end index.</param>
    /// <param name="str">the replacement string.</param>
    /// <returns>this builder.</returns>
    /// <exception cref="IndexOutOfRangeException">
    /// if <paramref name="start"/> is negative, greater than the current
    /// <see cref="StringBuilder.Length"/> or greater than <paramref name="end"/>.
    /// </exception>
    /// <exception cref="ArgumentNullException">if <paramref name="str"/> is <c>null</c>.</exception>
    public static StringBuilder Replace(this StringBuilder text, int start, int end, string str)
    {
        if (str == null)
        {
            throw new ArgumentNullException(nameof(str));
        }
        if (start >= 0)
        {
            if (end > text.Length)
            {
                end = text.Length;
            }
            if (end > start)
            {
                int stringLength = str.Length;
                int diff = end - start - stringLength;
                if (diff > 0)
                { // replacing with fewer characters
                    text.Remove(start, diff);
                }
                else if (diff < 0)
                {
                    // replacing with more characters...need some room
                    text.Insert(start, new char[-diff]);
                }
                // copy the chars based on the new length
                for (int i = 0; i < stringLength; i++)
                {
                    text[i + start] = str[i];
                }
                return text;
            }
            if (start == end)
            {

                text.Insert(start, str);
                return text;
            }
        }
        throw new IndexOutOfRangeException();
    }
}

Do note this is not very well tested and probably not very robust, but for testing purposes it should be fine.


问:
In MySQL, how to select data based on date?
I need to get record based on date but I got stuck.

```<code>rate  applicable_date

12        01/01/2001
13.5      01/05/2005
17.9      07/11/2017
</code>```

I need to get applicable rate based on applicable date. I used below SQL:

```<code>Select rate from ratetable where applicable_date <=$date;
</code>```

For $date = '12/02/2017';

It returns me 12

but for date 17/11/2017 it returns me all rates but I need only 17.9 latest one.

答:
try to do the following query</p>

```<code>select rate from ratetable where applicable_date = $date
</code>```

Body:
I need to get record based on date but I got stuck.

rate  applicable_date

12        01/01/2001
13.5      01/05/2005
17.9      07/11/2017

I need to get applicable rate based on applicable date. I used below SQL:

Select rate from ratetable where applicable_date <=$date;

For $date = '12/02/2017';

It returns me 12

but for date 17/11/2017 it returns me all rates but I need only 17.9 latest one.

Body:
try to do the following query

select rate from ratetable where applicable_date = $date