问:
Disable cascade delete with EF?
I have 2 entities linked by a one-to-many relationship as follows (I used code first):

```<code>public class Computer
{
    [Key]
    public int ComputerId { get; set; }

    [Required]
    public int ComputerIdInventory { get; set; }

    [DataType(DataType.Date)]
    public DateTime? AcquisitionDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? LastUpdate { get; set; }

    public string Comment { get; set; }

    //Foreign keys
    public int? ComputerModelId { get; set; }

    public int? EmployeeId { get; set; }

    //Navigation properties
    public virtual ICollection<Screen> Screens { get; set; }
}

public class Screen
{
    [Key]
    public int ScreenId { get; set; }

    [Required]
    public int ScreenIdInventory { get; set; }

    public string Comment { get; set; }

    //Foreign keys
    public int? ComputerId { get; set; }

    //Navigation properties
    public virtual Computer Computer { get; set; }
}
</code>```

When I delete a computer that is linked to one or many screens, I have the following error:

[SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Screen_dbo.Computer_ComputerId". The conflict occurred in database "CPInventory", table "dbo.Screen", column 'ComputerId'.

I have read many posts, and I tried 2 things that seemed to have worked for others. I changed the "OnModelCreating" method and added :

```<code>modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
</code>```

And I tried this too:

```<code>modelBuilder.Entity<Computer>()
            .HasMany<Screen>(c => c.Screens)
            .WithOptional(s => s.Computer)
            .WillCascadeOnDelete(false);
</code>```

But none of the solutions worked... Am I doing something wrong ? I also update the database but nothing has changed. Do I have to completely drop my database and recreate it in order for those changes to be taken into account?

Thank a lot !

Edit:
Here is the delete code

```<code>public ActionResult DeleteConfirmed(int id)
    {
        Computer computer = db.Computers.Find(id);
        db.Computers.Remove(computer);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
</code>```

答:
The problem is you have a foreign key constraint in the database that says you can't delete a parent row (computer) if there are child rows (screens) in the database.

This is the reason you have cascade delete function in the first place, so deleting the computer deletes the screens as well.

Your only other option is to delete all the screens with the same ComputerID before deleting the Computer.  (or why not just turn on cascade deletes and let the framework do it for you)

Title: Disable cascade delete with EF?

Body:
I have 2 entities linked by a one-to-many relationship as follows (I used code first):

public class Computer
{
    [Key]
    public int ComputerId { get; set; }

    [Required]
    public int ComputerIdInventory { get; set; }

    [DataType(DataType.Date)]
    public DateTime? AcquisitionDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? LastUpdate { get; set; }

    public string Comment { get; set; }

    //Foreign keys
    public int? ComputerModelId { get; set; }

    public int? EmployeeId { get; set; }

    //Navigation properties
    public virtual ICollection<Screen> Screens { get; set; }
}

public class Screen
{
    [Key]
    public int ScreenId { get; set; }

    [Required]
    public int ScreenIdInventory { get; set; }

    public string Comment { get; set; }

    //Foreign keys
    public int? ComputerId { get; set; }

    //Navigation properties
    public virtual Computer Computer { get; set; }
}

When I delete a computer that is linked to one or many screens, I have the following error:

[SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Screen_dbo.Computer_ComputerId". The conflict occurred in database "CPInventory", table "dbo.Screen", column 'ComputerId'.

I have read many posts, and I tried 2 things that seemed to have worked for others. I changed the "OnModelCreating" method and added :

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

And I tried this too:

modelBuilder.Entity<Computer>()
            .HasMany<Screen>(c => c.Screens)
            .WithOptional(s => s.Computer)
            .WillCascadeOnDelete(false);

But none of the solutions worked... Am I doing something wrong ? I also update the database but nothing has changed. Do I have to completely drop my database and recreate it in order for those changes to be taken into account?

Thank a lot !

Edit:
Here is the delete code

public ActionResult DeleteConfirmed(int id)
    {
        Computer computer = db.Computers.Find(id);
        db.Computers.Remove(computer);
        db.SaveChanges();
        return RedirectToAction("Index");
    }


来源: stackexchange

问:
Check for the google maps spelling of a location's name
I want to get the travel time between some airports in Europe with google maps. The thing is that some spellings of the names are not accurate, so, I want to first check for wrong names and get google's version of the names. From this question, I am able to use selenium to do that, but my code has some issues, 1) the output is not always complete, (last two result are only one alphabet) 2) it throws an exception at the end of the list (see below). Please help me fix the code. Automating this is the only way as the list of airports is very long.

Input:

```<code>wronglySpelled = ['Treviso (San Angelo) Airport', 'Milano - Malpensa
       Airport', 'Venezia - Tessera Airport', 'Milano - Linate Airport',
       'Treviso (San Angelo) Airport', 'Treviso (San Angelo) Airport',
      'Milano - Malpensa Airport', 'Venezia - Tessera Airport', 'Guernsey
       Channel Is. Airport', 'Jersey Channel Is. Airport','Treviso (San
                     Angelo) Airport']
</code>```

Code:

```<code>def setup():
    driver = webdriver.Chrome()
    driver.get("http://maps.google.com")
    driver.maximize_window() # For maximizing window
    driver.implicitly_wait(20) # gives an implicit wait for 20 seconds
    return driver

def correct_name(driver, name_to_check):
    searchBox = driver.find_element_by_name('q')
    searchBox.send_keys(name_to_check)
    correct_name = driver.find_element_by_class_name('suggest-bold')
    return correct_name.text.encode('utf-8')

driver = setup()
for item in wronglySpelled:
    print item,':', correct_name(driver, item)
    time.sleep(5)
    driver.find_element_by_id('searchboxinput').clear()
driver.quit()
</code>```

Error message:

```<code>Traceback (most recent call last):
  File "C:/...", line 60, in <module>
    print item,':', correct_name(driver, item)
  File "C:/...", line 41, in correct_name
    correct_name = driver.find_element_by_class_name('suggest-bold')
  File "C:\...", line 415, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\...", line 756, in find_element
    'value': value})['value']
  File "C:\...", line 238, in execute
    self.error_handler.check_response(response)
  File "C:\...", line 193, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"suggest-bold"}
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 10.0.14393 x86_64)
</code>```

output:

```<code>## Formatted as Input name : Google maps version
Treviso (San Angelo) Airport : Aeroporto di Treviso Canova
Milano - Malpensa Airport : Milano Malpensa Airport
Venezia - Tessera Airport : Venice Marco Polo Airport
Milano - Linate Airport : Aeroporto Milano Linate
Treviso (San Angelo) Airport : Aeroporto di Treviso Canova
Treviso (San Angelo) Airport : Aeroporto di Treviso Canova
Milano - Malpensa Airport : m
Venezia - Tessera Airport : V
Guernsey Channel Is. Airport :
</code>```

答:
As @JeffC mentioned in his comment, you'd probably be better off using the Google Maps API to accomplish whatever it is you're trying to do.

A couple things from your script:

I find implicit waits to be mostly worthless. It is worth the time, in my opinion, to learn about explicit waits, how they work, and when they are useful. Because Google tends use highly dynamic websites which AJAX in a lot of their information, things like Maps tend to work best if you use explicit waits.

Your script was throwing the NoSuchElementException because Google had no suggestions for that term, so your search term, suggest-bold never matched anything. Typically when I see a NSEE that is a red flag that I need to re-evaluate how I'm searching

I think, but I am not positive, that the Milano - Malpensa Airport : m output is a result of the selenium collecting the text from the element before the element has fully loaded.

I personally avoid hard sleeps (time.sleep(5)) at all costs, as they can easily cause your scripts to break if you experience any network lag. This is another area where explicit waits shine, as they can try and try and try to find an element until it is actually loaded, and then move on.

That said, here is how I would do it:

```<code>from explicit import waiter, ID
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.common.exceptions import StaleElementReferenceException

NO_SUGGESTION = 'Add a missing place to Google Maps.'

original_names = [
    'Treviso (San Angelo) Airport',
    'Milano - Malpensa Airport',
    'Venezia - Tessera Airport',
    'Milano - Linate Airport',
    'Treviso (San Angelo) Airport',
    'Treviso (San Angelo) Airport',
    'Milano - Malpensa Airport',
    'Venezia - Tessera Airport',
    'Guernsey Channel Is. Airport',
    'Jersey Channel Is. Airport',
    'Treviso (San Angelo) Airport'
]

def get_name_suggestion(driver, name):
    # Find the search box, clear it, write the name
    waiter.find_write(driver, 'searchboxinput', name, by=ID, clear_first=True)

    class SuggestionLoads(object):
        def __init__(self):
            self._last_seen = None

        def __call__(self, driver):
            """ Custom expected condition.
                Returns either the first suggested name, or '<No Suggestion>'
                Raises a TimeoutException in the event the page source is different
            """
            suggestion_icon = 'div.suggest-icon-container'
            suggest_css = 'div.suggest-left-cell > span.suggest-query'
            try:

                # Only want suggestions that have the location icon next to them, and not the
                # magnifying glass. Return False if we don't find any so as to retry
                icons = driver.find_elements_by_css_selector(suggestion_icon)
                if len(icons) < 1:
                    return False

                elems = driver.find_elements_by_css_selector(suggest_css)

                if len(elems) == 0:
                    # No suggestions have loaded yet, return False so the Wait can retry
                    return False

                suggest_text = elems[0].text
                if len(suggest_text) == 1:
                    # Sometimes we catch text mid-update. Return False to retry
                    # and hopefully get the whole suggestion
                    return False
                elif suggest_text == NO_SUGGESTION:
                    # Google has no suggestion for us, return NO_SUGGESTION, which the Wait will
                    # evaluate as True and exit
                    return '<No Suggestion>'
                else:
                    # We found a valid suggestion. We need to make sure nothing else is going to
                    # get AJAXed in, so compare it to or _last_seen property. If they match,
                    # everything has stabilized and return the string, which will be evaluated as
                    # True and cause the Wait to exit
                    # If you don't do this, you wind up with jung suggestions like "Traffic"
                    if suggest_text == self._last_seen:
                        return suggest_text
                    else:
                        self._last_seen = suggest_text
                        return False

            except StaleElementReferenceException:
                # Because the DOM is constantly updating, there is a pretty decent chance that a
                # SERE will get thrown. Catch it if it does and return False so the Wait
                # can try again
                return False

    return Wait(driver, 30).until(SuggestionLoads())

def main():
    driver = webdriver.Chrome()
    try:
        driver.get("http://maps.google.com")
        driver.maximize_window()
        for orig_name in original_names:
            suggested_name = get_name_suggestion(driver, orig_name)
            print "{0}: {1}".format(orig_name, suggested_name)
    finally:  # This is useful to make sure the browsers get closed, even if an exception is thrown
        driver.quit()

if __name__ == "__main__":
    main()
</code>```

Which returns:

```<code> (.venv27) ➜  tmp python google_maps.py
 Treviso (San Angelo) Airport: Aeroporto di Treviso Canova
 Milano - Malpensa Airport: Milano Malpensa Airport
 Venezia - Tessera Airport: Venice Marco Polo Airport
 Milano - Linate Airport: Aeroporto Milano Linate
 Treviso (San Angelo) Airport: Aeroporto di Treviso Canova
 Treviso (San Angelo) Airport: Aeroporto di Treviso Canova
 Milano - Malpensa Airport: Milano Malpensa Airport
 Venezia - Tessera Airport: Venice Marco Polo Airport
 Guernsey Channel Is. Airport: <No Suggestion>
 Jersey Channel Is. Airport: <No Suggestion>
 Treviso (San Angelo) Airport: Aeroporto di Treviso Canova
</code>```

Full discloser: explicit is a library I maintain and is available from PyPI: pip install explicit. It's designed to make using explicit waits easier, but you could replace it with a garden variety Wait

ContentLicense: CC BY-SA 3.0

Body:
I want to get the travel time between some airports in Europe with google maps. The thing is that some spellings of the names are not accurate, so, I want to first check for wrong names and get google's version of the names. From this question, I am able to use selenium to do that, but my code has some issues, 1) the output is not always complete, (last two result are only one alphabet) 2) it throws an exception at the end of the list (see below). Please help me fix the code. Automating this is the only way as the list of airports is very long.

Input:

wronglySpelled = ['Treviso (San Angelo) Airport', 'Milano - Malpensa
       Airport', 'Venezia - Tessera Airport', 'Milano - Linate Airport',
       'Treviso (San Angelo) Airport', 'Treviso (San Angelo) Airport',
      'Milano - Malpensa Airport', 'Venezia - Tessera Airport', 'Guernsey
       Channel Is. Airport', 'Jersey Channel Is. Airport','Treviso (San
                     Angelo) Airport']

Code:

def setup():
    driver = webdriver.Chrome()
    driver.get("http://maps.google.com")
    driver.maximize_window() # For maximizing window
    driver.implicitly_wait(20) # gives an implicit wait for 20 seconds
    return driver

def correct_name(driver, name_to_check):
    searchBox = driver.find_element_by_name('q')
    searchBox.send_keys(name_to_check)
    correct_name = driver.find_element_by_class_name('suggest-bold')
    return correct_name.text.encode('utf-8')

driver = setup()
for item in wronglySpelled:
    print item,':', correct_name(driver, item)
    time.sleep(5)
    driver.find_element_by_id('searchboxinput').clear()
driver.quit()

Error message:

Traceback (most recent call last):
  File "C:/...", line 60, in <module>
    print item,':', correct_name(driver, item)
  File "C:/...", line 41, in correct_name
    correct_name = driver.find_element_by_class_name('suggest-bold')
  File "C:\...", line 415, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\...", line 756, in find_element
    'value': value})['value']
  File "C:\...", line 238, in execute
    self.error_handler.check_response(response)
  File "C:\...", line 193, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"suggest-bold"}
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 10.0.14393 x86_64)

output:

## Formatted as Input name : Google maps version
Treviso (San Angelo) Airport : Aeroporto di Treviso Canova
Milano - Malpensa Airport : Milano Malpensa Airport
Venezia - Tessera Airport : Venice Marco Polo Airport
Milano - Linate Airport : Aeroporto Milano Linate
Treviso (San Angelo) Airport : Aeroporto di Treviso Canova
Treviso (San Angelo) Airport : Aeroporto di Treviso Canova
Milano - Malpensa Airport : m
Venezia - Tessera Airport : V
Guernsey Channel Is. Airport :

Body:
As @JeffC mentioned in his comment, you'd probably be better off using the Google Maps API to accomplish whatever it is you're trying to do.

A couple things from your script:

I find implicit waits to be mostly worthless. It is worth the time, in my opinion, to learn about explicit waits, how they work, and when they are useful. Because Google tends use highly dynamic websites which AJAX in a lot of their information, things like Maps tend to work best if you use explicit waits.

Your script was throwing the NoSuchElementException because Google had no suggestions for that term, so your search term, suggest-bold never matched anything. Typically when I see a NSEE that is a red flag that I need to re-evaluate how I'm searching

I think, but I am not positive, that the Milano - Malpensa Airport : m output is a result of the selenium collecting the text from the element before the element has fully loaded.

I personally avoid hard sleeps (time.sleep(5)) at all costs, as they can easily cause your scripts to break if you experience any network lag. This is another area where explicit waits shine, as they can try and try and try to find an element until it is actually loaded, and then move on.

That said, here is how I would do it:

from explicit import waiter, ID
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.common.exceptions import StaleElementReferenceException

NO_SUGGESTION = 'Add a missing place to Google Maps.'

original_names = [
    'Treviso (San Angelo) Airport',
    'Milano - Malpensa Airport',
    'Venezia - Tessera Airport',
    'Milano - Linate Airport',
    'Treviso (San Angelo) Airport',
    'Treviso (San Angelo) Airport',
    'Milano - Malpensa Airport',
    'Venezia - Tessera Airport',
    'Guernsey Channel Is. Airport',
    'Jersey Channel Is. Airport',
    'Treviso (San Angelo) Airport'
]

def get_name_suggestion(driver, name):
    # Find the search box, clear it, write the name
    waiter.find_write(driver, 'searchboxinput', name, by=ID, clear_first=True)

    class SuggestionLoads(object):
        def __init__(self):
            self._last_seen = None

        def __call__(self, driver):
            """ Custom expected condition.
                Returns either the first suggested name, or '<No Suggestion>'
                Raises a TimeoutException in the event the page source is different
            """
            suggestion_icon = 'div.suggest-icon-container'
            suggest_css = 'div.suggest-left-cell > span.suggest-query'
            try:

                # Only want suggestions that have the location icon next to them, and not the
                # magnifying glass. Return False if we don't find any so as to retry
                icons = driver.find_elements_by_css_selector(suggestion_icon)
                if len(icons) < 1:
                    return False

                elems = driver.find_elements_by_css_selector(suggest_css)

                if len(elems) == 0:
                    # No suggestions have loaded yet, return False so the Wait can retry
                    return False

                suggest_text = elems[0].text
                if len(suggest_text) == 1:
                    # Sometimes we catch text mid-update. Return False to retry
                    # and hopefully get the whole suggestion
                    return False
                elif suggest_text == NO_SUGGESTION:
                    # Google has no suggestion for us, return NO_SUGGESTION, which the Wait will
                    # evaluate as True and exit
                    return '<No Suggestion>'
                else:
                    # We found a valid suggestion. We need to make sure nothing else is going to
                    # get AJAXed in, so compare it to or _last_seen property. If they match,
                    # everything has stabilized and return the string, which will be evaluated as
                    # True and cause the Wait to exit
                    # If you don't do this, you wind up with jung suggestions like "Traffic"
                    if suggest_text == self._last_seen:
                        return suggest_text
                    else:
                        self._last_seen = suggest_text
                        return False

            except StaleElementReferenceException:
                # Because the DOM is constantly updating, there is a pretty decent chance that a
                # SERE will get thrown. Catch it if it does and return False so the Wait
                # can try again
                return False

    return Wait(driver, 30).until(SuggestionLoads())

def main():
    driver = webdriver.Chrome()
    try:
        driver.get("http://maps.google.com")
        driver.maximize_window()
        for orig_name in original_names:
            suggested_name = get_name_suggestion(driver, orig_name)
            print "{0}: {1}".format(orig_name, suggested_name)
    finally:  # This is useful to make sure the browsers get closed, even if an exception is thrown
        driver.quit()

if __name__ == "__main__":
    main()

Which returns:

 (.venv27) ➜  tmp python google_maps.py
 Treviso (San Angelo) Airport: Aeroporto di Treviso Canova
 Milano - Malpensa Airport: Milano Malpensa Airport
 Venezia - Tessera Airport: Venice Marco Polo Airport
 Milano - Linate Airport: Aeroporto Milano Linate
 Treviso (San Angelo) Airport: Aeroporto di Treviso Canova
 Treviso (San Angelo) Airport: Aeroporto di Treviso Canova
 Milano - Malpensa Airport: Milano Malpensa Airport
 Venezia - Tessera Airport: Venice Marco Polo Airport
 Guernsey Channel Is. Airport: <No Suggestion>
 Jersey Channel Is. Airport: <No Suggestion>
 Treviso (San Angelo) Airport: Aeroporto di Treviso Canova

Full discloser: explicit is a library I maintain and is available from PyPI: pip install explicit. It's designed to make using explicit waits easier, but you could replace it with a garden variety Wait


问:
Is there a more concise way to combine many comparisons in Ruby?
I currently have this if statement:

```<code>if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0
</code>```

Is there a more concise way to do this?

答:
You can use Time#to_a to convert your time to an array (sec, min, hour, day, month, year, wday, yday, isdst, zone):

```<code>Time.now.to_a  # => [20, 57, 16, 30, 11, 2010, 2, 334, false, "CET"]
</code>```

then slice off just the part you want to match against:

```<code>Time.now.to_a[0,4]  # => [20, 57, 16, 30]
</code>```

Your particular check can then be made as concise as this:

```<code>if Time.now.to_a[0,4] == [0,0,0,1]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I currently have this if statement:

if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0

Is there a more concise way to do this?

Body:
You can use Time#to_a to convert your time to an array (sec, min, hour, day, month, year, wday, yday, isdst, zone):

Time.now.to_a  # => [20, 57, 16, 30, 11, 2010, 2, 334, false, "CET"]

then slice off just the part you want to match against:

Time.now.to_a[0,4]  # => [20, 57, 16, 30]

Your particular check can then be made as concise as this:

if Time.now.to_a[0,4] == [0,0,0,1]


问:
How can I efficiently run XSLT transformations for a large number of files in parallel?
I have to regularly transform large amount of XML files (min. 100K) within 1 folder each time (basically, from the unzipped input dataset), and I'd like to learn how to do that in the most efficient way as possible. My technological stack consists of XLTs and the Saxon XSLT Java libraries, called from Bash scripts. And it runs on an Ubuntu server with 8 cores and a Raid of SSD with 64Gb of Ram. Keep in mind I handle nicely XSLT but I'm still in the process of learning Bash and how to distribute the loads properly for such tasks (and Java is almost just a word at that point too).

I previously created a post regarding this issue, as my approach seemed very inefficient and was actually in need of help to properly run (See this SOF post). A lot of comments later, it makes sense to present the issue differently, therefore this post. I was proposed several solutions, one currently working much better than mine, but it could still be more elegant and efficient.

Now, I'm running this :

```<code>printf -- '-s:%s\0' input/*.xml | xargs -P 600 -n 1 -0 java -jar saxon9he.jar -xsl:some-xslt-sheet.xsl
</code>```

I set 600 processes based on some previous tests. Going higher would just throw memory errors from Java. But it is only using between 30 to 40Gb of Ram now (all 8 cores are at 100% though).

To put it in a nutshell, here is all the advices/approaches I have so far :

Splitting the whole XML files among subfolders (e.g. containing each
5K files), and use this as a way to run in parallel transformation scripts for each subfolder

Use specifically the Saxon-EE library    (allowing
multithreaded    execution) with the collection() function to parse the XML files

Set the Java environment with a lower number of tasks, or decrease
the memory per process

Specifying Saxon regarding if the XSLT sheets are compatible with
libxml/libxslt (isn't it only for XSLT1.0?)

Use a specialized shell such as xmlsh

I can handle the solution #2, and it should directly enable to control the loop and load JVM only once ; the #1 seems more clumsy and I still need to improve in Bash (load distribution & perf, tackling relative/absolute paths) ; the #3, #4 and #5 are totally new to me and I may need more explanations to see how to tackle that.

Any input would be greatly appreciated.

答:
"the most efficient way possible" is asking a lot, and is not usually a reasonable objective. I doubt, for example, that you would be prepared to put in 6 months' effort to improve the efficiency of the process by 3%. What you are looking for is a way of doing it that meets performance targets and can be implemented with minimum effort. And "efficiency" itself begs questions about what your metrics are.

I'm pretty confident that the design I have suggested, with a single transformation processing all the files using collection() and xsl:result-document (which are both parallelized in Saxon-EE) is capable of giving good results, and is likely to be a lot less work than the only other approach I would consider, which is to write a Java application to hold the "control logic": although if you're good at writing multi-threaded Java applications then you can probably get that to go a bit faster by taking advantage of your knowledge of the workload.

Body:
I have to regularly transform large amount of XML files (min. 100K) within 1 folder each time (basically, from the unzipped input dataset), and I'd like to learn how to do that in the most efficient way as possible. My technological stack consists of XLTs and the Saxon XSLT Java libraries, called from Bash scripts. And it runs on an Ubuntu server with 8 cores and a Raid of SSD with 64Gb of Ram. Keep in mind I handle nicely XSLT but I'm still in the process of learning Bash and how to distribute the loads properly for such tasks (and Java is almost just a word at that point too).

I previously created a post regarding this issue, as my approach seemed very inefficient and was actually in need of help to properly run (See this SOF post). A lot of comments later, it makes sense to present the issue differently, therefore this post. I was proposed several solutions, one currently working much better than mine, but it could still be more elegant and efficient.

Now, I'm running this :

printf -- '-s:%s\0' input/*.xml | xargs -P 600 -n 1 -0 java -jar saxon9he.jar -xsl:some-xslt-sheet.xsl

I set 600 processes based on some previous tests. Going higher would just throw memory errors from Java. But it is only using between 30 to 40Gb of Ram now (all 8 cores are at 100% though).

To put it in a nutshell, here is all the advices/approaches I have so far :

Splitting the whole XML files among subfolders (e.g. containing each
5K files), and use this as a way to run in parallel transformation scripts for each subfolder

Use specifically the Saxon-EE library    (allowing
multithreaded    execution) with the collection() function to parse the XML files

Set the Java environment with a lower number of tasks, or decrease
the memory per process

Specifying Saxon regarding if the XSLT sheets are compatible with
libxml/libxslt (isn't it only for XSLT1.0?)

Use a specialized shell such as xmlsh

I can handle the solution #2, and it should directly enable to control the loop and load JVM only once ; the #1 seems more clumsy and I still need to improve in Bash (load distribution & perf, tackling relative/absolute paths) ; the #3, #4 and #5 are totally new to me and I may need more explanations to see how to tackle that.

Any input would be greatly appreciated.


问:
How do I protect an API?
I am currently working on a single-page web application. The web app will make calls to a REST-like API for authentication and data storage. We are currently in the middle of securing the application, and have worked out a strategy securing the site so only registered users can gain access. But one thing we also want to do is securing the API from others to write their own applications, or access it in any other way than through our web application. The problem from my view is that the API will be open for everybody and not only for my web application.

Anyone who knows how to do this, or who can point me in the right direction. Because right now, don't have a clue.

答:
Simplest way will be to use  OAuth 2.0 ( supports both  authentication and authorization) which you need.

Also ensure you secure the data on wire using TLS (HTTPS) and any of the options below

```<code>1. HTTP Digest
2. OAuthn 2.0
3. Certificates ( Shared secret)
</code>```

Stick to HTTPS+Oauth2 for now.

Title: How do I protect an API?

Body:
Simplest way will be to use  OAuth 2.0 ( supports both  authentication and authorization) which you need.

Also ensure you secure the data on wire using TLS (HTTPS) and any of the options below

1. HTTP Digest
2. OAuthn 2.0
3. Certificates ( Shared secret)

Stick to HTTPS+Oauth2 for now.


问:
Wireshark decrypt and save wireless packets from command line
I have a question that I can't seem to find a complete answer for. This may not be something that is possible, but I am hoping someone will have a solution.

At my work, we process wireless sniffs in wireshark. We have a shell script to merge and filter the files into the forms that we want, but we still have to manually generate a PSK and add it in wireshark preferences to decrypt each file for analysis. I would like to add a line to decrypt the main file before filtering and save it in a decrypted format.

Here is the problem:
I know I can use the -o flag when running tshark to add the psk to the computers decryption keys, but the processing is done on one computer then the files are distributed among many employees for analysis, so I need the files themselves decrypted.

I know I can use aircrack-ng to decrypt pcap files, but we use pcapng files and aircrack does not recognize those.

Is there any solution? It would even help if I could somehow generate a psk from ssid and password and save that as a text file, but there does not even seem to be a clean way to do that.

We use Ubuntu 16.04 as our OS. Wireshark version 2.0.2.

答:
You could possibly just append the psk information directly to the 80211_keys file located in your Wireshark personal configuration folder then distribute that file along with the capture file.  If you don't want (or if users don't want) to overwrite the existing 80211_keys file, they could set the WIRESHARK_DATA_DIR environment variable so the distributed file is used instead when they run Wireshark for this type of analysis.

Refer to the Wireshark man page for more information on the various Wireshark environment variables.

If aircrack-ng only supports pcap files, then I suppose another possible solution might be to simply convert the pcapng files to pcap using something like editcap, or just change the default capture file format to pcap if you're not making use of any of pcapng's features anyway, e.g., you're not capturing on multiple interfaces simultaneously, you don't use packet comments, etc.


问:
CSS: Make the width of auto div to expand till positioned element
I'm facing a problem.

How to make a div expand till the end of the positioned element.

.apple {
  background: #ccc;
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="apple">
  A for aplle
  <br>B for Ball
</div></code>```

Here, the div doesn't accept the width of the position changed element. How to make it work. Thanks.

答:
Try to add display: table; to the parent and display: table-row; to the child.

.apple {
  background: #ccc;
  width: auto;
  display: table;
}
.apple a {
  display: table-row;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="apple">
  A for aplle
  <br>B for Ball
</div></code>```

Body:
I'm facing a problem.

How to make a div expand till the end of the positioned element.

.apple {
  background: #ccc;
  width: auto;
}

  A for aplle

B for Ball

Here, the div doesn't accept the width of the position changed element. How to make it work. Thanks.

Body:
Try to add display: table; to the parent and display: table-row; to the child.

.apple {
  background: #ccc;
  width: auto;
  display: table;
}
.apple a {
  display: table-row;
}

<div class="apple">
  A for aplle
  <br><a style="position:relative; top:20px;">B for Ball</a>
</div>


问:
What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?
I was trying to change my default/main/startup (whatever you call it) activity by editing the androidmanifest.xml file. All i did was change the android:name property. however, this completely broke the entire app. when I try to install it fails and reads.

Installation error: INSTALL_PARSE_FAILED_NO_CERTIFICATES

When I tried to change it back to its previous state, it was still giving me the same error... What have I done?

答:
Its because previously generated build and current is having conflict in signature version between v1(jar signature) and v2(full APK Signature),

To fix tick proper signature version under Generate Signed APK dialog

ContentLicense: CC BY-SA 4.0


问:
In flask,how to query data use a selectfield as condition and display with pagination
I want to query data,use the selectfield as a condition,then show the result in a html and use paginage.
my question is when i display my data，the first can display normally but when i click the next_page，the selectfield is none and the data can not display.
what should I do to keep the selectfield when I click the next_page？</p>

答:
Your view should accept an integer to allow for the passing of the current datum. Below is an example:

```<code>@app.route('/view/<int:page>',methods=['GET'])
def view(page=1):
  if request.method == 'POST':
    select = int(request.form.get('select'))
    print(select)
  per_page = 2
  try:
    users = User.query.order_by(User.email.asc()).paginate(select,
                                                           per_page=per_page,
                                                           error_out=False)
  except NameError:
    users = User.query.order_by(User.email.asc()).paginate(page,
                                                           per_page=per_page,
                                                           error_out=False)
  return render_template('view.html',users=users)
</code>```

The view would look something like this:

```<code><html>
  <head>Welcome</head>
  <body>
<form method="POST" action="{{ url_for('view', page=users.prev_num + 1) }}">
  <div>
    <div>
       <span>Please select</span>
        <select name="select">
          {% for user in users.items %}
            <option value="{{ user.id }}">{{ user.username }}</option>
          {% endfor %}
        </select>
    </div>
    <button type="submit">Go</button>
  </div>
</form>
{% if users.has_prev %}<a href="{{ url_for('view', page=users.prev_num) }}"><< Newer users</a>{% else %}<< Newer posts{% endif %} |
{% if users.has_next %}<a href="{{ url_for('view', page=users.next_num) }}">Older users >></a>{% else %}Older posts >>{% endif %}

  </body>
</html>
</code>```

Body:
Your view should accept an integer to allow for the passing of the current datum. Below is an example:

@app.route('/view/<int:page>',methods=['GET'])
def view(page=1):
  if request.method == 'POST':
    select = int(request.form.get('select'))
    print(select)
  per_page = 2
  try:
    users = User.query.order_by(User.email.asc()).paginate(select,
                                                           per_page=per_page,
                                                           error_out=False)
  except NameError:
    users = User.query.order_by(User.email.asc()).paginate(page,
                                                           per_page=per_page,
                                                           error_out=False)
  return render_template('view.html',users=users)

The view would look something like this:

<html>
  <head>Welcome</head>
  <body>
<form method="POST" action="{{ url_for('view', page=users.prev_num + 1) }}">
  <div>
    <div>
       <span>Please select</span>
        <select name="select">
          {% for user in users.items %}
            <option value="{{ user.id }}">{{ user.username }}</option>
          {% endfor %}
        </select>
    </div>
    <button type="submit">Go</button>
  </div>
</form>
{% if users.has_prev %}<a href="{{ url_for('view', page=users.prev_num) }}">&lt;&lt; Newer users</a>{% else %}&lt;&lt; Newer posts{% endif %} |
{% if users.has_next %}<a href="{{ url_for('view', page=users.next_num) }}">Older users &gt;&gt;</a>{% else %}Older posts &gt;&gt;{% endif %}

  </body>
</html>


问:
Split a file name and only take one part for use
I have a $value such as 22214-HAV.jpg or 22214 HAV.jpg (notice no dash)

I want to run a quick function to pull only the number from filename.

答:
```<code>preg_match('/^\d+/' ,'22214-HAV.jpg', $matches);
var_dump($matches[0]);
</code>```

Observations:

This will only match numbers starting exactly from the beginning. Any position can be allowed by removing ^.

This will match any sequence of digits and not actual numbers. Numbers can be restricted by using ([1-9]\d*|0) in place of \d+.

If no match is found $matches[0] will be null and not an empty string.

Further reading:

http://www.php.net/manual/en/function.preg-match.php

http://www.regular-expressions.info/reference.html

Body:
preg_match('/^\d+/' ,'22214-HAV.jpg', $matches);
var_dump($matches[0]);

Observations:

This will only match numbers starting exactly from the beginning. Any position can be allowed by removing ^.

This will match any sequence of digits and not actual numbers. Numbers can be restricted by using ([1-9]\d*|0) in place of \d+.

If no match is found $matches[0] will be null and not an empty string.

Further reading:

http://www.php.net/manual/en/function.preg-match.php

http://www.regular-expressions.info/reference.html


问:
Subsetting list-elements based on conditional
I have the following dataframe

```<code>mydf<- data.frame(c(1,1,3,4,5,6),
                  c(1,1,3,10,20,30),
                  c(1,10,20,20,15,10))
colnames(mydf)<-c( "ID1","ID2", "ID3")
</code>```

Let's count how many instances of mydf$ID1 and mydf$ID2 we have where they appear twice

```<code>tmp<-plyr::ddply(mydf,c("ID1","ID2"),nrow)
tmp<-tmp[tmp$V1==2,]
</code>```

This has the following output (there's two identical instances)

```<code>  ID1 ID2 V1
1   1   1  2
</code>```

Now I want to extract the remaining fields, i.e. ID3, of these two instances:

```<code>asd<-mydf[ (mydf$ID1 %in% tmp$ID1) & (mydf$ID1 %in% tmp$ID2), ]
</code>```

This gives me the following

```<code>  ID1 ID2 ID3
1   1   1   1
2   1   1  10
</code>```

This is exactly as desired and what I wanted, so all good.

However, my real data set doesn't only contain 3 vectors like mydf, but 300. And each vector is not just 6 elements long, but +50.000

When I run the above method on my data, then I get instances of entries that occur not only 2 times, but also 1, 3, 4 and so on. So that means something is wrong.

Is it because the above method cannot be scaled up to large data? Or is it because the method I outlined above is inherently wrong?

Unfortunately, due to the large size of my data, I cannot post it here.

UPDATE: Having a list with 3 vectors was just chosen as an example. In reality my data has many vectors, but I still want to group them based on duplicates of two vectors. An example:

```<code>library(dplyr)

mydf<- data.frame(c(1,  1, 3, 4, 5, 6,0),
                  c(22,22, 3,10,20,30,0),
                  c(2, 10,20,20,15,10,0),
                  c(3, 10,20,20,15,10,0),
                  c(4, 10,20,20,15,10,15),
                  c(5, 99,98,98,97,99,97))
colnames(mydf)<-c( "ID1","ID2", "ID3", "ID4", "ID5", "ID6")

(mydf %>% group_by(ID5, ID6) %>% filter(n()==2))
</code>```

As desired, this produces

```<code>    ID1   ID2   ID3   ID4   ID5   ID6
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1    22    10    10    10    99
2     3     3    20    20    20    98
3     4    10    20    20    20    98
4     5    20    15    15    15    97
5     6    30    10    10    10    99
6     0     0     0     0    15    97
</code>```

答:
We can do this in easier way with dplyr

```<code>library(dplyr)
mydf %>%
    group_by(ID1, ID2) %>%
    filter(n()==2)
</code>```

If there are more than 2 columns as grouping variables, we can use the group_by_

```<code>mydf %>%
    group_by_(.dots = names(mydf)[1:2]) %>%
    filter(n()==2)
</code>```

Body:
I have the following dataframe

mydf<- data.frame(c(1,1,3,4,5,6),
                  c(1,1,3,10,20,30),
                  c(1,10,20,20,15,10))
colnames(mydf)<-c( "ID1","ID2", "ID3")

Let's count how many instances of mydf$ID1 and mydf$ID2 we have where they appear twice

tmp<-plyr::ddply(mydf,c("ID1","ID2"),nrow)
tmp<-tmp[tmp$V1==2,]

This has the following output (there's two identical instances)

  ID1 ID2 V1
1   1   1  2

Now I want to extract the remaining fields, i.e. ID3, of these two instances:

asd<-mydf[ (mydf$ID1 %in% tmp$ID1) & (mydf$ID1 %in% tmp$ID2), ]

This gives me the following

  ID1 ID2 ID3
1   1   1   1
2   1   1  10

This is exactly as desired and what I wanted, so all good.

However, my real data set doesn't only contain 3 vectors like mydf, but 300. And each vector is not just 6 elements long, but +50.000

When I run the above method on my data, then I get instances of entries that occur not only 2 times, but also 1, 3, 4 and so on. So that means something is wrong.

Is it because the above method cannot be scaled up to large data? Or is it because the method I outlined above is inherently wrong?

Unfortunately, due to the large size of my data, I cannot post it here.

UPDATE: Having a list with 3 vectors was just chosen as an example. In reality my data has many vectors, but I still want to group them based on duplicates of two vectors. An example:

library(dplyr)

mydf<- data.frame(c(1,  1, 3, 4, 5, 6,0),
                  c(22,22, 3,10,20,30,0),
                  c(2, 10,20,20,15,10,0),
                  c(3, 10,20,20,15,10,0),
                  c(4, 10,20,20,15,10,15),
                  c(5, 99,98,98,97,99,97))
colnames(mydf)<-c( "ID1","ID2", "ID3", "ID4", "ID5", "ID6")

(mydf %>% group_by(ID5, ID6) %>% filter(n()==2))

As desired, this produces

    ID1   ID2   ID3   ID4   ID5   ID6
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1    22    10    10    10    99
2     3     3    20    20    20    98
3     4    10    20    20    20    98
4     5    20    15    15    15    97
5     6    30    10    10    10    99
6     0     0     0     0    15    97

Body:
We can do this in easier way with dplyr

library(dplyr)
mydf %>%
    group_by(ID1, ID2) %>%
    filter(n()==2)

If there are more than 2 columns as grouping variables, we can use the group_by_

mydf %>%
    group_by_(.dots = names(mydf)[1:2]) %>%
    filter(n()==2)


答:
Its doing what it should.  You are positioning the element 20px below where it naturally falls in the DOM, so it is placed outside the gray div.  I understand your situation may be more complicated.  Can you do something like add padding-bottom:20px?

.apple {
  background: #ccc;
  width: auto;
  padding-bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="apple">
  A for aplle
  <br>B for Ball
</div></code>```

Title: CSS: Make the width of auto div to expand till positioned element

Body:
Its doing what it should.  You are positioning the element 20px below where it naturally falls in the DOM, so it is placed outside the gray div.  I understand your situation may be more complicated.  Can you do something like add padding-bottom:20px?

.apple {
  background: #ccc;
  width: auto;
  padding-bottom: 20px;
}

<div class="apple">
  A for aplle
  <br><a style="position:relative; top:20px;">B for Ball</a>
</div>


问:
PHP + PThreads + Redis/Predis = zend_mm_heap corrupted?
I have been struggling with a mysterious error for a few days now. I am using PHP 7.1.0RC3 (I recompiled myself with ZTS/pthreads enabled). Recently, I have been working on a refactor that replaces MySQL with Redis to optimize non-disk-worthy data I/O in my application.

I have a script that creates a Thread (A) for each Cryptocurrency Market. Thread (A) creates another Thread (B) for each Trading Strategy. B Threads are always synced before A Threads.

I keep getting this error: zend_mm_heap corrupted. It occurs at a different point in execution each time I run the script.

I have tried all suggested fixes, 100s of Google pages. Garbage Collection, PHP configuration/compilation, all has been reviewed to great detail. I haven't found anything related to "zend_mm_heap corrupted", PThreads and Redis/Predis, while other "fixes" have had no effect...

All data is read from and saved to Redis (via Predis). The error message only appears when using Predis within Thread A or Thread B (changes each time). It occurs more frequently when two Predis method invocations happen in rapid succession (set then get, for example).

If I use shell_exec() to run Redis commands directly via the CLI, I don't see this error. But, it's significantly slower so may simply be missing this edge case?

If anyone can give any input/thoughts towards any of the following, I would greatly appreciate it:

How can I find where this is coming from in my application?

Would a dedicated Redis Server potentially fix this?

Should I submit a bug report to https://github.com/krakjoe/pthreads?

Should I submit a bug report to https://github.com/nrk/predis?

Does anyone know why zend_mm_heap corrupted might occur, in general, in a thread "safe" environment (aka: ZTS)? Or how I should guard against it???

Should I try compiling even more different versions of PHP 7+? https://github.com/php/php-src

I am out of options, please have mercy. I can share code samples but pasting them here would not be very useful.

Edit
I recompiled PHP with ./configure --enable-maintainer-zts --enable-pthreads --with-pthreads-sanitize --with-mysqli --enable-embedded-mysqli and I saw a new error I haven't seen before:

```<code>==2716== ERROR: AddressSanitizer: heap-use-after-free on address 0x600800001c15 at pc 0xe25a87 bp 0x7f7a049feae0 sp 0x7f7a049fead0
READ of size 1 at 0x600800001c15 thread T1632
    #0 0xe25a86 (/usr/local/bin/php+0xe25a86)
    #1 0xe953c8 (/usr/local/bin/php+0xe953c8)
    #2 0xe4935b (/usr/local/bin/php+0xe4935b)
    #3 0xcbede3 (/usr/local/bin/php+0xcbede3)
    #4 0x98cfa9 (/usr/local/bin/php+0x98cfa9)
    #5 0x99dc3c (/usr/local/bin/php+0x99dc3c)
    #6 0x7f7b57e74a97 (/usr/lib64/libasan.so.0.0.0+0x19a97)
    #7 0x7f7b5694edc4 (/usr/lib64/libpthread-2.17.so+0x7dc4)
    #8 0x7f7b5667d73c (/usr/lib64/libc-2.17.so+0xf773c)
0x600800001c15 is located 5 bytes inside of 48-byte region [0x600800001c10,0x600800001c40)
freed by thread T1623 here:
    #0 0x7f7b57e71009 (/usr/lib64/libasan.so.0.0.0+0x16009)
    #1 0xe259fb (/usr/local/bin/php+0xe259fb)
    #2 0xe953c8 (/usr/local/bin/php+0xe953c8)
    #3 0xe4935b (/usr/local/bin/php+0xe4935b)
    #4 0xcbede3 (/usr/local/bin/php+0xcbede3)
    #5 0x98cfa9 (/usr/local/bin/php+0x98cfa9)
    #6 0x99dc3c (/usr/local/bin/php+0x99dc3c)
    #7 0x7f7b57e74a97 (/usr/lib64/libasan.so.0.0.0+0x19a97)
previously allocated by thread T0 here:
    #0 0x7f7b57e71129 (/usr/lib64/libasan.so.0.0.0+0x16129)
    #1 0xdb0118 (/usr/local/bin/php+0xdb0118)
    #2 0xe64f6c (/usr/local/bin/php+0xe64f6c)
    #3 0xe68c5d (/usr/local/bin/php+0xe68c5d)
    #4 0xcc4dcc (/usr/local/bin/php+0xcc4dcc)
    #5 0xcc5972 (/usr/local/bin/php+0xcc5972)
    #6 0x111f82c (/usr/local/bin/php+0x111f82c)
    #7 0x44c781 (/usr/local/bin/php+0x44c781)
    #8 0x7f7b565a7b34 (/usr/lib64/libc-2.17.so+0x21b34)
Thread T1632 created by T0 here:
    #0 0x7f7b57e65c3a (/usr/lib64/libasan.so.0.0.0+0xac3a)
    #1 0x99e4cb (/usr/local/bin/php+0x99e4cb)
    #2 0x975d2a (/usr/local/bin/php+0x975d2a)
    #3 0x11105c1 (/usr/local/bin/php+0x11105c1)
    #4 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #5 0x97b385 (/usr/local/bin/php+0x97b385)
    #6 0x11126bc (/usr/local/bin/php+0x11126bc)
    #7 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #8 0x97b385 (/usr/local/bin/php+0x97b385)
    #9 0x11126bc (/usr/local/bin/php+0x11126bc)
    #10 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #11 0x97b385 (/usr/local/bin/php+0x97b385)
    #12 0x11126bc (/usr/local/bin/php+0x11126bc)
    #13 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #14 0x97b385 (/usr/local/bin/php+0x97b385)
    #15 0x11126bc (/usr/local/bin/php+0x11126bc)
    #16 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #17 0x97b385 (/usr/local/bin/php+0x97b385)
    #18 0x1110b28 (/usr/local/bin/php+0x1110b28)
    #19 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #20 0x97b385 (/usr/local/bin/php+0x97b385)
    #21 0x11126bc (/usr/local/bin/php+0x11126bc)
    #22 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #23 0x97b385 (/usr/local/bin/php+0x97b385)
    #24 0x111c28a (/usr/local/bin/php+0x111c28a)
    #25 0xe52281 (/usr/local/bin/php+0xe52281)
    #26 0xcc766f (/usr/local/bin/php+0xcc766f)
    #27 0x1121d36 (/usr/local/bin/php+0x1121d36)
    #28 0x44d202 (/usr/local/bin/php+0x44d202)
    #29 0x7f7b565a7b34 (/usr/lib64/libc-2.17.so+0x21b34)
Thread T1623 created by T0 here:
    #0 0x7f7b57e65c3a (/usr/lib64/libasan.so.0.0.0+0xac3a)
    #1 0x99e4cb (/usr/local/bin/php+0x99e4cb)
    #2 0x975d2a (/usr/local/bin/php+0x975d2a)
    #3 0x11105c1 (/usr/local/bin/php+0x11105c1)
    #4 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #5 0x97b385 (/usr/local/bin/php+0x97b385)
    #6 0x11126bc (/usr/local/bin/php+0x11126bc)
    #7 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #8 0x97b385 (/usr/local/bin/php+0x97b385)
    #9 0x11126bc (/usr/local/bin/php+0x11126bc)
    #10 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #11 0x97b385 (/usr/local/bin/php+0x97b385)
    #12 0x11126bc (/usr/local/bin/php+0x11126bc)
    #13 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #14 0x97b385 (/usr/local/bin/php+0x97b385)
    #15 0x11126bc (/usr/local/bin/php+0x11126bc)
    #16 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #17 0x97b385 (/usr/local/bin/php+0x97b385)
    #18 0x1110b28 (/usr/local/bin/php+0x1110b28)
    #19 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #20 0x97b385 (/usr/local/bin/php+0x97b385)
    #21 0x11126bc (/usr/local/bin/php+0x11126bc)
    #22 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #23 0x97b385 (/usr/local/bin/php+0x97b385)
    #24 0x111c28a (/usr/local/bin/php+0x111c28a)
    #25 0xe52281 (/usr/local/bin/php+0xe52281)
    #26 0xcc766f (/usr/local/bin/php+0xcc766f)
    #27 0x1121d36 (/usr/local/bin/php+0x1121d36)
    #28 0x44d202 (/usr/local/bin/php+0x44d202)
    #29 0x7f7b565a7b34 (/usr/lib64/libc-2.17.so+0x21b34)
Shadow bytes around the buggy address:
  0x0c017fff8330: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 fa
  0x0c017fff8340: fa fa 00 00 00 00 00 fa fa fa 00 00 00 00 00 fa
  0x0c017fff8350: fa fa 00 00 00 00 00 fa fa fa 00 00 00 00 00 00
  0x0c017fff8360: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 fa
  0x0c017fff8370: fa fa 00 00 00 00 00 fa fa fa 00 00 00 00 00 00
=>0x0c017fff8380: fa fa[fd]fd fd fd fd fd fa fa 00 00 00 00 00 00
  0x0c017fff8390: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 00
  0x0c017fff83a0: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 00
  0x0c017fff83b0: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 00
  0x0c017fff83c0: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 fa
  0x0c017fff83d0: fa fa 00 00 00 00 00 fa fa fa 00 00 00 00 00 fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:     fa
  Heap righ redzone:     fb
  Freed Heap region:     fd
  Stack left redzone:    f1
  Stack mid redzone:     f2
  Stack right redzone:   f3
  Stack partial redzone: f4
  Stack after return:    f5
  Stack use after scope: f8
  Global redzone:        f9
  Global init order:     f6
  Poisoned by user:      f7
  ASan internal:         fe
==2716== ABORTING
</code>```

答:
I found the source of the memory corruption, and the "fix" was very simple. I have found that the only "non-fatal" way of using a phpiredis $client in pthreads is to explicitly connect/execute commands/disconnect in the current local scope.

Summed up, the following results in Memory Corruption when under high load:

Attempting to pass a phpiredis $client to another object by reference in Threaded context

Attempting to pass a phpiredis $client to another object by value in Threaded context

Attempting to instantiate/use a phpiredis $client in anywhere except local scope in Threaded context (ex: in another class, _Redis, when we are currently in Investor::save)

Attempting to statically reuse a phpiredis connection in general in Threaded context

Memory corruption does not occur when passing a MySQLi $client to another object in the same way/context, though.

I hope this saves someone else the week of despair I have witnessed. This is how one must use phpiredis within pthreads:

```<code>// Instantiate a local raw phpiredis $client and execute get/set commands using $client directly
// @Result: This WORKS :D
$client = phpiredis_connect('127.0.0.1', 6379);
$key = "table_name-_-$this->id";
foreach($args as $prop=>$val)
    if(isset($prop) && isset($val))
        phpiredis_command($client, "hset $key $prop $val");
$obj = phpiredis_command($client, "hgetall $key");
echo json_encode($obj);
phpiredis_disconnect($client);
</code>```

Body:
I have been struggling with a mysterious error for a few days now. I am using PHP 7.1.0RC3 (I recompiled myself with ZTS/pthreads enabled). Recently, I have been working on a refactor that replaces MySQL with Redis to optimize non-disk-worthy data I/O in my application.

I have a script that creates a Thread (A) for each Cryptocurrency Market. Thread (A) creates another Thread (B) for each Trading Strategy. B Threads are always synced before A Threads.

I keep getting this error: zend_mm_heap corrupted. It occurs at a different point in execution each time I run the script.

I have tried all suggested fixes, 100s of Google pages. Garbage Collection, PHP configuration/compilation, all has been reviewed to great detail. I haven't found anything related to "zend_mm_heap corrupted", PThreads and Redis/Predis, while other "fixes" have had no effect...

All data is read from and saved to Redis (via Predis). The error message only appears when using Predis within Thread A or Thread B (changes each time). It occurs more frequently when two Predis method invocations happen in rapid succession (set then get, for example).

If I use shell_exec() to run Redis commands directly via the CLI, I don't see this error. But, it's significantly slower so may simply be missing this edge case?

If anyone can give any input/thoughts towards any of the following, I would greatly appreciate it:

How can I find where this is coming from in my application?

Would a dedicated Redis Server potentially fix this?

Should I submit a bug report to https://github.com/krakjoe/pthreads?

Should I submit a bug report to https://github.com/nrk/predis?

Does anyone know why zend_mm_heap corrupted might occur, in general, in a thread "safe" environment (aka: ZTS)? Or how I should guard against it???

Should I try compiling even more different versions of PHP 7+? https://github.com/php/php-src

I am out of options, please have mercy. I can share code samples but pasting them here would not be very useful.

Edit
I recompiled PHP with ./configure --enable-maintainer-zts --enable-pthreads --with-pthreads-sanitize --with-mysqli --enable-embedded-mysqli and I saw a new error I haven't seen before:

==2716== ERROR: AddressSanitizer: heap-use-after-free on address 0x600800001c15 at pc 0xe25a87 bp 0x7f7a049feae0 sp 0x7f7a049fead0
READ of size 1 at 0x600800001c15 thread T1632
    #0 0xe25a86 (/usr/local/bin/php+0xe25a86)
    #1 0xe953c8 (/usr/local/bin/php+0xe953c8)
    #2 0xe4935b (/usr/local/bin/php+0xe4935b)
    #3 0xcbede3 (/usr/local/bin/php+0xcbede3)
    #4 0x98cfa9 (/usr/local/bin/php+0x98cfa9)
    #5 0x99dc3c (/usr/local/bin/php+0x99dc3c)
    #6 0x7f7b57e74a97 (/usr/lib64/libasan.so.0.0.0+0x19a97)
    #7 0x7f7b5694edc4 (/usr/lib64/libpthread-2.17.so+0x7dc4)
    #8 0x7f7b5667d73c (/usr/lib64/libc-2.17.so+0xf773c)
0x600800001c15 is located 5 bytes inside of 48-byte region [0x600800001c10,0x600800001c40)
freed by thread T1623 here:
    #0 0x7f7b57e71009 (/usr/lib64/libasan.so.0.0.0+0x16009)
    #1 0xe259fb (/usr/local/bin/php+0xe259fb)
    #2 0xe953c8 (/usr/local/bin/php+0xe953c8)
    #3 0xe4935b (/usr/local/bin/php+0xe4935b)
    #4 0xcbede3 (/usr/local/bin/php+0xcbede3)
    #5 0x98cfa9 (/usr/local/bin/php+0x98cfa9)
    #6 0x99dc3c (/usr/local/bin/php+0x99dc3c)
    #7 0x7f7b57e74a97 (/usr/lib64/libasan.so.0.0.0+0x19a97)
previously allocated by thread T0 here:
    #0 0x7f7b57e71129 (/usr/lib64/libasan.so.0.0.0+0x16129)
    #1 0xdb0118 (/usr/local/bin/php+0xdb0118)
    #2 0xe64f6c (/usr/local/bin/php+0xe64f6c)
    #3 0xe68c5d (/usr/local/bin/php+0xe68c5d)
    #4 0xcc4dcc (/usr/local/bin/php+0xcc4dcc)
    #5 0xcc5972 (/usr/local/bin/php+0xcc5972)
    #6 0x111f82c (/usr/local/bin/php+0x111f82c)
    #7 0x44c781 (/usr/local/bin/php+0x44c781)
    #8 0x7f7b565a7b34 (/usr/lib64/libc-2.17.so+0x21b34)
Thread T1632 created by T0 here:
    #0 0x7f7b57e65c3a (/usr/lib64/libasan.so.0.0.0+0xac3a)
    #1 0x99e4cb (/usr/local/bin/php+0x99e4cb)
    #2 0x975d2a (/usr/local/bin/php+0x975d2a)
    #3 0x11105c1 (/usr/local/bin/php+0x11105c1)
    #4 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #5 0x97b385 (/usr/local/bin/php+0x97b385)
    #6 0x11126bc (/usr/local/bin/php+0x11126bc)
    #7 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #8 0x97b385 (/usr/local/bin/php+0x97b385)
    #9 0x11126bc (/usr/local/bin/php+0x11126bc)
    #10 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #11 0x97b385 (/usr/local/bin/php+0x97b385)
    #12 0x11126bc (/usr/local/bin/php+0x11126bc)
    #13 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #14 0x97b385 (/usr/local/bin/php+0x97b385)
    #15 0x11126bc (/usr/local/bin/php+0x11126bc)
    #16 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #17 0x97b385 (/usr/local/bin/php+0x97b385)
    #18 0x1110b28 (/usr/local/bin/php+0x1110b28)
    #19 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #20 0x97b385 (/usr/local/bin/php+0x97b385)
    #21 0x11126bc (/usr/local/bin/php+0x11126bc)
    #22 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #23 0x97b385 (/usr/local/bin/php+0x97b385)
    #24 0x111c28a (/usr/local/bin/php+0x111c28a)
    #25 0xe52281 (/usr/local/bin/php+0xe52281)
    #26 0xcc766f (/usr/local/bin/php+0xcc766f)
    #27 0x1121d36 (/usr/local/bin/php+0x1121d36)
    #28 0x44d202 (/usr/local/bin/php+0x44d202)
    #29 0x7f7b565a7b34 (/usr/lib64/libc-2.17.so+0x21b34)
Thread T1623 created by T0 here:
    #0 0x7f7b57e65c3a (/usr/lib64/libasan.so.0.0.0+0xac3a)
    #1 0x99e4cb (/usr/local/bin/php+0x99e4cb)
    #2 0x975d2a (/usr/local/bin/php+0x975d2a)
    #3 0x11105c1 (/usr/local/bin/php+0x11105c1)
    #4 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #5 0x97b385 (/usr/local/bin/php+0x97b385)
    #6 0x11126bc (/usr/local/bin/php+0x11126bc)
    #7 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #8 0x97b385 (/usr/local/bin/php+0x97b385)
    #9 0x11126bc (/usr/local/bin/php+0x11126bc)
    #10 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #11 0x97b385 (/usr/local/bin/php+0x97b385)
    #12 0x11126bc (/usr/local/bin/php+0x11126bc)
    #13 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #14 0x97b385 (/usr/local/bin/php+0x97b385)
    #15 0x11126bc (/usr/local/bin/php+0x11126bc)
    #16 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #17 0x97b385 (/usr/local/bin/php+0x97b385)
    #18 0x1110b28 (/usr/local/bin/php+0x1110b28)
    #19 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #20 0x97b385 (/usr/local/bin/php+0x97b385)
    #21 0x11126bc (/usr/local/bin/php+0x11126bc)
    #22 0xf71de2 (/usr/local/bin/php+0xf71de2)
    #23 0x97b385 (/usr/local/bin/php+0x97b385)
    #24 0x111c28a (/usr/local/bin/php+0x111c28a)
    #25 0xe52281 (/usr/local/bin/php+0xe52281)
    #26 0xcc766f (/usr/local/bin/php+0xcc766f)
    #27 0x1121d36 (/usr/local/bin/php+0x1121d36)
    #28 0x44d202 (/usr/local/bin/php+0x44d202)
    #29 0x7f7b565a7b34 (/usr/lib64/libc-2.17.so+0x21b34)
Shadow bytes around the buggy address:
  0x0c017fff8330: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 fa
  0x0c017fff8340: fa fa 00 00 00 00 00 fa fa fa 00 00 00 00 00 fa
  0x0c017fff8350: fa fa 00 00 00 00 00 fa fa fa 00 00 00 00 00 00
  0x0c017fff8360: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 fa
  0x0c017fff8370: fa fa 00 00 00 00 00 fa fa fa 00 00 00 00 00 00
=>0x0c017fff8380: fa fa[fd]fd fd fd fd fd fa fa 00 00 00 00 00 00
  0x0c017fff8390: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 00
  0x0c017fff83a0: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 00
  0x0c017fff83b0: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 00
  0x0c017fff83c0: fa fa 00 00 00 00 00 00 fa fa 00 00 00 00 00 fa
  0x0c017fff83d0: fa fa 00 00 00 00 00 fa fa fa 00 00 00 00 00 fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:     fa
  Heap righ redzone:     fb
  Freed Heap region:     fd
  Stack left redzone:    f1
  Stack mid redzone:     f2
  Stack right redzone:   f3
  Stack partial redzone: f4
  Stack after return:    f5
  Stack use after scope: f8
  Global redzone:        f9
  Global init order:     f6
  Poisoned by user:      f7
  ASan internal:         fe
==2716== ABORTING

Body:
I found the source of the memory corruption, and the "fix" was very simple. I have found that the only "non-fatal" way of using a phpiredis $client in pthreads is to explicitly connect/execute commands/disconnect in the current local scope.

Summed up, the following results in Memory Corruption when under high load:

Attempting to pass a phpiredis $client to another object by reference in Threaded context

Attempting to pass a phpiredis $client to another object by value in Threaded context

Attempting to instantiate/use a phpiredis $client in anywhere except local scope in Threaded context (ex: in another class, _Redis, when we are currently in Investor::save)

Attempting to statically reuse a phpiredis connection in general in Threaded context

Memory corruption does not occur when passing a MySQLi $client to another object in the same way/context, though.

I hope this saves someone else the week of despair I have witnessed. This is how one must use phpiredis within pthreads:

// Instantiate a local raw phpiredis $client and execute get/set commands using $client directly
// @Result: This WORKS :D
$client = phpiredis_connect('127.0.0.1', 6379);
$key = "table_name-_-$this->id";
foreach($args as $prop=>$val)
    if(isset($prop) && isset($val))
        phpiredis_command($client, "hset $key $prop $val");
$obj = phpiredis_command($client, "hgetall $key");
echo json_encode($obj);
phpiredis_disconnect($client);


问:
generate random 64 bit integer
I need your help and please  give me some advice. From programming pearls I know that to generate random 30 bit integer we should write it like this:

```<code>RAND_MAX*rand()+rand()
</code>```

But what could I do for generating not 30, but 64 bit random integer instead? I think that is very inefficient method if I multiply two 30 bit integers and then multiply again 4 bit integer, so what kind of method should I use?
I am using now  popcount_1 different method for 64 bit one and I would like to test it on random integers(I am also measuring the time which each one takes to accomplish the task)

答:
'Returns a pseudo-random integral value between 0 and RAND_MAX (0 and RAND_MAX included).' - http://en.cppreference.com/w/cpp/numeric/random/rand

So you should use RAND_MAX + 1 (it's like generating a number digit by digit and then converting it to base 10) instead of RAND_MAX.
This way you can generate numbers with one, two, three etc. digits in base RAND_MAX + 1(possibly with leading zeroes) and convert them to base 10 and get arbitrarily large numbers.

Everything that you obtain larger than your desired MAX_VALUE can be discarded and you still get 1/(MAX_VALUE + 1) probability for obtaining each number.

Note, that this method might take a while, especially if your desired MAX_VALUE is a lot less than the maximum value that can be obtained before discarding the numbers that are not desired, as the expected number of steps to obtain a random number in [0, MAX_VALUE] with this algorithm is: (MAX_OBTAINABLE_VALUE + 1)/(MAX_VALUE + 1)

Title: generate random 64 bit integer

Body:
I need your help and please  give me some advice. From programming pearls I know that to generate random 30 bit integer we should write it like this:

RAND_MAX*rand()+rand()

But what could I do for generating not 30, but 64 bit random integer instead? I think that is very inefficient method if I multiply two 30 bit integers and then multiply again 4 bit integer, so what kind of method should I use?
I am using now  popcount_1 different method for 64 bit one and I would like to test it on random integers(I am also measuring the time which each one takes to accomplish the task)


问:
Disable ui-sref based on a condition
Can you tell me a way to disable the submit button, which changes to a new state by:

```<code><a ui-sref="state">Submit</a>
</code>```

The button should be enabled only when the form is valid.

ng-disabled with ui-sref does not work:

```<code><form name="tickets">
  <button ng-disabled="!canSave()"><a ui-sref="view">Submit</a></button>
</form>
</code>```

canSave function inside app.js being:

```<code>$scope.canSave = function(){
  return $scope.tickets.$dirty && $scope.tickets.$valid;
};
</code>```

答:
I had problems with the isolate scope and using other directives inside anchors, so here's my take, replacing the iscolate scope with regular attributes.

```<code>angular.module('app').directive('uiSrefIf', ['$compile', function($compile) {
  var directive = {
    restrict: 'A',
    link: linker
  };

  return directive;

  function linker(scope, elem, attrs) {
    elem.removeAttr('ui-sref-if');
    $compile(elem)(scope);

    scope.$watch(attrs.condition, function(bool) {
      if (bool) {
        elem.attr('ui-sref', attrs.value);
      } else {
        elem.removeAttr('ui-sref');
        elem.removeAttr('href');
      }

      $compile(elem)(scope);
    });
  }
}]);
</code>```

Html Looks like this.

```<code><a ui-sref-if condition="enableLink()" value="init.main">
    <cover class="card-image" card="card"></cover>
</a>
</code>```

Title: Disable ui-sref based on a condition

Body:
Can you tell me a way to disable the submit button, which changes to a new state by:

Submit

The button should be enabled only when the form is valid.

ng-disabled with ui-sref does not work:

<form name="tickets">
  <button ng-disabled="!canSave()">Submit</button>
</form>

canSave function inside app.js being:

$scope.canSave = function(){
  return $scope.tickets.$dirty && $scope.tickets.$valid;
};

Body:
I had problems with the isolate scope and using other directives inside anchors, so here's my take, replacing the iscolate scope with regular attributes.

angular.module('app').directive('uiSrefIf', ['$compile', function($compile) {
  var directive = {
    restrict: 'A',
    link: linker
  };

  return directive;

  function linker(scope, elem, attrs) {
    elem.removeAttr('ui-sref-if');
    $compile(elem)(scope);

    scope.$watch(attrs.condition, function(bool) {
      if (bool) {
        elem.attr('ui-sref', attrs.value);
      } else {
        elem.removeAttr('ui-sref');
        elem.removeAttr('href');
      }

      $compile(elem)(scope);
    });
  }
}]);

Html Looks like this.

<a ui-sref-if condition="enableLink()" value="init.main">
    <cover class="card-image" card="card"></cover>
</a>


答:
Is this really your code? You always want to return AA if $c is a multiple of 100?

The fastest way to get the same result with the least amount of code would be....

```<code>$res=array('A','B','C',....);
if (($c % 100) && ($c>0) && ($c<2100)) {
   echo $res[(integer)($c/100)];
} else {
   echo 'AA';
}
</code>```

But I would use a solution like that from sterofrog.

Title: Faster way to check if integer is in any of ranges?

Body:
I wonder if there is another way to shorten this ? Here is the example im looking for to do same thing just shorter.

if($c <= 100){
    echo 'A';
}elseif($c <= 200 && $c > 100){
    echo 'B';
}elseif($c <= 300 && $c > 200){
    echo 'C';
}elseif($c <= 400 && $c > 300){
    echo 'D';
}elseif($c <= 500 && $c > 400){
    echo 'E';
}elseif($c <= 600 && $c > 500){
    echo 'F';
}elseif($c <= 700 && $c > 600){
    echo 'Z';
}elseif($c <= 800 && $c > 700){
    echo 'H';
}elseif($c <= 900 && $c > 800){
    echo 'I';
}elseif($c < 1000 && $c > 900){
    echo 'K';
}elseif($c <= 1100 && $c > 1000){
    echo 'L';
}elseif($c <= 1200 && $c > 1100){
    echo 'M';
}elseif($c < 1300 && $c > 1200){
    echo 'N';
}elseif($c <= 1400 && $c > 1300){
    echo 'O';
}elseif($c <= 1500 && $c > 1400){
    echo 'P';
}elseif($c <= 1600 && $c > 1500){
    echo 'Q';
}elseif($c <= 1700 && $c > 1600){
    echo 'R';
}elseif($c <= 1800 && $c > 1700){
    echo 'S';
}elseif($c <= 1900 && $c > 1800){
    echo 'T';
}elseif($c <= 2000 && $c > 1900){
    echo 'V';
}elseif($c <= 2100 && $c > 2000){
    echo 'X';
}else{
    echo 'AA';
}

Body:
Is this really your code? You always want to return AA if $c is a multiple of 100?

The fastest way to get the same result with the least amount of code would be....

$res=array('A','B','C',....);
if (($c % 100) && ($c>0) && ($c<2100)) {
   echo $res[(integer)($c/100)];
} else {
   echo 'AA';
}

But I would use a solution like that from sterofrog.


问:
Batch - Trouble with Redirect within For Loop
I'm having difficulty getting a command to run in a For Loop.  From a cmd prompt this works fine:

```<code>"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" -r info | find "E:"
</code>```

But, the following seems to have a syntax problem

```<code>for /f "tokens=1-7 delims=," %%A in ('"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info ^| find "E:"') do (set _DRVID=%%A)
</code>```

Yielding an error - C:\Program' is not recognized as an internal or external command, operable program or batch file.

Just for reference, I found a way to get my desired result with the following:
I can get the following code to work in Batch as well generating the desired output:

```<code>for /f "tokens=1-7 delims=," %%A in ('"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info') do (IF %%G=="E:" set _DRVID=%%A)
</code>```

What am I doing wrong?

答:
when piping, both sides of a pipe are executed in an own instance of cmd. This makes quoting and escaping look non-intuitive. Try:

```<code>for /f "tokens=1-7 delims=," %%A in ('""C:\Program Files (x86^)\MakeMKV\makemkvcon64.exe" -r info | find "E:""') do (set _DRVID=%%A)
</code>```

Body:
I'm having difficulty getting a command to run in a For Loop.  From a cmd prompt this works fine:

"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" -r info | find "E:"

But, the following seems to have a syntax problem

for /f "tokens=1-7 delims=," %%A in ('"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info ^| find "E:"') do (set _DRVID=%%A)

Yielding an error - C:\Program' is not recognized as an internal or external command, operable program or batch file.

Just for reference, I found a way to get my desired result with the following:
I can get the following code to work in Batch as well generating the desired output:

for /f "tokens=1-7 delims=," %%A in ('"C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" ^-r info') do (IF %%G=="E:" set _DRVID=%%A)

What am I doing wrong?

Body:
when piping, both sides of a pipe are executed in an own instance of cmd. This makes quoting and escaping look non-intuitive. Try:

for /f "tokens=1-7 delims=," %%A in ('""C:\Program Files (x86^)\MakeMKV\makemkvcon64.exe" -r info | find "E:""') do (set _DRVID=%%A)


问:
Update Access database using Visual Studio 2015 - VB.net
I am trying to do a simple update to an Access 2016 database.  I am using Visual Studio/VB.net.  I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore).  I have tried two different ways to do this...using the update table adapter, for example:

```<code>            MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
            AvailabilityTextBox.Text, EmailTextBox.Text)
</code>```

Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):

```<code>saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
              VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
            '" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
</code>```

But this method gives me the error of Syntax Error in UPDATE statement.  Again I have used this method elsewhere with no problems.  Below I will post all the code for this form.

```<code>Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient

Public Class editMediators

Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")

' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
    Dim cmd As New OleDbCommand
    connect() ' open our connection
    Try
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        conn.Close()
        MsgBox("Data Has Been Saved !", vbInformation)
    Catch ex As Exception
        MsgBox("Error when saving data: " & ex.Message)
    End Try
End Sub

Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
    DateTimePicker1.Value = Today()

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
    NewData = True
    alertMsgBox2()

End Sub

Private Sub alertMsgBox2()

    Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
           "No: Exits the mediator update window without saving," & vbNewLine &
           "Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
        Case MsgBoxResult.Yes

            MediatorsListBindingSource.EndEdit()
            updateMediator()

         'intentionally commented out
         'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text,    MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
            'AvailabilityTextBox.Text, EmailTextBox.Text)

           ' Me.Close()

        Case MsgBoxResult.No
            MediatorsListBindingSource.CancelEdit()
            Me.Close()
    End Select

End Sub

Private Sub updateMediator()
    Dim saveInfo As String
    If NewData Then
        Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
        If Message = vbNo Then
            Exit Sub
        End If
        Try
            'Update mediator information
            saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
              VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
            '" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
        Catch ex As Exception
        End Try

    Else
        Exit Sub

    End If
    runAccessSQL(saveInfo)

End Sub
</code>```

There is obviously something I am missing, though I am not sure it is missing from the code.  I checked my database fields and set them to string/text fields just to see if I could get it working.  At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements.  I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since.  I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.

I am rather lost on what else to try as this seems like it should work one way or another.   Any ideas what to look at and/or try??  Hopefully I can be pointed in the right direction.

Thanks  :)

答:
Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.

Try this instead:
(Edited)

```<code>saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
    MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
    mediatorID = '" & MediatorIDTextBox.Text & "'"
</code>```

Also be sure to handle the date correctly.  I usually force formatting in yyyy/mmm/dd format.

Body:
I am trying to do a simple update to an Access 2016 database.  I am using Visual Studio/VB.net.  I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore).  I have tried two different ways to do this...using the update table adapter, for example:

            MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
            AvailabilityTextBox.Text, EmailTextBox.Text)

Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):

saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
              VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
            '" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "

But this method gives me the error of Syntax Error in UPDATE statement.  Again I have used this method elsewhere with no problems.  Below I will post all the code for this form.

Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient

Public Class editMediators

Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")

' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
    Dim cmd As New OleDbCommand
    connect() ' open our connection
    Try
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        conn.Close()
        MsgBox("Data Has Been Saved !", vbInformation)
    Catch ex As Exception
        MsgBox("Error when saving data: " & ex.Message)
    End Try
End Sub

Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
    DateTimePicker1.Value = Today()

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
    NewData = True
    alertMsgBox2()

End Sub

Private Sub alertMsgBox2()

    Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
           "No: Exits the mediator update window without saving," & vbNewLine &
           "Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
        Case MsgBoxResult.Yes

            MediatorsListBindingSource.EndEdit()
            updateMediator()

         'intentionally commented out
         'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text,    MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
            'AvailabilityTextBox.Text, EmailTextBox.Text)

           ' Me.Close()

        Case MsgBoxResult.No
            MediatorsListBindingSource.CancelEdit()
            Me.Close()
    End Select

End Sub

Private Sub updateMediator()
    Dim saveInfo As String
    If NewData Then
        Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
        If Message = vbNo Then
            Exit Sub
        End If
        Try
            'Update mediator information
            saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
              VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
            '" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
        Catch ex As Exception
        End Try

    Else
        Exit Sub

    End If
    runAccessSQL(saveInfo)

End Sub

There is obviously something I am missing, though I am not sure it is missing from the code.  I checked my database fields and set them to string/text fields just to see if I could get it working.  At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements.  I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since.  I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.

I am rather lost on what else to try as this seems like it should work one way or another.   Any ideas what to look at and/or try??  Hopefully I can be pointed in the right direction.

Thanks  :)

Body:
Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.

Try this instead:
(Edited)

saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
    MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
    mediatorID = '" & MediatorIDTextBox.Text & "'"

Also be sure to handle the date correctly.  I usually force formatting in yyyy/mmm/dd format.