问:
Scrapy spider not following links and error
I am trying to write my first web crawler / data extractor using scrapy and can't get it follow links. I am also getting an error:

ERROR: Spider error processing < GET
  https://en.wikipedia.org/wiki/Wikipedia:Unusual_articles>

I know the spider is scanning the page once as I am able to pull out information from an a tag and h1 element I was messing with.

Does anyone know how I could make this follow the links on the page and get rid of the error?

```<code>import scrapy
from scrapy.linkextractors import LinkExtractor
from wikiCrawler.items import WikicrawlerItem
from scrapy.spiders import Rule

class WikispyderSpider(scrapy.Spider):
    name = "wikiSpyder"

    allowed_domains = ['https://en.wikipedia.org/']

    start_urls = ['https://en.wikipedia.org/wiki/Wikipedia:Unusual_articles']

    rules = (
        Rule(LinkExtractor(canonicalize=True, unique=True), follow=True, callback="parse"),
    )

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, callback=self.parse, dont_filter=True)

    def parse(self, response):
        items = []
        links = LinkExtractor(canonicalize=True, unique=True).extract_links(response)
        for link in links:
            item = WikicrawlerItem()
            item['url_from'] = response.url
            item['url_to'] = link.url
            items.append(item)
            print(items)
        return items
</code>```

答:
If you want to use Link Extractors, you need to use a special spider class - CrawlSpider:

```<code>from scrapy.spiders import CrawlSpider

class WikispyderSpider(CrawlSpider):
    # ...
</code>```

Here is a simple spider that follows the links from your start url and prints out the page titles:

```<code>from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider

from scrapy.spiders import Rule

class WikispyderSpider(CrawlSpider):
    name = "wikiSpyder"

    allowed_domains = ['en.wikipedia.org']
    start_urls = ['https://en.wikipedia.org/wiki/Wikipedia:Unusual_articles']

    rules = (
        Rule(LinkExtractor(canonicalize=True, unique=True), follow=True, callback="parse_link"),
    )

    def parse_link(self, response):
        print(response.xpath("//title/text()").extract_first())
</code>```

Body:
I am trying to write my first web crawler / data extractor using scrapy and can't get it follow links. I am also getting an error:

ERROR: Spider error processing < GET
  https://en.wikipedia.org/wiki/Wikipedia:Unusual_articles>

I know the spider is scanning the page once as I am able to pull out information from an a tag and h1 element I was messing with.

Does anyone know how I could make this follow the links on the page and get rid of the error?

import scrapy
from scrapy.linkextractors import LinkExtractor
from wikiCrawler.items import WikicrawlerItem
from scrapy.spiders import Rule

class WikispyderSpider(scrapy.Spider):
    name = "wikiSpyder"

    allowed_domains = ['https://en.wikipedia.org/']

    start_urls = ['https://en.wikipedia.org/wiki/Wikipedia:Unusual_articles']

    rules = (
        Rule(LinkExtractor(canonicalize=True, unique=True), follow=True, callback="parse"),
    )

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, callback=self.parse, dont_filter=True)

    def parse(self, response):
        items = []
        links = LinkExtractor(canonicalize=True, unique=True).extract_links(response)
        for link in links:
            item = WikicrawlerItem()
            item['url_from'] = response.url
            item['url_to'] = link.url
            items.append(item)
            print(items)
        return items

Body:
If you want to use Link Extractors, you need to use a special spider class - CrawlSpider:

from scrapy.spiders import CrawlSpider

class WikispyderSpider(CrawlSpider):
    # ...

Here is a simple spider that follows the links from your start url and prints out the page titles:

from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider

from scrapy.spiders import Rule

class WikispyderSpider(CrawlSpider):
    name = "wikiSpyder"

    allowed_domains = ['en.wikipedia.org']
    start_urls = ['https://en.wikipedia.org/wiki/Wikipedia:Unusual_articles']

    rules = (
        Rule(LinkExtractor(canonicalize=True, unique=True), follow=True, callback="parse_link"),
    )

    def parse_link(self, response):
        print(response.xpath("//title/text()").extract_first())


来源: stackexchange

问:
Howto delete every second and third element from an array?
I want to delete every second and third element from an array in Javascript.

My array looks like this:

```<code>var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];
</code>```

Now I want to delete every second and third element. The result would look like this:

```<code>["Banana", "Orange", "Apple"]
</code>```

I tried to use a for-loop and splice:

```<code>for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};
</code>```

Of course this returns an empty array because the elements are removed while the loop is still executed.

How can I do this correctly?

答:
You could approach this from a different angle and push() the value you don't want deleted into another Array:

```<code>var firstFruits = []

for (var i = 0; i < fruits.length; i = i+3) {
    firstFruits.push(fruits[i]);
};
</code>```

This approach may not be as terse as using splice(), but I think you see gain in terms of readability.

ContentLicense: CC BY-SA 4.0

Body:
I want to delete every second and third element from an array in Javascript.

My array looks like this:

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];

Now I want to delete every second and third element. The result would look like this:

["Banana", "Orange", "Apple"]

I tried to use a for-loop and splice:

for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};

Of course this returns an empty array because the elements are removed while the loop is still executed.

How can I do this correctly?

Body:
You could approach this from a different angle and push() the value you don't want deleted into another Array:

var firstFruits = []

for (var i = 0; i < fruits.length; i = i+3) {
    firstFruits.push(fruits[i]);
};

This approach may not be as terse as using splice(), but I think you see gain in terms of readability.

ContentLicense: CC BY-SA 2.5


问:
Call different method if first one fails
Using Rails/Ruby. I have the following:

```<code>  def normalize
    rg = ReverseGeocoder.new(lat, lng, LOCALITY).process!
    return save_normalized_values(rg) if rg[:results].any?

    rg = ReverseGeocoder.new(lat, lng, ADMINISTRATIVE_AREA_LEVEL_1).process!
    return save_normalized_values(rg) if rg[:results].any?
  end
</code>```

While this works, is there a better way to write this?

答:
If you could make .process! return false on a failure you could do this

```<code>rg = ReverseGeocoder.new(lat, lng, LOCALITY).process! || ReverseGeocoder.new(lat, lng, ADMINISTRATIVE_AREA_LEVEL_1).process!
save_normalized_values(rg) if rg[:results].any?
</code>```

Otherwise I don't see a cleaner way, just different:

```<code>rg = ReverseGeocoder.new(lat, lng, LOCALITY).process!
rg[:results] || rg = ReverseGeocoder.new(lat, lng, ADMINISTRATIVE_AREA_LEVEL_1).process!
rg[:results] && save_normalized_values(rg)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using Rails/Ruby. I have the following:

  def normalize
    rg = ReverseGeocoder.new(lat, lng, LOCALITY).process!
    return save_normalized_values(rg) if rg[:results].any?

    rg = ReverseGeocoder.new(lat, lng, ADMINISTRATIVE_AREA_LEVEL_1).process!
    return save_normalized_values(rg) if rg[:results].any?
  end

While this works, is there a better way to write this?

Body:
If you could make .process! return false on a failure you could do this

rg = ReverseGeocoder.new(lat, lng, LOCALITY).process! || ReverseGeocoder.new(lat, lng, ADMINISTRATIVE_AREA_LEVEL_1).process!
save_normalized_values(rg) if rg[:results].any?

Otherwise I don't see a cleaner way, just different:

rg = ReverseGeocoder.new(lat, lng, LOCALITY).process!
rg[:results] || rg = ReverseGeocoder.new(lat, lng, ADMINISTRATIVE_AREA_LEVEL_1).process!
rg[:results] && save_normalized_values(rg)


问:
PHP code does not recognize some values
EDIT: Thank you all for the very quick answers! I have been at this for a while, trying to figure out why $id was being recognized and why the strings weren't. I feel a bit silly now seeing the obvious answer but I'm relieved to have it working.

I apologize if this has been answered before, I've looked for hours and could not find something similar to help me figure this out.

I am trying to update a row in my database of devices with new information. Problem is, the php file only recognizes $data->devID; and nothing else.

If I have something like
$sql = "UPDATE devices SET devName = 'static test string', description = 'static test string' WHERE devID = $id";
the entry with the correct ID will update in my database table just fine.

If I try
$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";
it does not work.

Where am I going wrong?

HTML:

```<code><div data-ng-repeat="info in deviceInfo">
    <form class="deviceInfo">
        <h2>Device ID: {{info.devID}}</h2>
        <p>Device Name:</p>
        <input type="text" data-ng-model="info.devName">
        <p>Device Description:</p>
        <textarea data-ng-model="info.description"></textarea>
        <p>Device Available: {{info.isAvailable}}</p>
        <input type="submit" name="Update" value="Update" data-ng-click="updateInfo(info.devID, info.devName, info.description)">
    </form>
</div>
</code>```

updateDeviceInfo.php:

```<code><?php

$data = json_decode(file_get_contents("php://input"));

include('config.php');

$id = $data->devID;
$name = $data->devName;
$desc = $data->description;

$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";

$qry = $conn->query($sql);

$data = $qry;

$sql = "SELECT * FROM devices";

$qry = $conn->query($sql);

$data = array();

if($qry->num_rows > 0){
    while($row = $qry->fetch_object()){
        $data[] = $row;
    }
}else {
    $data[] = null;
}

$conn->close();

echo json_encode($data);
</code>```

controller.js:

```<code>$scope.updateInfo = function($paramID, $paramName, $paramDesc){

    console.log($paramID);
    console.log($paramName);
    console.log($paramDesc);

    $scope.dataOneTest = {
            devID: $paramID,
            devName: $paramName,
            description: $paramDesc

        };

    console.log($scope.dataOneTest.devID);

    $http.post('./js/updateDeviceInfo.php', {'devID': $paramID, 'devName': $paramName, 'description': $paramDesc})
        .success(function(data){
            $scope.results = data;
        })
        .error(function(err){
            $log.error(err);
        })
}
</code>```

答:
tl;dr You are almost certainly performing SQL injection on yourself both by inserting variables directly into a query and by failing to use proper quotation marks around them.

You need to use prepared statements, rather than concatenating variables directly into your query. If, for example, $data->devName contained something nefarious like NULL --, that would toast your entire table. And that's a very mild example of how badly things could go. Prepared statements would render that example (and pretty much all other examples) harmless.

Short-Term Fix

As a short-term fix, put quotation marks in the query and escape your data, like this:

```<code>$id = your_database_escape_function($data->devID);
$name = your_database_escape_function($data->devName);
$desc = your_database_escape_function($data->description);

$sql = "UPDATE devices SET devName = '$name', description = '$desc' WHERE devID = $id";
</code>```

substituting your database's corresponding escaping function for your_database_escape_function(). For example, use $conn->real_escape_string() if $conn is a MySQLi object. See the manual.

The Real Fix

Here's how you really do it correctly, and the solution you should implement ASAP. That is, do this before you go any further if at all possible. Use prepared statements.

Read this entire Q&A and this cheat sheet from OWASP (no affiliation) for more information.

Title: PHP code does not recognize some values

Body:
EDIT: Thank you all for the very quick answers! I have been at this for a while, trying to figure out why $id was being recognized and why the strings weren't. I feel a bit silly now seeing the obvious answer but I'm relieved to have it working.

I apologize if this has been answered before, I've looked for hours and could not find something similar to help me figure this out.

I am trying to update a row in my database of devices with new information. Problem is, the php file only recognizes $data->devID; and nothing else.

If I have something like
$sql = "UPDATE devices SET devName = 'static test string', description = 'static test string' WHERE devID = $id";
the entry with the correct ID will update in my database table just fine.

If I try
$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";
it does not work.

Where am I going wrong?

HTML:

    <form class="deviceInfo">

Device ID: {{info.devID}}

Device Name:

        <input type="text" data-ng-model="info.devName">

Device Description:

        <textarea data-ng-model="info.description"></textarea>

Device Available: {{info.isAvailable}}

        <input type="submit" name="Update" value="Update" data-ng-click="updateInfo(info.devID, info.devName, info.description)">
    </form>

updateDeviceInfo.php:

<?php

$data = json_decode(file_get_contents("php://input"));

include('config.php');

$id = $data->devID;
$name = $data->devName;
$desc = $data->description;

$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";

$qry = $conn->query($sql);

$data = $qry;

$sql = "SELECT * FROM devices";

$qry = $conn->query($sql);

$data = array();

if($qry->num_rows > 0){
    while($row = $qry->fetch_object()){
        $data[] = $row;
    }
}else {
    $data[] = null;
}

$conn->close();

echo json_encode($data);

controller.js:

$scope.updateInfo = function($paramID, $paramName, $paramDesc){

    console.log($paramID);
    console.log($paramName);
    console.log($paramDesc);

    $scope.dataOneTest = {
            devID: $paramID,
            devName: $paramName,
            description: $paramDesc

        };

    console.log($scope.dataOneTest.devID);

    $http.post('./js/updateDeviceInfo.php', {'devID': $paramID, 'devName': $paramName, 'description': $paramDesc})
        .success(function(data){
            $scope.results = data;
        })
        .error(function(err){
            $log.error(err);
        })
}

Body:
tl;dr You are almost certainly performing SQL injection on yourself both by inserting variables directly into a query and by failing to use proper quotation marks around them.

You need to use prepared statements, rather than concatenating variables directly into your query. If, for example, $data->devName contained something nefarious like NULL --, that would toast your entire table. And that's a very mild example of how badly things could go. Prepared statements would render that example (and pretty much all other examples) harmless.

Short-Term Fix

As a short-term fix, put quotation marks in the query and escape your data, like this:

$id = your_database_escape_function($data->devID);
$name = your_database_escape_function($data->devName);
$desc = your_database_escape_function($data->description);

$sql = "UPDATE devices SET devName = '$name', description = '$desc' WHERE devID = $id";

substituting your database's corresponding escaping function for your_database_escape_function(). For example, use $conn->real_escape_string() if $conn is a MySQLi object. See the manual.

The Real Fix

Here's how you really do it correctly, and the solution you should implement ASAP. That is, do this before you go any further if at all possible. Use prepared statements.

Read this entire Q&A and this cheat sheet from OWASP (no affiliation) for more information.


问:
How to make a class attribute exclusive to the super class
I have a master class for a planet:

```<code>class Planet:

    def __init__(self,name):
        self.name = name
        (...)

    def destroy(self):
        (...)
</code>```

I also have a few classes that inherit from Planet and I want to make one of them unable to be destroyed (not to inherit the destroy function)

Example:

```<code>class Undestroyable(Planet):

    def __init__(self,name):
        super().__init__(name)
        (...)

    #Now it shouldn't have the destroy(self) function
</code>```

So when this is run,

```<code>Undestroyable('This Planet').destroy()
</code>```

it should produce an error like:

```<code>AttributeError: Undestroyable has no attribute 'destroy'
</code>```

答:
Metaclasses and descriptor protocols are fun, but perhaps overkill.  Sometimes, for raw functionality, you can't beat good ole' __slots__.

```<code>class Planet(object):

    def __init__(self, name):
        self.name = name

    def destroy(self):
        print("Boom!  %s is toast!\n" % self.name)

class Undestroyable(Planet):
    __slots__ = ['destroy']

    def __init__(self,name):
        super().__init__(name)

print()
x = Planet('Pluto')  # Small, easy to destroy
y = Undestroyable('Jupiter') # Too big to fail
x.destroy()
y.destroy()

Boom!  Pluto is toast!

Traceback (most recent call last):
  File "planets.py", line 95, in <module>
    y.destroy()
AttributeError: destroy
</code>```

Body:
I have a master class for a planet:

class Planet:

    def __init__(self,name):
        self.name = name
        (...)

    def destroy(self):
        (...)

I also have a few classes that inherit from Planet and I want to make one of them unable to be destroyed (not to inherit the destroy function)

Example:

class Undestroyable(Planet):

    def __init__(self,name):
        super().__init__(name)
        (...)

    #Now it shouldn't have the destroy(self) function

So when this is run,

Undestroyable('This Planet').destroy()

it should produce an error like:

AttributeError: Undestroyable has no attribute 'destroy'

Body:
Metaclasses and descriptor protocols are fun, but perhaps overkill.  Sometimes, for raw functionality, you can't beat good ole' __slots__.

class Planet(object):

    def __init__(self, name):
        self.name = name

    def destroy(self):
        print("Boom!  %s is toast!\n" % self.name)

class Undestroyable(Planet):
    __slots__ = ['destroy']

    def __init__(self,name):
        super().__init__(name)

print()
x = Planet('Pluto')  # Small, easy to destroy
y = Undestroyable('Jupiter') # Too big to fail
x.destroy()
y.destroy()

Boom!  Pluto is toast!

Traceback (most recent call last):
  File "planets.py", line 95, in <module>
    y.destroy()
AttributeError: destroy


问:
tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"
Lint error message:

src/app/detail/edit/edit.component.ts[111, 5]: for (... in ...)
  statements must be filtered with an if statement

Code snippet (It is a working code. It is also available at angular.io form validation section):

```<code>for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
</code>```

Any idea how to fix this lint error?

答:
A neater way of applying @Helzgate's reply is possibly to replace your 'for .. in' with</p>

```<code>for (const field of Object.keys(this.formErrors)) {
</code>```

Body:
Lint error message:

src/app/detail/edit/edit.component.ts[111, 5]: for (... in ...)
  statements must be filtered with an if statement

Code snippet (It is a working code. It is also available at angular.io form validation section):

for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }

Any idea how to fix this lint error?

Body:
A neater way of applying @Helzgate's reply is possibly to replace your 'for .. in' with

for (const field of Object.keys(this.formErrors)) {


问:
1044 - Access denied for user 'user'@'localhost' to database 'db'
I tried a lot to import the sql script to create database and tables through phpmyadmin in the new site I hosted. But i'm getting the error,

1044 - Access denied for user 'user'@'localhost' to database 'db'

I tried to create a sample db directly : create database sampled; I'm getting the same access denied error.

I'm not able to grant privileges to the user also, i'm getting the same access denied error.

Following is the output of show grants command,

```<code>show grants;
GRANT USAGE ON . TO 'someuser'@'localhost' IDENTIFIED BY PASSWORD 'somepw'

GRANT ALL PRIVILEGES ON someuser\_%.* TO 'someuser'@'localhost'
</code>```

Any help would be appreciated. thank you.

答:
Must Ensure that your User_Name, Password and Database name are correct.
If you are Deal with database 'sampled' then type 'sampled' in query instead of 'db' also must ensure that you don't have to use quota(') in Statement.</p>

Body:
I tried a lot to import the sql script to create database and tables through phpmyadmin in the new site I hosted. But i'm getting the error,

1044 - Access denied for user 'user'@'localhost' to database 'db'

I tried to create a sample db directly : create database sampled; I'm getting the same access denied error.

I'm not able to grant privileges to the user also, i'm getting the same access denied error.

Following is the output of show grants command,

show grants;
GRANT USAGE ON . TO 'someuser'@'localhost' IDENTIFIED BY PASSWORD 'somepw'

GRANT ALL PRIVILEGES ON someuser\_%.* TO 'someuser'@'localhost'

Any help would be appreciated. thank you.


问:
Improving performance for a TM simulator
I am trying to simulate a lot of 2 state, 3 symbol (One direction tape) Turing machines. Each simulation will have different input, and will run for a fixed number of steps. The current bottleneck in the program seems to be the simulator, taking a ton of memory on Turing machines which do not halt.

The task is to simulate about 650000 TMs, each with about 200 non-blank inputs. The largest number of steps I am trying is 1 billion (10**9).

Below is the code I am running. vector<vector<int> > TM is a transition table.

```<code>vector<int> fast_simulate(vector<vector<int> > TM, string TM_input, int steps) {
    /* Return the state reached after supplied steps */

    vector<int> tape = itotape(TM_input);

    int head = 0;
    int current_state = 0;
    int halt_state = 2;

    for(int i = 0; i < steps; i++){

        // Read from tape
        if(head >= tape.size()) {
            tape.push_back(2);
        }
        int cell = tape[head];
        int data = TM[current_state][cell];  // get transition for this state/input

        int move = data % 2;
        int write = (data % 10) % 3;
        current_state = data / 10;

        if(current_state == halt_state) {
            // This highlights the last place that is written to in the tape
            tape[head] = 4;
            vector<int> res = shorten_tape(tape);
            res.push_back(i+1);
            return res;
        }

        // Write to tape
        tape[head] = write;

        // move head
        if(move == 0) {
            if(head != 0) {
                head--;
            }
        } else {
            head++;
        }
    }

    vector<int> res {-1};
    return res;
}

vector<int> itotape(string TM_input) {
    vector<int> tape;
    for(char &c : TM_input) {
        tape.push_back(c - '0');
    }
    return tape;
}

vector<int> shorten_tape(vector<int> tape) {
    /*  Shorten the tape by removing unnecessary 2's (blanks) from the end of it.
    */
    int i = tape.size()-1;
    for(; i >= 0; --i) {
        if(tape[i] != 2) {
            tape.resize(i+1);
            return tape;
        }
    }
    return tape;
}
</code>```

Is there anywhere I can make improvements in terms of performance or memory usage? Even a 2% decrease would make a noticeable difference.

答:
Here is another answer with more algorithmic approaches.

Simulation by blocks

Since you have tiny alphabet and tiny number of states, you can accelerate the simulation by processing chunks of the tape at once. This is related to the well-known speedup theorem, although I suggest a slightly different method.

Divide the tape into blocks of 8 characters each. Each such block can be represented with 16-bit number (2 bits per character). Now imagine that the machine is located either at the first or at the last character of a block. Then its subsequent behavior depends only on its initial state and the initial value on the block, until the TM moves out of the block (either to the left or to the right). We can precompute the outcome for all (block value + state + end) combinations, or maybe lazily compute them during simulation.

This method can simulate about 8 steps at once, although if you are unlucky it can do only one step per iteration (moving back and forth around block boundary). Here is the code sample:

```<code>//R = table[s][e][V] --- outcome for TM which:
//  starts in state s
//  runs on a tape block with initial contents V
//  starts on the (e = 0: leftmost, e = 1: rightmost) char of the block
//The value R is a bitmask encoding:
//  0..15 bits: the new value of the block
//  16..17 bits: the new state
//  18 bit: TM moved to the (0: left, 1: right) of the block
//  ??encode number of steps taken??
uint32_t table[2][2][1<<16];

//contents of the tape (grouped in 8-character blocks)
uint16_t tape[...];

int pos = 0;    //index of current block
int end = 0;    //TM is currently located at (0: start, 1: end) of the block
int state = 0;  //current state
while (state != 2) {
  //take the outcome of simulation on the current block
  uint32_t res = table[state][end][tape[pos]];
  //decode it into parts
  uint16_t newValue = res & 0xFFFFU;
  int newState = (res >> 16) & 3U;
  int move = (res >> 18);
  //write new contents to the tape
  tape[pos] = newValue;
  //switch to the new state
  state = newState;
  //move to the neighboring block
  pos += (2*move-1);
  end = !move;
  //avoid getting out of tape on the left
  if (pos < 0)
      pos = 0, move = 0;
}
</code>```

Halting problem

The comment says that TM simulation is expected either to finish very early, or to run all the steps up to the predefined huge limit. Since you are going to simulate many Turing machines, it might be worth investing some time in solving the halting problem.

The first type of hanging which can be detected is: when machine stays at the same place without moving far away from it. Let's maintain surrounding of TM during simulation, which is the values of segment of characters at distance < 16 from TM's current location. If you have 3 characters, you can encode surrounding in a 62-bit number.

Maintain a hash table for each position of TM (as we'll see later, only 31 tables are necessary). After each step, store tuple (state, surrounding) in the hash table of current position. Now the important part: after each move, clear all hash tables at distance >= 16 from TM (actually, only one such hash table has to be cleared). Before each step, check if (state, surrounding) is already present in the hash table. If it is, then the machine is in infinite loop.

You can also detect another type of hanging: when machine moves to the right infinitely, but never returns back. In order to achieve that, you can use the same hashtables. If TM is located at the currently last character of the tape with index p, check current tuple (state, surrounding) not only in the p-th hashtable, but also in the (p-1)-th, (p-2)-th, ..., (p-15)-th hash tables. If you find a match, then TM is in infinite loop moving to the right.

Body:
I am trying to simulate a lot of 2 state, 3 symbol (One direction tape) Turing machines. Each simulation will have different input, and will run for a fixed number of steps. The current bottleneck in the program seems to be the simulator, taking a ton of memory on Turing machines which do not halt.

The task is to simulate about 650000 TMs, each with about 200 non-blank inputs. The largest number of steps I am trying is 1 billion (10**9).

Below is the code I am running. vector<vector<int> > TM is a transition table.

vector<int> fast_simulate(vector<vector<int> > TM, string TM_input, int steps) {
    /* Return the state reached after supplied steps */

    vector<int> tape = itotape(TM_input);

    int head = 0;
    int current_state = 0;
    int halt_state = 2;

    for(int i = 0; i < steps; i++){

        // Read from tape
        if(head >= tape.size()) {
            tape.push_back(2);
        }
        int cell = tape[head];
        int data = TM[current_state][cell];  // get transition for this state/input

        int move = data % 2;
        int write = (data % 10) % 3;
        current_state = data / 10;

        if(current_state == halt_state) {
            // This highlights the last place that is written to in the tape
            tape[head] = 4;
            vector<int> res = shorten_tape(tape);
            res.push_back(i+1);
            return res;
        }

        // Write to tape
        tape[head] = write;

        // move head
        if(move == 0) {
            if(head != 0) {
                head--;
            }
        } else {
            head++;
        }
    }

    vector<int> res {-1};
    return res;
}

vector<int> itotape(string TM_input) {
    vector<int> tape;
    for(char &c : TM_input) {
        tape.push_back(c - '0');
    }
    return tape;
}

vector<int> shorten_tape(vector<int> tape) {
    /*  Shorten the tape by removing unnecessary 2's (blanks) from the end of it.
    */
    int i = tape.size()-1;
    for(; i >= 0; --i) {
        if(tape[i] != 2) {
            tape.resize(i+1);
            return tape;
        }
    }
    return tape;
}

Is there anywhere I can make improvements in terms of performance or memory usage? Even a 2% decrease would make a noticeable difference.

Body:
Here is another answer with more algorithmic approaches.

Simulation by blocks

Since you have tiny alphabet and tiny number of states, you can accelerate the simulation by processing chunks of the tape at once. This is related to the well-known speedup theorem, although I suggest a slightly different method.

Divide the tape into blocks of 8 characters each. Each such block can be represented with 16-bit number (2 bits per character). Now imagine that the machine is located either at the first or at the last character of a block. Then its subsequent behavior depends only on its initial state and the initial value on the block, until the TM moves out of the block (either to the left or to the right). We can precompute the outcome for all (block value + state + end) combinations, or maybe lazily compute them during simulation.

This method can simulate about 8 steps at once, although if you are unlucky it can do only one step per iteration (moving back and forth around block boundary). Here is the code sample:

//R = table[s][e][V] --- outcome for TM which:
//  starts in state s
//  runs on a tape block with initial contents V
//  starts on the (e = 0: leftmost, e = 1: rightmost) char of the block
//The value R is a bitmask encoding:
//  0..15 bits: the new value of the block
//  16..17 bits: the new state
//  18 bit: TM moved to the (0: left, 1: right) of the block
//  ??encode number of steps taken??
uint32_t table[2][2][1<<16];

//contents of the tape (grouped in 8-character blocks)
uint16_t tape[...];

int pos = 0;    //index of current block
int end = 0;    //TM is currently located at (0: start, 1: end) of the block
int state = 0;  //current state
while (state != 2) {
  //take the outcome of simulation on the current block
  uint32_t res = table[state][end][tape[pos]];
  //decode it into parts
  uint16_t newValue = res & 0xFFFFU;
  int newState = (res >> 16) & 3U;
  int move = (res >> 18);
  //write new contents to the tape
  tape[pos] = newValue;
  //switch to the new state
  state = newState;
  //move to the neighboring block
  pos += (2*move-1);
  end = !move;
  //avoid getting out of tape on the left
  if (pos < 0)
      pos = 0, move = 0;
}

Halting problem

The comment says that TM simulation is expected either to finish very early, or to run all the steps up to the predefined huge limit. Since you are going to simulate many Turing machines, it might be worth investing some time in solving the halting problem.

The first type of hanging which can be detected is: when machine stays at the same place without moving far away from it. Let's maintain surrounding of TM during simulation, which is the values of segment of characters at distance < 16 from TM's current location. If you have 3 characters, you can encode surrounding in a 62-bit number.

Maintain a hash table for each position of TM (as we'll see later, only 31 tables are necessary). After each step, store tuple (state, surrounding) in the hash table of current position. Now the important part: after each move, clear all hash tables at distance >= 16 from TM (actually, only one such hash table has to be cleared). Before each step, check if (state, surrounding) is already present in the hash table. If it is, then the machine is in infinite loop.

You can also detect another type of hanging: when machine moves to the right infinitely, but never returns back. In order to achieve that, you can use the same hashtables. If TM is located at the currently last character of the tape with index p, check current tuple (state, surrounding) not only in the p-th hashtable, but also in the (p-1)-th, (p-2)-th, ..., (p-15)-th hash tables. If you find a match, then TM is in infinite loop moving to the right.


问:
How to reload .bash_profile from the command line
How can I reload file .bash_profile from the command line?

I can get the shell to recognize changes to .bash_profile by exiting and logging back in, but I would like to be able to do it on demand.

答: I use Debian and I can simply type exec bash to achieve this. I can't say if it will work on all other distributions.


问:
Find if the number is Prime or show the prime factors using excel formula?
I have of integers in Col A and in col B i want to show result 'Prime' if it doesn't have further factors for the number itself. This goes like this if the number for example is 37 result will be 'Prime' and if its 44 then result will be 2x2x11. How can i do this using excel formula? Screen shot :

答:
Disclaimer: code below is ported from this very useful VB.NET example

```<code>Option Explicit

Sub Test()
    Debug.Print FindFactors(2)
    Debug.Print FindFactors(3)
    Debug.Print FindFactors(11)
    Debug.Print FindFactors(12)
    Debug.Print FindFactors(13)
    Debug.Print FindFactors(16)
    Debug.Print FindFactors(17)
    Debug.Print FindFactors(24)
    Debug.Print FindFactors(25)
    Debug.Print FindFactors(11234)
    Debug.Print FindFactors(67894)
End Sub

Function FindFactors(lngNumber As Long) As String
    Dim collFactors As Collection
    Dim lngFactor As Long
    Dim lngCounter As Long
    Dim strFactors As String
    Dim strFactor As String

    Set collFactors = New Collection

    ' Take out the 2s.
    Do While (lngNumber Mod 2 = 0)
        collFactors.Add 2
        lngNumber = lngNumber / 2
    Loop

    ' Take out other primes.
    lngFactor = 3
    Do While (lngFactor * lngFactor <= lngNumber)
        If (lngNumber Mod lngFactor = 0) Then
            ' This is a factor.
            collFactors.Add lngFactor
            lngNumber = lngNumber / lngFactor
        Else
            ' Go to the next odd number.
            lngFactor = lngFactor + 2
        End If
    Loop

    ' If num is not 1, then whatever is left is prime.
    If lngNumber > 1 Then
        collFactors.Add lngNumber
    End If

    ' make a string out of collection
    strFactors = ""
    If collFactors.Count = 1 Then
        strFactors = "Prime"
    Else
        For lngCounter = 1 To collFactors.Count
            strFactors = strFactors & collFactors(lngCounter)
            If lngCounter < collFactors.Count Then
                strFactors = strFactors & "x"
            End If
        Next lngCounter

    End If

    FindFactors = strFactors

End Function
</code>```

Gives an output of:

```<code>Prime
Prime
Prime
2x2x3
Prime
2x2x2x2
Prime
2x2x2x3
5x5
2x41x137
2x83x409
</code>```

Can be used in a worksheet:

Body:
Disclaimer: code below is ported from this very useful VB.NET example

Option Explicit

Sub Test()
    Debug.Print FindFactors(2)
    Debug.Print FindFactors(3)
    Debug.Print FindFactors(11)
    Debug.Print FindFactors(12)
    Debug.Print FindFactors(13)
    Debug.Print FindFactors(16)
    Debug.Print FindFactors(17)
    Debug.Print FindFactors(24)
    Debug.Print FindFactors(25)
    Debug.Print FindFactors(11234)
    Debug.Print FindFactors(67894)
End Sub

Function FindFactors(lngNumber As Long) As String
    Dim collFactors As Collection
    Dim lngFactor As Long
    Dim lngCounter As Long
    Dim strFactors As String
    Dim strFactor As String

    Set collFactors = New Collection

    ' Take out the 2s.
    Do While (lngNumber Mod 2 = 0)
        collFactors.Add 2
        lngNumber = lngNumber / 2
    Loop

    ' Take out other primes.
    lngFactor = 3
    Do While (lngFactor * lngFactor <= lngNumber)
        If (lngNumber Mod lngFactor = 0) Then
            ' This is a factor.
            collFactors.Add lngFactor
            lngNumber = lngNumber / lngFactor
        Else
            ' Go to the next odd number.
            lngFactor = lngFactor + 2
        End If
    Loop

    ' If num is not 1, then whatever is left is prime.
    If lngNumber > 1 Then
        collFactors.Add lngNumber
    End If

    ' make a string out of collection
    strFactors = ""
    If collFactors.Count = 1 Then
        strFactors = "Prime"
    Else
        For lngCounter = 1 To collFactors.Count
            strFactors = strFactors & collFactors(lngCounter)
            If lngCounter < collFactors.Count Then
                strFactors = strFactors & "x"
            End If
        Next lngCounter

    End If

    FindFactors = strFactors

End Function

Gives an output of:

Prime
Prime
Prime
2x2x3
Prime
2x2x2x2
Prime
2x2x2x3
5x5
2x41x137
2x83x409

Can be used in a worksheet:


问:
Compare All Strings in a List - C#
I have List<String> clr9, which has a known Count of nine.

What I want to know is how to shorthand something that goes on later in the code.

```<code>else if(clr9[0].Equals(clr9[1]) && clr9[0].Equals(clr9[2]) && clr9[0].Equals(clr9[3]))
</code>```

I've already tried this:

```<code>else if(clr9[0].Equals(clr9[1].Equals(clr9[2].Equals(clr9[3]))))
</code>```

but it doesn't seem to work. Is there any way I can avoid the ampersands?
Basically just asking if there's a way to find out if all 4 strings are the same without cluttering up that if statement.

答:
Distinct will work, but I think testing equality directly is more expressive of intent:</p>

```<code>if(clr9.Skip(1).All(c => c.Equals(clr9[0])))
</code>```

Title: Compare All Strings in a List - C#

Body:
I have List<String> clr9, which has a known Count of nine.

What I want to know is how to shorthand something that goes on later in the code.

else if(clr9[0].Equals(clr9[1]) && clr9[0].Equals(clr9[2]) && clr9[0].Equals(clr9[3]))

I've already tried this:

else if(clr9[0].Equals(clr9[1].Equals(clr9[2].Equals(clr9[3]))))

but it doesn't seem to work. Is there any way I can avoid the ampersands?
Basically just asking if there's a way to find out if all 4 strings are the same without cluttering up that if statement.

Body:
Distinct will work, but I think testing equality directly is more expressive of intent:

if(clr9.Skip(1).All(c => c.Equals(clr9[0])))


问:
Elastic search is returning undefined for _id in elastic search
I am using elastic search in my application and everything works fine until you click the search result link which returns undefined. The problem I have is that the _source._id is returning undefined. So I cannot view the search result.

How can I pass the object id in /blog/article/<%= data[i]._source._id?

My code is below

router.js

```<code>router.post('/search', function(req, res, next) {
  res.redirect('/search?q=' + req.body.q);
});

router.get('/search', function(req, res, next) {
  if (req.query.q) {
    Article.search({
      query_string: { query: req.query.q}
    }, function(err, results) {
      results:
      if (err) return next (err);
      var data = results.hits.hits.map(function(hit) {
        return hit;
      });
      res.render('main/search-result', {
        query: req.query.q,
        data: data
      });
    });
  }
});
</code>```

search-result.ejs

```<code><% for (var i=0; i < data.length; i++) { %>
         <div class="col-md-4">
           <a href="/blog/article/<%= data[i]._source._id %>">
             <div class="thumbnail">
               <h3 id="data_title"><%= data[i]._source.title %></h3>
             </div>
         </div>
       <% } %>
</code>```

答:
Finally resolved this issue by changing </p>

```<code><a href="/blog/article/<%= data[i]._source._id %>">
</code>```

<p>to </p>

```<code><a href="/blog/article/<%= data[i]._id %>">
</code>```

Body:
I am using elastic search in my application and everything works fine until you click the search result link which returns undefined. The problem I have is that the _source._id is returning undefined. So I cannot view the search result.

How can I pass the object id in /blog/article/<%= data[i]._source._id?

My code is below

router.js

router.post('/search', function(req, res, next) {
  res.redirect('/search?q=' + req.body.q);
});

router.get('/search', function(req, res, next) {
  if (req.query.q) {
    Article.search({
      query_string: { query: req.query.q}
    }, function(err, results) {
      results:
      if (err) return next (err);
      var data = results.hits.hits.map(function(hit) {
        return hit;
      });
      res.render('main/search-result', {
        query: req.query.q,
        data: data
      });
    });
  }
});

search-result.ejs

<% for (var i=0; i < data.length; i++) { %>

           <a href="/blog/article/<%= data[i]._source._id %>">

<%= data[i]._source.title %>

       <% } %>

Body:
Finally resolved this issue by changing

<a href="/blog/article/<%= data[i]._source._id %>">

to

<a href="/blog/article/<%= data[i]._id %>">


问:
Angularjs order by not working properly
I'm facing a little problem with order by that i could not underdstand.

When i reoder the array i can see that every thing is working perfectly, but the problem is in the ng-click function of the list.

For example if i have this array:

```<code>$scope.ticketsEncour = [
  {_id: 1, vendeur: 'John Doe', date_ticket: '18:52', total: 50},
  {_id: 2, vendeur: 'Foo Bar', date_ticket: '12:12', total: 20},
  {_id: 3, vendeur: 'John Smith', date_ticket: '11:02', total: 10},
  {_id: 4, vendeur: 'Test Test', date_ticket: '05:10', total: 6000}
]
</code>```

And this is ther reoder and click functions:

```<code>$scope.reverse = false;
$scope.orderItems = function (item) {
$scope.reverse = !$scope.reverse;
  if (item != undefined) {
    if (item == $scope.orderItem) {
      $scope.orderType = $scope.orderType == '+' ? '-' : '+';
    }
    else {
      $scope.orderItem = item;
      $scope.orderType = '+';
    }
  }

  $('.iconOrder').removeClass('up').removeClass('down');
  if ($scope.orderType == '+') {
    $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('down')
  }
  else {
    $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('up')
  }

  return $scope.orderType + $scope.orderItem;
}
$scope.goToCaissePage = function (id) {
  id = id.replace("app/caisse/", "");
  console.log(id);
};
</code>```

And my Html Code

```<code><ion-list class="list articlesList swipedList" show-delete="showDelete">
      <ion-item class="item item-button-right stable-bg">
        <span class="row">
          <span class="col col-20" ng-click="orderItems('vendeur')">
            <strong>Vendeur</strong>
            <div class="iconOrder" name="vendeur">
              <i class="icon ion-android-arrow-dropup"></i>
              <i class="icon ion-android-arrow-dropdown"></i>
            </div>
          </span>
          <span class="col col-20" ng-click="orderItems('date_ticket')">
            <strong>Heure</strong>
            <div class="iconOrder" name="date_ticket">
              <i class="icon ion-android-arrow-dropup"></i>
              <i class="icon ion-android-arrow-dropdown"></i>
            </div>
          </span>
          <span class="col col-10" ng-click="orderItems('total')">
            <strong>Total</strong>
            <div class="iconOrder" name="total">
              <i class="icon ion-android-arrow-dropup"></i>
              <i class="icon ion-android-arrow-dropdown"></i>
            </div>
          </span>
        </span>
      </ion-item>

      <ion-item class="item item-button-right pad-item" ng-repeat="ticket in ticketsEncour | orderBy : orderBy : orderItem:reverse  track by $index">
        <span class="row">
          <span class="col col-20 col-pad" ng-click="goToCaissePage('app/caisse/{{ticket._id}}')">
            <div>
              <a href="" style="color: #333; text-decoration: none">{{ ticket.vendeur }}</a>
            </div>
          </span>
          <span class="col col-20 col-pad" ng-click="goToCaissePage('app/caisse/{{ticket._id}}')">
            <div>
              <a href="" style="color: #333; text-decoration: none">{{ ticket.date_ticket | date:'HH:mm' }}</a>
            </div>
          </span>
          <span class="col col-10 col-pad" ng-click="goToCaissePage('app/caisse/{{ticket._id}}')">
            <div>
              <a href="" style="color: #333; text-decoration: none">{{ ticket.total.toFixed(2) }}€</a>
            </div>
          </span>
        </span>
      </ion-item>
    </ion-list>
</code>```

When i click on any item of the ng-repeat it shows the right id in the console. But when i use the reorder i can is that the HTML has changed but the ng-click function render always the old one:

click on index 0 => console 1 (perfect)

After reoder with any type:

click on index 0 => console 1 (expected 3 for example)

Thanks

Update: changed the array name (copy cut error)

Updated with @Weijian suggestion

答:
I suggest using the orderBy that uses the scope variables directly. This is also the method suggested by the angular docs.

js

```<code>$scope.reverse = false;
$scope.orderItems = function (item) {
    if( item == $scope.orderItem ){
        $scope.reverse = !$scope.reverse;
    }
    $scope.orderItem = item;
    $('.iconOrder').removeClass('up').removeClass('down');
    if( $scope.reverse ){
        $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('down');
    }
    else {
        $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('up');
    }
}
</code>```

html

```<code>orderBy:orderItem:reverse
</code>```

https://docs.angularjs.org/api/ng/filter/orderBy

this way is cleaner since you avoid the mixed use of the orderItems function.

Title: Angularjs order by not working properly

Body:
I'm facing a little problem with order by that i could not underdstand.

When i reoder the array i can see that every thing is working perfectly, but the problem is in the ng-click function of the list.

For example if i have this array:

$scope.ticketsEncour = [
  {_id: 1, vendeur: 'John Doe', date_ticket: '18:52', total: 50},
  {_id: 2, vendeur: 'Foo Bar', date_ticket: '12:12', total: 20},
  {_id: 3, vendeur: 'John Smith', date_ticket: '11:02', total: 10},
  {_id: 4, vendeur: 'Test Test', date_ticket: '05:10', total: 6000}
]

And this is ther reoder and click functions:

$scope.reverse = false;
$scope.orderItems = function (item) {
$scope.reverse = !$scope.reverse;
  if (item != undefined) {
    if (item == $scope.orderItem) {
      $scope.orderType = $scope.orderType == '+' ? '-' : '+';
    }
    else {
      $scope.orderItem = item;
      $scope.orderType = '+';
    }
  }

  $('.iconOrder').removeClass('up').removeClass('down');
  if ($scope.orderType == '+') {
    $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('down')
  }
  else {
    $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('up')
  }

  return $scope.orderType + $scope.orderItem;
}
$scope.goToCaissePage = function (id) {
  id = id.replace("app/caisse/", "");
  console.log(id);
};

And my Html Code

<ion-list class="list articlesList swipedList" show-delete="showDelete">
      <ion-item class="item item-button-right stable-bg">

            Vendeur

            Heure

            Total

      </ion-item>

      <ion-item class="item item-button-right pad-item" ng-repeat="ticket in ticketsEncour | orderBy : orderBy : orderItem:reverse  track by $index">

              {{ ticket.vendeur }}

              {{ ticket.date_ticket | date:'HH:mm' }}

              {{ ticket.total.toFixed(2) }}€

      </ion-item>
    </ion-list>

When i click on any item of the ng-repeat it shows the right id in the console. But when i use the reorder i can is that the HTML has changed but the ng-click function render always the old one:

click on index 0 => console 1 (perfect)

After reoder with any type:

click on index 0 => console 1 (expected 3 for example)

Thanks

Update: changed the array name (copy cut error)

Updated with @Weijian suggestion

Body:
I suggest using the orderBy that uses the scope variables directly. This is also the method suggested by the angular docs.

js

$scope.reverse = false;
$scope.orderItems = function (item) {
    if( item == $scope.orderItem ){
        $scope.reverse = !$scope.reverse;
    }
    $scope.orderItem = item;
    $('.iconOrder').removeClass('up').removeClass('down');
    if( $scope.reverse ){
        $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('down');
    }
    else {
        $('.iconOrder[name="' + $scope.orderItem + '"]').addClass('up');
    }
}

html

orderBy:orderItem:reverse

https://docs.angularjs.org/api/ng/filter/orderBy

this way is cleaner since you avoid the mixed use of the orderItems function.


问:
Receiving ParseException with String containing ISO 8601 Formatted Date using Java 1.6
Keep getting a ParseException when I try to parse a ISO 8601 formatted String into a Java Date  type.

```<code>String myDateString = "2014-07-04T22:59:36Z";
TimeZone timeZone = TimeZone.getTimeZone("UTC");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.US);
dateFormat.setTimeZone(timeZone);
Date formattedDate = dateFormat.parse(myDateString);
</code>```

Keeps returning a ParseException:

```<code>Unparseable date: "2014-07-04T22:59:36Z"
</code>```

What am I possibly doing wrong?

答:
tl;dr

For Java 6 & 7, add the ThreeTen-Backport library to your project. For Java 8 and later, java.time is built-in.

```<code>Instant.parse( "2014-07-04T22:59:36Z" )
</code>```

java.time

The modern way is with the java.time classes that supplant the troublesome old legacy date-time classes such as SimpleDateFormat, Date, and Calendar.

While built into Java 8 and later, a back-port to Java 6 and Java 7 is available. (see below)

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern. The Instant class can directly parse your input string.

```<code>Instant instant = Instant.parse( "2014-07-04T22:59:36Z" );
</code>```

To generate a String in standard ISO 8601 format, simply call toString.

```<code>String output = instant.toString();
</code>```

2014-07-04T22:59:36Z

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Body:
Keep getting a ParseException when I try to parse a ISO 8601 formatted String into a Java Date  type.

String myDateString = "2014-07-04T22:59:36Z";
TimeZone timeZone = TimeZone.getTimeZone("UTC");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.US);
dateFormat.setTimeZone(timeZone);
Date formattedDate = dateFormat.parse(myDateString);

Keeps returning a ParseException:

Unparseable date: "2014-07-04T22:59:36Z"

What am I possibly doing wrong?

Body:
tl;dr

For Java 6 & 7, add the ThreeTen-Backport library to your project. For Java 8 and later, java.time is built-in.

Instant.parse( "2014-07-04T22:59:36Z" )

java.time

The modern way is with the java.time classes that supplant the troublesome old legacy date-time classes such as SimpleDateFormat, Date, and Calendar.

While built into Java 8 and later, a back-port to Java 6 and Java 7 is available. (see below)

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern. The Instant class can directly parse your input string.

Instant instant = Instant.parse( "2014-07-04T22:59:36Z" );

To generate a String in standard ISO 8601 format, simply call toString.

String output = instant.toString();

2014-07-04T22:59:36Z

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
Custom syntax highlighting in jupyter notebook
I have a special family of functions used for different type of tracing and verbose output, calls to which are sprinkled throughout my code. I've given them a prefix and I often search for that prefix. However, I realized I spend so much time looking for and editing these functions that I'd like to make it a bit more streamlined if possible. I would like to add syntax highlighting to any calls to these functions so that they are easy to find.

I work in Jupyter Notebook, is it's doable to add syntax highlighting with a unique color to calls to any of a specified set of functions in Jupyter Notebooks without rewriting half of Jupyter and how would I go about it?

答:
I don't know if I understand your question correctly. But if you require a addon which highlights the selected variable on Jupyter Notebook you can install the following Repo in your python/Jupyter notebook version

Jupyter Highlight Selected word

Note that you should run the jupyter nbextension enable highlight_selected_word/main on every environment you have by activating each environment and runing that command in the command line (if using Conda or other package manager)


答:
I've come across this situation often enough that I've written a simple extension method for it.

```<code>public static bool In<T>(this T val, params T[] options)
{
    return options.Contains(val);
}
</code>```

And then to use it in your code statement

```<code>else if (clr9[0].In(clr9.Skip(1).ToArray()))
</code>```

Edit based on comment by OP, this works just as well:

```<code>else if (clr9[0].In(clr9[1], clr9[2], clr9[3]))
</code>```

Or

```<code>else if (clr9[0].In(clr9.Skip(1).Take(3).ToArray())
</code>```

Title: Compare All Strings in a List - C#

Body:
I've come across this situation often enough that I've written a simple extension method for it.

public static bool In<T>(this T val, params T[] options)
{
    return options.Contains(val);
}

And then to use it in your code statement

else if (clr9[0].In(clr9.Skip(1).ToArray()))

Edit based on comment by OP, this works just as well:

else if (clr9[0].In(clr9[1], clr9[2], clr9[3]))

Or

else if (clr9[0].In(clr9.Skip(1).Take(3).ToArray())


问:
What are all of the generic collections/types in the 4.0 .NET Framework?
Is there an exhaustive list of all of the "base" (not used in an object-oriented sense but more in a common sense) generic types in the 4.0 .NET Framework? I have found this list that I often send newer/mid-level devs to so they can understand how non-generic types map to generic types, but this is by no means exhaustive. I'm looking for something that also includes things such as KeyValuePair<>, Tuple<>, and other basic generics that may not be very-well known. Interfaces such as IObservable<> would be nice but not necessarily required.

答:
Here's my code. Add more assemblies as you desire.

```<code>    static void Main(string[] args)
    {
        Assembly[] assemblies = new Assembly[] {
            typeof(string).Assembly,
            typeof(Uri).Assembly,
            typeof(System.Linq.Enumerable).Assembly};

        List<string> final = new List<string>();

        Debug.WriteLine("Checked assemblies: ");
        foreach (Assembly assembly in assemblies)
        {
            Debug.WriteLine(assembly.FullName);

            Type[] types = assembly.GetTypes();
            IEnumerable<Type> genericTypes = types.Where(t => t.IsGenericType && t.IsPublic);
            foreach (Type t in genericTypes)
            {
                final.Add(t.FullName);
            }
        }

        final.Sort();

        Debug.WriteLine("Generic classes: ");
        foreach (string s in final)
        {
            Debug.WriteLine(s);
        }
    }
</code>```

Results:

Checked assemblies:

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Generic classes:

System.Action`1

System.Action`10

System.Action`11

System.Action`12

System.Action`13

System.Action`14

System.Action`15

System.Action`16

System.Action`2

System.Action`3

System.Action`4

System.Action`5

System.Action`6

System.Action`7

System.Action`8

System.Action`9

System.ArraySegment`1

System.Collections.Concurrent.BlockingCollection`1

System.Collections.Concurrent.ConcurrentBag`1

System.Collections.Concurrent.ConcurrentDictionary`2

System.Collections.Concurrent.ConcurrentQueue`1

System.Collections.Concurrent.ConcurrentStack`1

System.Collections.Concurrent.IProducerConsumerCollection`1

System.Collections.Concurrent.OrderablePartitioner`1

System.Collections.Concurrent.Partitioner`1

System.Collections.Generic.Comparer`1

System.Collections.Generic.Dictionary`2

System.Collections.Generic.EqualityComparer`1

System.Collections.Generic.HashSet`1

System.Collections.Generic.ICollection`1

System.Collections.Generic.IComparer`1

System.Collections.Generic.IDictionary`2

System.Collections.Generic.IEnumerable`1

System.Collections.Generic.IEnumerator`1

System.Collections.Generic.IEqualityComparer`1

System.Collections.Generic.IList`1

System.Collections.Generic.ISet`1

System.Collections.Generic.KeyValuePair`2

System.Collections.Generic.LinkedList`1

System.Collections.Generic.LinkedListNode`1

System.Collections.Generic.List`1

System.Collections.Generic.Queue`1

System.Collections.Generic.SortedDictionary`2

System.Collections.Generic.SortedList`2

System.Collections.Generic.SortedSet`1

System.Collections.Generic.Stack`1

System.Collections.ObjectModel.Collection`1

System.Collections.ObjectModel.KeyedCollection`2

System.Collections.ObjectModel.ObservableCollection`1

System.Collections.ObjectModel.ReadOnlyCollection`1

System.Collections.ObjectModel.ReadOnlyObservableCollection`1

System.Comparison`1

System.ComponentModel.BindingList`1

System.Converter`2

System.EventHandler`1

System.Func`1

System.Func`10

System.Func`11

System.Func`12

System.Func`13

System.Func`14

System.Func`15

System.Func`16

System.Func`17

System.Func`2

System.Func`3

System.Func`4

System.Func`5

System.Func`6

System.Func`7

System.Func`8

System.Func`9

System.IComparable`1

System.IEquatable`1

System.IObservable`1

System.IObserver`1

System.Lazy`1

System.Linq.EnumerableExecutor`1

System.Linq.EnumerableQuery`1

System.Linq.Expressions.Expression`1

System.Linq.IGrouping`2

System.Linq.ILookup`2

System.Linq.IOrderedEnumerable`1

System.Linq.IOrderedQueryable`1

System.Linq.IQueryable`1

System.Linq.Lookup`2

System.Linq.OrderedParallelQuery`1

System.Linq.ParallelQuery`1

System.Nullable`1

System.Predicate`1

System.Runtime.CompilerServices.CallSite`1

System.Runtime.CompilerServices.ConditionalWeakTable`2

System.Runtime.CompilerServices.ReadOnlyCollectionBuilder`1

System.Runtime.CompilerServices.RuleCache`1

System.Runtime.CompilerServices.StrongBox`1

System.Security.AccessControl.AccessRule`1

System.Security.AccessControl.AuditRule`1

System.Security.AccessControl.ObjectSecurity`1

System.Threading.Tasks.Task`1

System.Threading.Tasks.TaskCompletionSource`1

System.Threading.Tasks.TaskFactory`1

System.Threading.ThreadLocal`1

System.Tuple`1

System.Tuple`2

System.Tuple`3

System.Tuple`4

System.Tuple`5

System.Tuple`6

System.Tuple`7

System.Tuple`8

Body:
Here's my code. Add more assemblies as you desire.

    static void Main(string[] args)
    {
        Assembly[] assemblies = new Assembly[] {
            typeof(string).Assembly,
            typeof(Uri).Assembly,
            typeof(System.Linq.Enumerable).Assembly};

        List<string> final = new List<string>();

        Debug.WriteLine("Checked assemblies: ");
        foreach (Assembly assembly in assemblies)
        {
            Debug.WriteLine(assembly.FullName);

            Type[] types = assembly.GetTypes();
            IEnumerable<Type> genericTypes = types.Where(t => t.IsGenericType && t.IsPublic);
            foreach (Type t in genericTypes)
            {
                final.Add(t.FullName);
            }
        }

        final.Sort();

        Debug.WriteLine("Generic classes: ");
        foreach (string s in final)
        {
            Debug.WriteLine(s);
        }
    }

Results:

Checked assemblies:

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Generic classes:

System.Action`1

System.Action`10

System.Action`11

System.Action`12

System.Action`13

System.Action`14

System.Action`15

System.Action`16

System.Action`2

System.Action`3

System.Action`4

System.Action`5

System.Action`6

System.Action`7

System.Action`8

System.Action`9

System.ArraySegment`1

System.Collections.Concurrent.BlockingCollection`1

System.Collections.Concurrent.ConcurrentBag`1

System.Collections.Concurrent.ConcurrentDictionary`2

System.Collections.Concurrent.ConcurrentQueue`1

System.Collections.Concurrent.ConcurrentStack`1

System.Collections.Concurrent.IProducerConsumerCollection`1

System.Collections.Concurrent.OrderablePartitioner`1

System.Collections.Concurrent.Partitioner`1

System.Collections.Generic.Comparer`1

System.Collections.Generic.Dictionary`2

System.Collections.Generic.EqualityComparer`1

System.Collections.Generic.HashSet`1

System.Collections.Generic.ICollection`1

System.Collections.Generic.IComparer`1

System.Collections.Generic.IDictionary`2

System.Collections.Generic.IEnumerable`1

System.Collections.Generic.IEnumerator`1

System.Collections.Generic.IEqualityComparer`1

System.Collections.Generic.IList`1

System.Collections.Generic.ISet`1

System.Collections.Generic.KeyValuePair`2

System.Collections.Generic.LinkedList`1

System.Collections.Generic.LinkedListNode`1

System.Collections.Generic.List`1

System.Collections.Generic.Queue`1

System.Collections.Generic.SortedDictionary`2

System.Collections.Generic.SortedList`2

System.Collections.Generic.SortedSet`1

System.Collections.Generic.Stack`1

System.Collections.ObjectModel.Collection`1

System.Collections.ObjectModel.KeyedCollection`2

System.Collections.ObjectModel.ObservableCollection`1

System.Collections.ObjectModel.ReadOnlyCollection`1

System.Collections.ObjectModel.ReadOnlyObservableCollection`1

System.Comparison`1

System.ComponentModel.BindingList`1

System.Converter`2

System.EventHandler`1

System.Func`1

System.Func`10

System.Func`11

System.Func`12

System.Func`13

System.Func`14

System.Func`15

System.Func`16

System.Func`17

System.Func`2

System.Func`3

System.Func`4

System.Func`5

System.Func`6

System.Func`7

System.Func`8

System.Func`9

System.IComparable`1

System.IEquatable`1

System.IObservable`1

System.IObserver`1

System.Lazy`1

System.Linq.EnumerableExecutor`1

System.Linq.EnumerableQuery`1

System.Linq.Expressions.Expression`1

System.Linq.IGrouping`2

System.Linq.ILookup`2

System.Linq.IOrderedEnumerable`1

System.Linq.IOrderedQueryable`1

System.Linq.IQueryable`1

System.Linq.Lookup`2

System.Linq.OrderedParallelQuery`1

System.Linq.ParallelQuery`1

System.Nullable`1

System.Predicate`1

System.Runtime.CompilerServices.CallSite`1

System.Runtime.CompilerServices.ConditionalWeakTable`2

System.Runtime.CompilerServices.ReadOnlyCollectionBuilder`1

System.Runtime.CompilerServices.RuleCache`1

System.Runtime.CompilerServices.StrongBox`1

System.Security.AccessControl.AccessRule`1

System.Security.AccessControl.AuditRule`1

System.Security.AccessControl.ObjectSecurity`1

System.Threading.Tasks.Task`1

System.Threading.Tasks.TaskCompletionSource`1

System.Threading.Tasks.TaskFactory`1

System.Threading.ThreadLocal`1

System.Tuple`1

System.Tuple`2

System.Tuple`3

System.Tuple`4

System.Tuple`5

System.Tuple`6

System.Tuple`7

System.Tuple`8


问:
mask only where consecutive nans exceeds x
I was answering a question about pandas interpolation method.  The OP wanted to use only interpolate where the number of consecutive np.nans was one.  The limit=1 option for interpolate will interpolate the first np.nan and stop there.  OP wanted to be able to tell that there were in fact more than one np.nan and not even bother with the first one.

I boiled this down to just executing the interpolate as is and mask the consecutive np.nan after the fact.

The question is: What is a generalized solution that takes a 1-d array a and an integer x and produces a boolean mask with False in the positions of x or more consecutive np.nan

Consider the 1-d array a

```<code>a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1])
</code>```

I'd expect that for x = 2 the mask would look like this

```<code># assume 1 for True and 0 for False
# a is [  1.  nan  nan  nan   1.  nan   1.   1.  nan  nan   1.   1.]
# mask [  1.   0.   0.   0.   1.   1.   1.   1.   0.   0.   1.   1.]
#                                  ^
#                                  |
#   Notice that this is not masked because there is only one np.nan
</code>```

I'd expect that for x = 3 the mask would look like this

```<code># assume 1 for True and 0 for False
# a is [  1.  nan  nan  nan   1.  nan   1.   1.  nan  nan   1.   1.]
# mask [  1.   0.   0.   0.   1.   1.   1.   1.   1.   1.   1.   1.]
#                                  ^              ^    ^
#                                  |              |    |
# Notice that this is not masked because there is less than 3 np.nan's
</code>```

I look forward to learning from others ideas ;-)

答:
I really like numba for such easy to grasp but hard to "numpyfy" problems! Even though that package might be a bit too heavy for most libraries it allows to write such "python"-like functions without loosing too much speed:

```<code>import numpy as np
import numba as nb
import math

@nb.njit
def mask_nan_if_consecutive(arr, limit):  # I'm not good at function names :(
    result = np.ones_like(arr)
    cnt = 0
    for idx in range(len(arr)):
        if math.isnan(arr[idx]):
            cnt += 1
            # If we just reached the limit we need to backtrack,
            # otherwise just mask current.
            if cnt == limit:
                for subidx in range(idx-limit+1, idx+1):
                    result[subidx] = 0
            elif cnt > limit:
                result[idx] = 0
        else:
            cnt = 0

    return result
</code>```

At least if you worked with pure-python this should be quite easy to understand and it should work:

```<code>>>> a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1])
>>> mask_nan_if_consecutive(a, 1)
array([ 1.,  0.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  0.,  1.,  1.])
>>> mask_nan_if_consecutive(a, 2)
array([ 1.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  0.,  0.,  1.,  1.])
>>> mask_nan_if_consecutive(a, 3)
array([ 1.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
>>> mask_nan_if_consecutive(a, 4)
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
</code>```

But the really nice thing about @nb.njit-decorator is, that this function will be fast:

```<code>a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1])
i = 2

res1 = mask_nan_if_consecutive(a, i)
res2 = mask_knans(a, i)
np.testing.assert_array_equal(res1, res2)

%timeit mask_nan_if_consecutive(a, i)  # 100000 loops, best of 3: 6.03 µs per loop
%timeit mask_knans(a, i)               # 1000 loops, best of 3: 302 µs per loop
</code>```

So for short arrays this is approximatly 50 times faster, even though the difference gets lower it's still faster for longer arrays:

```<code>a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1]*100000)
i = 2

%timeit mask_nan_if_consecutive(a, i)  # 10 loops, best of 3: 20.9 ms per loop
%timeit mask_knans(a, i)               # 10 loops, best of 3: 154 ms per loop
</code>```

Body:
I was answering a question about pandas interpolation method.  The OP wanted to use only interpolate where the number of consecutive np.nans was one.  The limit=1 option for interpolate will interpolate the first np.nan and stop there.  OP wanted to be able to tell that there were in fact more than one np.nan and not even bother with the first one.

I boiled this down to just executing the interpolate as is and mask the consecutive np.nan after the fact.

The question is: What is a generalized solution that takes a 1-d array a and an integer x and produces a boolean mask with False in the positions of x or more consecutive np.nan

Consider the 1-d array a

a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1])

I'd expect that for x = 2 the mask would look like this

# assume 1 for True and 0 for False
# a is [  1.  nan  nan  nan   1.  nan   1.   1.  nan  nan   1.   1.]
# mask [  1.   0.   0.   0.   1.   1.   1.   1.   0.   0.   1.   1.]
#                                  ^
#                                  |
#   Notice that this is not masked because there is only one np.nan

I'd expect that for x = 3 the mask would look like this

# assume 1 for True and 0 for False
# a is [  1.  nan  nan  nan   1.  nan   1.   1.  nan  nan   1.   1.]
# mask [  1.   0.   0.   0.   1.   1.   1.   1.   1.   1.   1.   1.]
#                                  ^              ^    ^
#                                  |              |    |
# Notice that this is not masked because there is less than 3 np.nan's

I look forward to learning from others ideas ;-)

Body:
I really like numba for such easy to grasp but hard to "numpyfy" problems! Even though that package might be a bit too heavy for most libraries it allows to write such "python"-like functions without loosing too much speed:

import numpy as np
import numba as nb
import math

@nb.njit
def mask_nan_if_consecutive(arr, limit):  # I'm not good at function names :(
    result = np.ones_like(arr)
    cnt = 0
    for idx in range(len(arr)):
        if math.isnan(arr[idx]):
            cnt += 1
            # If we just reached the limit we need to backtrack,
            # otherwise just mask current.
            if cnt == limit:
                for subidx in range(idx-limit+1, idx+1):
                    result[subidx] = 0
            elif cnt > limit:
                result[idx] = 0
        else:
            cnt = 0

    return result

At least if you worked with pure-python this should be quite easy to understand and it should work:

>>> a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1])
>>> mask_nan_if_consecutive(a, 1)
array([ 1.,  0.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  0.,  1.,  1.])
>>> mask_nan_if_consecutive(a, 2)
array([ 1.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  0.,  0.,  1.,  1.])
>>> mask_nan_if_consecutive(a, 3)
array([ 1.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
>>> mask_nan_if_consecutive(a, 4)
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

But the really nice thing about @nb.njit-decorator is, that this function will be fast:

a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1])
i = 2

res1 = mask_nan_if_consecutive(a, i)
res2 = mask_knans(a, i)
np.testing.assert_array_equal(res1, res2)

%timeit mask_nan_if_consecutive(a, i)  # 100000 loops, best of 3: 6.03 µs per loop
%timeit mask_knans(a, i)               # 1000 loops, best of 3: 302 µs per loop

So for short arrays this is approximatly 50 times faster, even though the difference gets lower it's still faster for longer arrays:

a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1]*100000)
i = 2

%timeit mask_nan_if_consecutive(a, i)  # 10 loops, best of 3: 20.9 ms per loop
%timeit mask_knans(a, i)               # 10 loops, best of 3: 154 ms per loop


问:
How to change the color of a selected item of a ComboboxItem which includes a TextBlock?
I have the following XAML of a Combobox:

```<code><ComboBox>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleGreen">1</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Salmon">2</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleTurquoise">3</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gold">4</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Black" Foreground="White">5</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gray">6</TextBlock>
    </ComboBoxItem>
</ComboBox>
</code>```

The following pictures shows my problem:

Combobox open

Combobox closed

So you can see in the picture "Combobox closed" that the number "4" has no color, but I want that the text "4" is yellow. Can you help me?

答:
You need to edit the template of the ComboBox.

Go to [Document Outline], right-click the ComboBox, Edit Template->Edit a Copy.

Then find the "ComboBoxEditableTemplate" and edit the Border the contains the "PART_EditableTextBox". Here's the specific part of the generated code::

```<code>...
<ControlTemplate x:Key="ComboBoxEditableTemplate"
                 TargetType="{x:Type ComboBox}">
    <Grid x:Name="templateRoot"
          SnapsToDevicePixels="true">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="0"
                              MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" />
        </Grid.ColumnDefinitions>
        <Popup x:Name="PART_Popup"
               Grid.ColumnSpan="2"
               AllowsTransparency="true"
               IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}"
               Placement="Bottom"
               PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}">
            <Themes:SystemDropShadowChrome x:Name="shadow"
                                           MinWidth="{Binding ActualWidth, ElementName=templateRoot}"
                                           MaxHeight="{TemplateBinding MaxDropDownHeight}"
                                           Color="Transparent">
                <Border x:Name="dropDownBorder"
                        Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
                        BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}"
                        BorderThickness="1">
                    <ScrollViewer x:Name="DropDownScrollViewer">
                        <Grid x:Name="grid"
                              RenderOptions.ClearTypeHint="Enabled">
                            <Canvas x:Name="canvas"
                                    Width="0"
                                    Height="0"
                                    HorizontalAlignment="Left"
                                    VerticalAlignment="Top">
                                <Rectangle x:Name="opaqueRect"
                                           Width="{Binding ActualWidth, ElementName=dropDownBorder}"
                                           Height="{Binding ActualHeight, ElementName=dropDownBorder}"
                                           Fill="{Binding Background, ElementName=dropDownBorder}" />
                            </Canvas>
                            <ItemsPresenter x:Name="ItemsPresenter"
                                            KeyboardNavigation.DirectionalNavigation="Contained"
                                            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Grid>
                    </ScrollViewer>
                </Border>
            </Themes:SystemDropShadowChrome>
        </Popup>
        <ToggleButton x:Name="toggleButton"
                      Grid.ColumnSpan="2"
                      Background="{TemplateBinding Background}"
                      BorderBrush="{TemplateBinding BorderBrush}"
                      BorderThickness="{TemplateBinding BorderThickness}"
                      IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                      Style="{StaticResource ComboBoxToggleButton}" />
<!--  EDIT THIS PART LIKE SO  -->
        <Border x:Name="border"
                Margin="{TemplateBinding BorderThickness}"
                Background="{Binding SelectedItem.Background, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, FallbackValue=Transparent}">
            <!--  Background="{StaticResource TextBox.Static.Background}">  -->
<!-- //////////////////////// -->
            <TextBox x:Name="PART_EditableTextBox"
                     Margin="{TemplateBinding Padding}"
                     HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                     VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                     IsReadOnly="{Binding IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
                     Style="{StaticResource ComboBoxEditableTextBox}" />
        </Border>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <Setter TargetName="border" Property="Opacity" Value="0.56" />
        </Trigger>
        <Trigger Property="IsKeyboardFocusWithin" Value="true">
            <Setter Property="Foreground" Value="Black" />
        </Trigger>
        <Trigger SourceName="PART_Popup" Property="HasDropShadow" Value="true">
            <Setter TargetName="shadow" Property="Margin" Value="0,0,5,5" />
            <Setter TargetName="shadow" Property="Color" Value="#71000000" />
        </Trigger>
        <Trigger Property="HasItems" Value="false">
            <Setter TargetName="dropDownBorder" Property="Height" Value="95" />
        </Trigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsGrouping" Value="true" />
                <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="false" />
            </MultiTrigger.Conditions>
            <Setter Property="ScrollViewer.CanContentScroll" Value="false" />
        </MultiTrigger>
        <Trigger SourceName="DropDownScrollViewer" Property="ScrollViewer.CanContentScroll" Value="false">
            <Setter TargetName="opaqueRect" Property="Canvas.Top" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}" />
            <Setter TargetName="opaqueRect" Property="Canvas.Left" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
...
</code>```

After that, you can use it like the following, without using TextBlocks:

```<code>    <ComboBox IsEditable="True"
              Style="{DynamicResource YourComboBoxStyleName}">
        <ComboBoxItem Background="PaleGreen"
                      Content="1"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Salmon"
                      Content="2"
                      FontWeight="Bold" />
        <ComboBoxItem Background="PaleTurquoise"
                      Content="3"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Gold"
                      Content="4"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Black"
                      Content="5"
                      FontWeight="Bold"
                      Foreground="White" />
        <ComboBoxItem Background="Gray"
                      Content="6"
                      FontWeight="Bold" />
    </ComboBox>
</code>```

Body:
I have the following XAML of a Combobox:

<ComboBox>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleGreen">1</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Salmon">2</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleTurquoise">3</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gold">4</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Black" Foreground="White">5</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gray">6</TextBlock>
    </ComboBoxItem>
</ComboBox>

The following pictures shows my problem:

Combobox open

Combobox closed

So you can see in the picture "Combobox closed" that the number "4" has no color, but I want that the text "4" is yellow. Can you help me?

Body:
You need to edit the template of the ComboBox.

Go to [Document Outline], right-click the ComboBox, Edit Template->Edit a Copy.

Then find the "ComboBoxEditableTemplate" and edit the Border the contains the "PART_EditableTextBox". Here's the specific part of the generated code::

...
<ControlTemplate x:Key="ComboBoxEditableTemplate"
                 TargetType="{x:Type ComboBox}">
    <Grid x:Name="templateRoot"
          SnapsToDevicePixels="true">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="0"
                              MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" />
        </Grid.ColumnDefinitions>
        <Popup x:Name="PART_Popup"
               Grid.ColumnSpan="2"
               AllowsTransparency="true"
               IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}"
               Placement="Bottom"
               PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}">
            <Themes:SystemDropShadowChrome x:Name="shadow"
                                           MinWidth="{Binding ActualWidth, ElementName=templateRoot}"
                                           MaxHeight="{TemplateBinding MaxDropDownHeight}"
                                           Color="Transparent">
                <Border x:Name="dropDownBorder"
                        Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
                        BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}"
                        BorderThickness="1">
                    <ScrollViewer x:Name="DropDownScrollViewer">
                        <Grid x:Name="grid"
                              RenderOptions.ClearTypeHint="Enabled">
                            <Canvas x:Name="canvas"
                                    Width="0"
                                    Height="0"
                                    HorizontalAlignment="Left"
                                    VerticalAlignment="Top">
                                <Rectangle x:Name="opaqueRect"
                                           Width="{Binding ActualWidth, ElementName=dropDownBorder}"
                                           Height="{Binding ActualHeight, ElementName=dropDownBorder}"
                                           Fill="{Binding Background, ElementName=dropDownBorder}" />
                            </Canvas>
                            <ItemsPresenter x:Name="ItemsPresenter"
                                            KeyboardNavigation.DirectionalNavigation="Contained"
                                            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Grid>
                    </ScrollViewer>
                </Border>
            </Themes:SystemDropShadowChrome>
        </Popup>
        <ToggleButton x:Name="toggleButton"
                      Grid.ColumnSpan="2"
                      Background="{TemplateBinding Background}"
                      BorderBrush="{TemplateBinding BorderBrush}"
                      BorderThickness="{TemplateBinding BorderThickness}"
                      IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                      Style="{StaticResource ComboBoxToggleButton}" />
<!--  EDIT THIS PART LIKE SO  -->
        <Border x:Name="border"
                Margin="{TemplateBinding BorderThickness}"
                Background="{Binding SelectedItem.Background, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, FallbackValue=Transparent}">
            <!--  Background="{StaticResource TextBox.Static.Background}">  -->
<!-- //////////////////////// -->
            <TextBox x:Name="PART_EditableTextBox"
                     Margin="{TemplateBinding Padding}"
                     HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                     VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                     IsReadOnly="{Binding IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
                     Style="{StaticResource ComboBoxEditableTextBox}" />
        </Border>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <Setter TargetName="border" Property="Opacity" Value="0.56" />
        </Trigger>
        <Trigger Property="IsKeyboardFocusWithin" Value="true">
            <Setter Property="Foreground" Value="Black" />
        </Trigger>
        <Trigger SourceName="PART_Popup" Property="HasDropShadow" Value="true">
            <Setter TargetName="shadow" Property="Margin" Value="0,0,5,5" />
            <Setter TargetName="shadow" Property="Color" Value="#71000000" />
        </Trigger>
        <Trigger Property="HasItems" Value="false">
            <Setter TargetName="dropDownBorder" Property="Height" Value="95" />
        </Trigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsGrouping" Value="true" />
                <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="false" />
            </MultiTrigger.Conditions>
            <Setter Property="ScrollViewer.CanContentScroll" Value="false" />
        </MultiTrigger>
        <Trigger SourceName="DropDownScrollViewer" Property="ScrollViewer.CanContentScroll" Value="false">
            <Setter TargetName="opaqueRect" Property="Canvas.Top" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}" />
            <Setter TargetName="opaqueRect" Property="Canvas.Left" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
...

After that, you can use it like the following, without using TextBlocks:

    <ComboBox IsEditable="True"
              Style="{DynamicResource YourComboBoxStyleName}">
        <ComboBoxItem Background="PaleGreen"
                      Content="1"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Salmon"
                      Content="2"
                      FontWeight="Bold" />
        <ComboBoxItem Background="PaleTurquoise"
                      Content="3"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Gold"
                      Content="4"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Black"
                      Content="5"
                      FontWeight="Bold"
                      Foreground="White" />
        <ComboBoxItem Background="Gray"
                      Content="6"
                      FontWeight="Bold" />
    </ComboBox>


问:
Externalizing a module in Angular 2
So, i was working on my application and i realized that several modules could be extracted to separate libraries, that could be installed via NPM and reused across other applications. The current structure looks like this:

```<code>app/
    search/
        component1/
        component2/
        component3/
        search.module.ts
        search.service.ts
    login/
    register/
</code>```

Let's say i want to extract search, what's the first step? How do i organize this separate repository? Does it also have a src dir and a package.json? Is there any specific documentation on this topic?

答:
I would recommend you the official style guide that recommends you the folder structure and some conventions when creating modules.

https://angular.io/styleguide#!#application-structure-and-angular-modules

additionally as I see you are starting I would also suggest

https://github.com/angular/angular-cli

this tool allows you to create modules, components and other staff from command line and follows some rules from the style guide.

Title: Externalizing a module in Angular 2

Body:
So, i was working on my application and i realized that several modules could be extracted to separate libraries, that could be installed via NPM and reused across other applications. The current structure looks like this:

app/
    search/
        component1/
        component2/
        component3/
        search.module.ts
        search.service.ts
    login/
    register/

Let's say i want to extract search, what's the first step? How do i organize this separate repository? Does it also have a src dir and a package.json? Is there any specific documentation on this topic?


问:
Why does console.log strip characters in nodejs?
My nodejs code is reading from a stream and print it on the console. I found an interested behaviour that console.log strips characters for me. For example, below is the debug window on my nodejs.

From this debug window you can see that the value of line includes some Ansi encoding characters. But when I print it to terminal by console.log, I just got this output > var prompt="dbenvy> ". It doesn't have any ansi characters. I don't understand what cause this behaviour. I am not sure whether this is something to do with console.log or terminal

答: You did not mention if it was displaying the letters in the color or format indicated by the ANSI Escape codes.  Your debugger does not support ANSI Escape, but your terminal does have at least some support -- if it is not showing the colors, at least it knows not to dump the escape codes as text.</p>


问:
SQL - Order by time, then text on beginning
I have a query below :

SELECT DISTINCT TimeSched from tbl_schedule

It returns this result:

```<code>TimeSched

Rest Day
11:00 AM - 08:00 PM
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
</code>```

When I use ORDER BY TimeSched, it returns this result:

```<code>TimeSched

09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
No Schedule
Rest Day
</code>```

However, my desired result is I want 'Rest Day' and 'No Schedule' on the first and second row by default, then followed by the order of schedules in ascending order. As seen below :

```<code>TimeSched

Rest Day
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
</code>```

答:
try this.

```<code>select * from timetable
order by
iif(timesched in ('No Schedule','Rest Day'),'01' + timesched,timesched)
</code>```

Append a prefix for No Schedule and Restday with
  01 when ordering.. so 01No will go 1, 01R will go next then your 09 to
  24

Body:
I have a query below :

SELECT DISTINCT TimeSched from tbl_schedule

It returns this result:

TimeSched

Rest Day
11:00 AM - 08:00 PM
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM

When I use ORDER BY TimeSched, it returns this result:

TimeSched

09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
No Schedule
Rest Day

However, my desired result is I want 'Rest Day' and 'No Schedule' on the first and second row by default, then followed by the order of schedules in ascending order. As seen below :

TimeSched

Rest Day
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM

Body:
try this.

select * from timetable
order by
iif(timesched in ('No Schedule','Rest Day'),'01' + timesched,timesched)

Append a prefix for No Schedule and Restday with
  01 when ordering.. so 01No will go 1, 01R will go next then your 09 to
  24


问:
Background image not appearing in compiled CHM file - Html workshop
I've recently re-compiled a .chm file as a lot of changes needed to be made in each html file.

The main problem I'm having when simply recompiling these files is the background image. The code in one of the html files is as follows:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>How to Create a File</title>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" media="screen" type="text/css" title="Design"
  href="design.css" />
  <!--(Style Sheet)===================================================-->
  <style>
body { background-image:url("Background.gif"); background-repeat:repeat; background-attachment:scroll;  }</style>
</head>
</code>```

The compiled version that was there before worked and kept the background. I have simply changed the text in the html files using Amaya and now it doesn't work!

The other problem is that if I rename all the files and change the index files etc accordingly, I ALSO loose the boxes I have around titled sections etc. So I have had to resort back to the old named and seriously unorganised files!

All of the images I'm using are in the same folder so this is not the problem.

Does any one know why this is happening? Any help would be hugely appreciated!

Thank you!

答:
Convert image to base 64 first and then,

For use in  elements:

```<code><img src='data:image/png;base64,iVBOR.....'/>
</code>```

For use as CSS background:

```<code>url('data:image/png;base64,iVBOR...............'
</code>```

Body:
I've recently re-compiled a .chm file as a lot of changes needed to be made in each html file.

The main problem I'm having when simply recompiling these files is the background image. The code in one of the html files is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>How to Create a File</title>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" media="screen" type="text/css" title="Design"
  href="design.css" />

The compiled version that was there before worked and kept the background. I have simply changed the text in the html files using Amaya and now it doesn't work!

The other problem is that if I rename all the files and change the index files etc accordingly, I ALSO loose the boxes I have around titled sections etc. So I have had to resort back to the old named and seriously unorganised files!

All of the images I'm using are in the same folder so this is not the problem.

Does any one know why this is happening? Any help would be hugely appreciated!

Thank you!

Body:
Convert image to base 64 first and then,

For use in <img> elements:

<img src='data:image/png;base64,iVBOR.....'/>

For use as CSS background:

url('data:image/png;base64,iVBOR...............'