问:
How to determine appropriate strftime format from a date string?
The dateutil parser does a great job of correctly guessing the date and time from a wide variety of sources.

We are processing files in which each file uses only one date/time format, but the format varies between files. Profiling shows a lot of time being used by dateutil.parser.parse.  Since it only needs to be determined once per file, implementing something that isn't guessing the format each time could speed things up.

I don't actually know the formats in advance and I'll still need to infer the format.  Something like:

```<code>from MysteryPackage import date_string_to_format_string
import datetime

# e.g. mystring = '1 Jan 2016'
myformat = None

...

# somewhere in a loop reading from a file or connection:
if myformat is None:
    myformat = date_string_to_format_string(mystring)

# do the usual checks to see if that worked, then:
mydatetime = datetime.strptime(mystring, myformat)
</code>```

Is there such a function?

答:
This is a tricky one. My approach makes use of regular expressions and the (?(DEFINE)...) syntax which is only supported by the newer regex module.

Essentially, DEFINE let us define subroutines prior to matching them, so first of all we define all needed bricks for our date guessing function:

```<code>    (?(DEFINE)
        (?P<year_def>[12]\d{3})
        (?P<year_short_def>\d{2})
        (?P<month_def>January|February|March|April|May|June|
        July|August|September|October|November|December)
        (?P<month_short_def>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
        (?P<day_def>(?:0[1-9]|[1-9]|[12][0-9]|3[01]))
        (?P<weekday_def>(?:Mon|Tue|Wednes|Thurs|Fri|Satur|Sun)day)
        (?P<weekday_short_def>Mon|Tue|Wed|Thu|Fri|Sat|Sun)
        (?P<hms_def>\d{2}:\d{2}:\d{2})
        (?P<hm_def>\d{2}:\d{2})
            (?P<ms_def>\d{5,6})
            (?P<delim_def>([-/., ]+|(?<=\d|^)T))
        )
        # actually match them
        (?P<hms>^(?&hms_def)$)|(?P<year>^(?&year_def)$)|(?P<month>^(?&month_def)$)|(?P<month_short>^(?&month_short_def)$)|(?P<day>^(?&day_def)$)|
        (?P<weekday>^(?&weekday_def)$)|(?P<weekday_short>^(?&weekday_short_def)$)|(?P<hm>^(?&hm_def)$)|(?P<delim>^(?&delim_def)$)|(?P<ms>^(?&ms_def)$)
        """, re.VERBOSE)
</code>```

After this, we need to think of possible delimiters:

```<code># delim
delim = re.compile(r'([-/., ]+|(?<=\d)T)')
</code>```

Format mapping:

```<code># formats
formats = {'ms': '%f', 'year': '%Y', 'month': '%B', 'month_dec': '%m', 'day': '%d', 'weekday': '%A', 'hms': '%H:%M:%S', 'weekday_short': '%a', 'month_short': '%b', 'hm': '%H:%M', 'delim': ''}
</code>```

The function GuessFormat() splits the parts with the help of the delimiters, tries to match them and outputs the corresponding code for strftime():

```<code>def GuessFormat(datestring):

    # define the bricks
    bricks = re.compile(r"""
            (?(DEFINE)
                (?P<year_def>[12]\d{3})
                (?P<year_short_def>\d{2})
                (?P<month_def>January|February|March|April|May|June|
                July|August|September|October|November|December)
                (?P<month_short_def>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
                (?P<day_def>(?:0[1-9]|[1-9]|[12][0-9]|3[01]))
                (?P<weekday_def>(?:Mon|Tue|Wednes|Thurs|Fri|Satur|Sun)day)
                (?P<weekday_short_def>Mon|Tue|Wed|Thu|Fri|Sat|Sun)
                (?P<hms_def>T?\d{2}:\d{2}:\d{2})
                (?P<hm_def>T?\d{2}:\d{2})
                (?P<ms_def>\d{5,6})
                (?P<delim_def>([-/., ]+|(?<=\d|^)T))
            )
            # actually match them
            (?P<hms>^(?&hms_def)$)|(?P<year>^(?&year_def)$)|(?P<month>^(?&month_def)$)|(?P<month_short>^(?&month_short_def)$)|(?P<day>^(?&day_def)$)|
            (?P<weekday>^(?&weekday_def)$)|(?P<weekday_short>^(?&weekday_short_def)$)|(?P<hm>^(?&hm_def)$)|(?P<delim>^(?&delim_def)$)|(?P<ms>^(?&ms_def)$)
            """, re.VERBOSE)

    # delim
    delim = re.compile(r'([-/., ]+|(?<=\d)T)')

    # formats
    formats = {'ms': '%f', 'year': '%Y', 'month': '%B', 'month_dec': '%m', 'day': '%d', 'weekday': '%A', 'hms': '%H:%M:%S', 'weekday_short': '%a', 'month_short': '%b', 'hm': '%H:%M', 'delim': ''}

    parts = delim.split(datestring)
    out = []
    for index, part in enumerate(parts):
        try:
            brick = dict(filter(lambda x: x[1] is not None, bricks.match(part).groupdict().items()))
            key = next(iter(brick))

            # ambiguities
            if key == 'day' and index == 2:
                key = 'month_dec'

            item = part if key == 'delim' else formats[key]
            out.append(item)
        except AttributeError:
            out.append(part)

    return "".join(out)
</code>```

A test in the end:

```<code>import regex as re

datestrings = [datetime.now().isoformat(), '2006-11-02', 'Thursday, 10 August 2006 08:42:51', 'August 9, 1995', 'Aug 9, 1995', 'Thu, 01 Jan 1970 00:00:00', '21/11/06 16:30',
'06 Jun 2017 20:33:10']

# test
for dt in datestrings:
    print("Date: {}, Format: {}".format(dt, GuessFormat(dt)))
</code>```

This yields:

```<code>Date: 2017-06-07T22:02:05.001811, Format: %Y-%m-%dT%H:%M:%S.%f
Date: 2006-11-02, Format: %Y-%m-%d
Date: Thursday, 10 August 2006 08:42:51, Format: %A, %m %B %Y %H:%M:%S
Date: August 9, 1995, Format: %B %m, %Y
Date: Aug 9, 1995, Format: %b %m, %Y
Date: Thu, 01 Jan 1970 00:00:00, Format: %a, %m %b %Y %H:%M:%S
Date: 21/11/06 16:30, Format: %d/%m/%d %H:%M
Date: 06 Jun 2017 20:33:10, Format: %d %b %Y %H:%M:%S
</code>```

Body:
The dateutil parser does a great job of correctly guessing the date and time from a wide variety of sources.

We are processing files in which each file uses only one date/time format, but the format varies between files. Profiling shows a lot of time being used by dateutil.parser.parse.  Since it only needs to be determined once per file, implementing something that isn't guessing the format each time could speed things up.

I don't actually know the formats in advance and I'll still need to infer the format.  Something like:

from MysteryPackage import date_string_to_format_string
import datetime

# e.g. mystring = '1 Jan 2016'
myformat = None

...

# somewhere in a loop reading from a file or connection:
if myformat is None:
    myformat = date_string_to_format_string(mystring)

# do the usual checks to see if that worked, then:
mydatetime = datetime.strptime(mystring, myformat)

Is there such a function?

Body:
This is a tricky one. My approach makes use of regular expressions and the (?(DEFINE)...) syntax which is only supported by the newer regex module.

Essentially, DEFINE let us define subroutines prior to matching them, so first of all we define all needed bricks for our date guessing function:

    (?(DEFINE)
        (?P<year_def>[12]\d{3})
        (?P<year_short_def>\d{2})
        (?P<month_def>January|February|March|April|May|June|
        July|August|September|October|November|December)
        (?P<month_short_def>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
        (?P<day_def>(?:0[1-9]|[1-9]|[12][0-9]|3[01]))
        (?P<weekday_def>(?:Mon|Tue|Wednes|Thurs|Fri|Satur|Sun)day)
        (?P<weekday_short_def>Mon|Tue|Wed|Thu|Fri|Sat|Sun)
        (?P<hms_def>\d{2}:\d{2}:\d{2})
        (?P<hm_def>\d{2}:\d{2})
            (?P<ms_def>\d{5,6})
            (?P<delim_def>([-/., ]+|(?<=\d|^)T))
        )
        # actually match them
        (?P<hms>^(?&hms_def)$)|(?P<year>^(?&year_def)$)|(?P<month>^(?&month_def)$)|(?P<month_short>^(?&month_short_def)$)|(?P<day>^(?&day_def)$)|
        (?P<weekday>^(?&weekday_def)$)|(?P<weekday_short>^(?&weekday_short_def)$)|(?P<hm>^(?&hm_def)$)|(?P<delim>^(?&delim_def)$)|(?P<ms>^(?&ms_def)$)
        """, re.VERBOSE)

After this, we need to think of possible delimiters:

# delim
delim = re.compile(r'([-/., ]+|(?<=\d)T)')

Format mapping:

# formats
formats = {'ms': '%f', 'year': '%Y', 'month': '%B', 'month_dec': '%m', 'day': '%d', 'weekday': '%A', 'hms': '%H:%M:%S', 'weekday_short': '%a', 'month_short': '%b', 'hm': '%H:%M', 'delim': ''}

The function GuessFormat() splits the parts with the help of the delimiters, tries to match them and outputs the corresponding code for strftime():

def GuessFormat(datestring):

    # define the bricks
    bricks = re.compile(r"""
            (?(DEFINE)
                (?P<year_def>[12]\d{3})
                (?P<year_short_def>\d{2})
                (?P<month_def>January|February|March|April|May|June|
                July|August|September|October|November|December)
                (?P<month_short_def>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
                (?P<day_def>(?:0[1-9]|[1-9]|[12][0-9]|3[01]))
                (?P<weekday_def>(?:Mon|Tue|Wednes|Thurs|Fri|Satur|Sun)day)
                (?P<weekday_short_def>Mon|Tue|Wed|Thu|Fri|Sat|Sun)
                (?P<hms_def>T?\d{2}:\d{2}:\d{2})
                (?P<hm_def>T?\d{2}:\d{2})
                (?P<ms_def>\d{5,6})
                (?P<delim_def>([-/., ]+|(?<=\d|^)T))
            )
            # actually match them
            (?P<hms>^(?&hms_def)$)|(?P<year>^(?&year_def)$)|(?P<month>^(?&month_def)$)|(?P<month_short>^(?&month_short_def)$)|(?P<day>^(?&day_def)$)|
            (?P<weekday>^(?&weekday_def)$)|(?P<weekday_short>^(?&weekday_short_def)$)|(?P<hm>^(?&hm_def)$)|(?P<delim>^(?&delim_def)$)|(?P<ms>^(?&ms_def)$)
            """, re.VERBOSE)

    # delim
    delim = re.compile(r'([-/., ]+|(?<=\d)T)')

    # formats
    formats = {'ms': '%f', 'year': '%Y', 'month': '%B', 'month_dec': '%m', 'day': '%d', 'weekday': '%A', 'hms': '%H:%M:%S', 'weekday_short': '%a', 'month_short': '%b', 'hm': '%H:%M', 'delim': ''}

    parts = delim.split(datestring)
    out = []
    for index, part in enumerate(parts):
        try:
            brick = dict(filter(lambda x: x[1] is not None, bricks.match(part).groupdict().items()))
            key = next(iter(brick))

            # ambiguities
            if key == 'day' and index == 2:
                key = 'month_dec'

            item = part if key == 'delim' else formats[key]
            out.append(item)
        except AttributeError:
            out.append(part)

    return "".join(out)

A test in the end:

import regex as re

datestrings = [datetime.now().isoformat(), '2006-11-02', 'Thursday, 10 August 2006 08:42:51', 'August 9, 1995', 'Aug 9, 1995', 'Thu, 01 Jan 1970 00:00:00', '21/11/06 16:30',
'06 Jun 2017 20:33:10']

# test
for dt in datestrings:
    print("Date: {}, Format: {}".format(dt, GuessFormat(dt)))

This yields:

Date: 2017-06-07T22:02:05.001811, Format: %Y-%m-%dT%H:%M:%S.%f
Date: 2006-11-02, Format: %Y-%m-%d
Date: Thursday, 10 August 2006 08:42:51, Format: %A, %m %B %Y %H:%M:%S
Date: August 9, 1995, Format: %B %m, %Y
Date: Aug 9, 1995, Format: %b %m, %Y
Date: Thu, 01 Jan 1970 00:00:00, Format: %a, %m %b %Y %H:%M:%S
Date: 21/11/06 16:30, Format: %d/%m/%d %H:%M
Date: 06 Jun 2017 20:33:10, Format: %d %b %Y %H:%M:%S


来源: stackexchange

问:
(Selenium WebDriver) Menu click pass but nothing happens on page
I am writing a selenium C# test code for an old "infragistics" (I seriouly don't know too much about this) page. The page doesn't give me that much options when it comes to elements references. Like in the HTML below I want to click on INVENTORY which is a submenu of a menu item but there is no element Id or Name so I used XPath (see code below). It looks like webdriver recognizes that xpath but when the click function executes and complete, nothing happens on the page. It does not open the expected page. Is there something that I am doing wrong here?

 INVENTORY...
```
</div>
</div>
</p>

<p>Code:</p>

```private By FileSubMenu = By.XPath(".//li/a/span[text()=' Inventory...']");

    public HomePage SubMenu()
    {
        int retryCount = 0;
        while (true && retryCount < Constants.RETRY_COUNT)
        {
            try
            {
                Thread.Sleep(3000);
                IWebElement element = _driver.FindElement(FileSubMenu);
                Actions Rmouseover = new Actions(_driver);
                Rmouseover.MoveToElement(element).Click().Perform();
                return this;
            }
            catch (Exception ex) when (ex is WebDriverTimeoutException || ex is TimeoutException)
            {
                retryCount++;
                Thread.Sleep(3000);
            }
        }
        return this;
    }
```

答:
XPath is okay, but I prefer CSS Selector as it tends to yeild less brittle selectors (not so location in the DOM based, but still can be). To get one in Chrome:

Right-click on the element and select 'Inspect'

Right-click on the element in the DOM explorer of DevTools

Select "Copy" > "Copy selector"

So then your code would look something like:

```<code>IWebElement element =  driver.FindElement(By.CssSelector("paste_the_selector_here"));
// Click via Selenium's Click method
element.Click();
// Or, click via JavaScript
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", element);
</code>```

Also, instead of clicking the  you may want to click on the  instead as it has an onclick event listener.

If the selector includes an ID for a parent that is dynamic, then you'll want to remove it. To remove it, find the element with that ID in the DevTool's Element tab. Double-click on the id="..." part and delete the whole thing. Now get the selector for the child element.

This example

```<code><div id="ctl00_NavBarAdmin_WebDataMenu1"> // <- Parent div html
#ctl00_NavBarAdmin_WebDataMenu1 > ul > li:nth-child(2) > ul > li.igdm_MenuItemVertical.igdm_MenuItemVerticalParent.igdm_MenuItemVerticalSelected > a
</code>```

Might become

```<code><div> // <- Parent div HTML
div > ul > li:nth-child(2) > ul > li.igdm_MenuItemVertical.igdm_MenuItemVerticalParent.igdm_MenuItemVerticalSelected > a
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing a selenium C# test code for an old "infragistics" (I seriouly don't know too much about this) page. The page doesn't give me that much options when it comes to elements references. Like in the HTML below I want to click on INVENTORY which is a submenu of a menu item but there is no element Id or Name so I used XPath (see code below). It looks like webdriver recognizes that xpath but when the click function executes and complete, nothing happens on the page. It does not open the expected page. Is there something that I am doing wrong here?

 INVENTORY...

Code:

private By FileSubMenu = By.XPath(".//li/a/span[text()=' Inventory...']");

    public HomePage SubMenu()
    {
        int retryCount = 0;
        while (true && retryCount < Constants.RETRY_COUNT)
        {
            try
            {
                Thread.Sleep(3000);
                IWebElement element = _driver.FindElement(FileSubMenu);
                Actions Rmouseover = new Actions(_driver);
                Rmouseover.MoveToElement(element).Click().Perform();
                return this;
            }
            catch (Exception ex) when (ex is WebDriverTimeoutException || ex is TimeoutException)
            {
                retryCount++;
                Thread.Sleep(3000);
            }
        }
        return this;
    }

Body:
XPath is okay, but I prefer CSS Selector as it tends to yeild less brittle selectors (not so location in the DOM based, but still can be). To get one in Chrome:

Right-click on the element and select 'Inspect'

Right-click on the element in the DOM explorer of DevTools

Select "Copy" > "Copy selector"

So then your code would look something like:

IWebElement element =  driver.FindElement(By.CssSelector("paste_the_selector_here"));
// Click via Selenium's Click method
element.Click();
// Or, click via JavaScript
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", element);

Also, instead of clicking the <span> you may want to click on the <a> instead as it has an onclick event listener.

If the selector includes an ID for a parent that is dynamic, then you'll want to remove it. To remove it, find the element with that ID in the DevTool's Element tab. Double-click on the id="..." part and delete the whole thing. Now get the selector for the child element.

This example

<div id="ctl00_NavBarAdmin_WebDataMenu1"> // <- Parent div html
#ctl00_NavBarAdmin_WebDataMenu1 > ul > li:nth-child(2) > ul > li.igdm_MenuItemVertical.igdm_MenuItemVerticalParent.igdm_MenuItemVerticalSelected > a

Might become

<div> // <- Parent div HTML
div > ul > li:nth-child(2) > ul > li.igdm_MenuItemVertical.igdm_MenuItemVerticalParent.igdm_MenuItemVerticalSelected > a


问:
How do I specify my own NER classifier in StanfordNLP coreference resolution tagging?
I have trained my own NER classifier and now I want to use that in doing the coreference resolution. How do I do this? I tried this:

java -Xmx5g -cp stanford-corenlp-3.7.0.jar:stanford-corenlp-models-3.7.0.jar:* edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators ner,coref -loadClassifier ./classifiers/my_classifier.ser.gz -coref.algorithm neural -file my_file.txt

But it didn't work and error message:

java.io.IOException: Unable to open "edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz" as class path, filename or URL

So it seems that it is still not using my NER classifier.

答:
Suppose I have the custom model stored at:

```<code>/Users/stanfordnlphelp/custom_model.ser.gz
</code>```

Then you want to add this option:

```<code>-ner.model /Users/stanfordnlphelp/custom_model.ser.gz
</code>```

Body:
Suppose I have the custom model stored at:

/Users/stanfordnlphelp/custom_model.ser.gz

Then you want to add this option:

-ner.model /Users/stanfordnlphelp/custom_model.ser.gz


问:
matplotlib taking time when being imported
I just upgraded to the latest stable release of matplotlib (1.5.1) and everytime I import matplotlib I get this message:

```<code>/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
</code>```

... which always stalls for a few seconds.

Is this the expected behaviour? Was it the same also before, but just without the printed message?

答:
HI you must find this file : font_manager.py in my case : C:\Users\gustavo\Anaconda3\Lib\site-packages\matplotlib\ font_manager.py

and FIND def win32InstalledFonts(directory=None, fontext='ttf') and replace by :

def win32InstalledFonts(directory=None, fontext='ttf'):
    """
    Search for fonts in the specified font directory, or use the
    system directories if none given.  A list of TrueType font
    filenames are returned by default, or AFM fonts if fontext ==
    'afm'.
    """

```<code>from six.moves import winreg
if directory is None:
    directory = win32FontDirectory()

fontext = get_fontext_synonyms(fontext)

key, items = None, {}
for fontdir in MSFontDirectories:
    try:
        local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
    except OSError:
        continue

    if not local:
        return list_fonts(directory, fontext)
    try:
        for j in range(winreg.QueryInfoKey(local)[1]):
            try:
                key, direc, any = winreg.EnumValue(local, j)
                if not is_string_like(direc):
                    continue
                if not os.path.dirname(direc):
                    direc = os.path.join(directory, direc)
                    direc = direc.split('\0', 1)[0]

                if os.path.splitext(direc)[1][1:] in fontext:
                    items[direc] = 1
            except EnvironmentError:
                continue
            except WindowsError:
                continue
            except MemoryError:
                continue
        return list(six.iterkeys(items))
    finally:
        winreg.CloseKey(local)
return None
</code>```

Body:
I just upgraded to the latest stable release of matplotlib (1.5.1) and everytime I import matplotlib I get this message:

/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')

... which always stalls for a few seconds.

Is this the expected behaviour? Was it the same also before, but just without the printed message?

Body:
HI you must find this file : font_manager.py in my case : C:\Users\gustavo\Anaconda3\Lib\site-packages\matplotlib\ font_manager.py

and FIND def win32InstalledFonts(directory=None, fontext='ttf') and replace by :

def win32InstalledFonts(directory=None, fontext='ttf'):
    """
    Search for fonts in the specified font directory, or use the
    system directories if none given.  A list of TrueType font
    filenames are returned by default, or AFM fonts if fontext ==
    'afm'.
    """

from six.moves import winreg
if directory is None:
    directory = win32FontDirectory()

fontext = get_fontext_synonyms(fontext)

key, items = None, {}
for fontdir in MSFontDirectories:
    try:
        local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
    except OSError:
        continue

    if not local:
        return list_fonts(directory, fontext)
    try:
        for j in range(winreg.QueryInfoKey(local)[1]):
            try:
                key, direc, any = winreg.EnumValue(local, j)
                if not is_string_like(direc):
                    continue
                if not os.path.dirname(direc):
                    direc = os.path.join(directory, direc)
                    direc = direc.split('\0', 1)[0]

                if os.path.splitext(direc)[1][1:] in fontext:
                    items[direc] = 1
            except EnvironmentError:
                continue
            except WindowsError:
                continue
            except MemoryError:
                continue
        return list(six.iterkeys(items))
    finally:
        winreg.CloseKey(local)
return None


问:
How can we mock a response from another class using Mockito while unit testing
I have a method to test which is calling another class to get some information:

```<code>public ClassToTest {

    public void methodToTest() {
        AnotherClass ac = Factory.getInstance();
        ResponseObj response = ac.anotherMethod();
    }
}
</code>```

AnotherClass is part of another JAR and I would like to mock the response from it(to be specific mock ResponseObj response)

How can I achieve that using Mockito?

答:
First you need is to make your class testable. It means you need to extract object creation (AnotherClass ac = Factory.getInstance()) from your methodToTest to instance field or maybe separate method (to be able to mock it), or even better - create object outside of your class and pass it via constructor. As a result, your class under test should look like:

```<code>public class ClassToTest {

    private AnotherClass ac;

    public ClassToTest(AnotherClass ac) {
        this.ac = ac;
    }

    public void methodToTest() {
        ResponseObj response = ac.anotherMethod();
        response.smth();
    }
}
</code>```

Then you need to declare AnotherClass and ResponseObj as fields in test class, and initialize them as a mocks.

```<code>AnotherClass ac = Mockito.mock(AnotherClass.class);
ResponseObj responseMock = Mockito.mock(ResponseObj.class);
</code>```

After that you can mock method call:

```<code>when(anotherClassMock.anotherMethod()).thenReturn(responseMock);
</code>```

At the end your test class should look like:

```<code>public class ClassToTestTest {

    private AnotherClass anotherClassMock = mock(AnotherClass.class);
    private ResponseObj responseMock = mock(ResponseObj.class);
    private ClassToTest classToTest = new ClassToTest(anotherClassMock);

    @Test
    public void test() {
        when(anotherClassMock.anotherMethod()).thenReturn(responseMock);

        classToTest.methodToTest();

        verify(responseMock, only()).smth();
    }
}
</code>```

And in case you couldn't change public API of your ClassToTest, you can use approach with Mockito spy and protected method.

```<code>public class ClassToTest {

    public void methodToTest() {
        AnotherClass ac = constructAnotherClassObj();
        ResponseObj response = ac.anotherMethod();
        response.smth();
    }

    protected AnotherClass constructAnotherClassObj() {
        return Factory.getInstance();
    }
}

public class ClassToTestTest {

    private AnotherClass anotherClassMock = mock(AnotherClass.class);
    private ResponseObj responseMock = mock(ResponseObj.class);
    private ClassToTest classToTest = spy(new ClassToTest());

    @Test
    public void test() {
        when(anotherClassMock.anotherMethod()).thenReturn(responseMock);
        when(classToTest.constructAnotherClassObj()).thenReturn(anotherClassMock);

        classToTest.methodToTest();

        verify(responseMock, only()).smth();
    }
}
</code>```

Body:
I have a method to test which is calling another class to get some information:

public ClassToTest {

    public void methodToTest() {
        AnotherClass ac = Factory.getInstance();
        ResponseObj response = ac.anotherMethod();
    }
}

AnotherClass is part of another JAR and I would like to mock the response from it(to be specific mock ResponseObj response)

How can I achieve that using Mockito?

Body:
First you need is to make your class testable. It means you need to extract object creation (AnotherClass ac = Factory.getInstance()) from your methodToTest to instance field or maybe separate method (to be able to mock it), or even better - create object outside of your class and pass it via constructor. As a result, your class under test should look like:

public class ClassToTest {

    private AnotherClass ac;

    public ClassToTest(AnotherClass ac) {
        this.ac = ac;
    }

    public void methodToTest() {
        ResponseObj response = ac.anotherMethod();
        response.smth();
    }
}

Then you need to declare AnotherClass and ResponseObj as fields in test class, and initialize them as a mocks.

AnotherClass ac = Mockito.mock(AnotherClass.class);
ResponseObj responseMock = Mockito.mock(ResponseObj.class);

After that you can mock method call:

when(anotherClassMock.anotherMethod()).thenReturn(responseMock);

At the end your test class should look like:

public class ClassToTestTest {

    private AnotherClass anotherClassMock = mock(AnotherClass.class);
    private ResponseObj responseMock = mock(ResponseObj.class);
    private ClassToTest classToTest = new ClassToTest(anotherClassMock);

    @Test
    public void test() {
        when(anotherClassMock.anotherMethod()).thenReturn(responseMock);

        classToTest.methodToTest();

        verify(responseMock, only()).smth();
    }
}

And in case you couldn't change public API of your ClassToTest, you can use approach with Mockito spy and protected method.

public class ClassToTest {

    public void methodToTest() {
        AnotherClass ac = constructAnotherClassObj();
        ResponseObj response = ac.anotherMethod();
        response.smth();
    }

    protected AnotherClass constructAnotherClassObj() {
        return Factory.getInstance();
    }
}

public class ClassToTestTest {

    private AnotherClass anotherClassMock = mock(AnotherClass.class);
    private ResponseObj responseMock = mock(ResponseObj.class);
    private ClassToTest classToTest = spy(new ClassToTest());

    @Test
    public void test() {
        when(anotherClassMock.anotherMethod()).thenReturn(responseMock);
        when(classToTest.constructAnotherClassObj()).thenReturn(anotherClassMock);

        classToTest.methodToTest();

        verify(responseMock, only()).smth();
    }
}


问:
Visually designing a database structure
I am quite happy to code out tables by hand when making a database but it's not the easiest way to convey information about a database to someone else, especially someone that's not so comfortable coding the tables via a script and would instead use something such at phpMyAdmin.

Is there thus a free program (for me to use it it'll have to work on a Mac but feel free to suggest PC apps for others with the same Q) or script (preferably in PHP or Python) that allows you to design database structure and will then output either a basic diagram or the code as chosen by the user?

答:
I'm currently checking out SQL Power Architect (both w/ PostgreSQL and Mysql - but it also supports other vendors) and it definitely seems promising. Does both forward and backward SQL engineering. The Community Edition is open source and cross platform (Java). You can check it out yourself: http://code.google.com/p/power-architect/

When strictly dealing w/ MySQL so far I've otherwise used MySQL Workbench,  http://wb.mysql.com/ which performed reliably.

OwnerDisplayName: Teifion

ContentLicense: CC BY-SA 2.5

Title: Visually designing a database structure


问:
react render not working with getElementById
Why is the first render working but not the second?

```<code>// load react library
var React = require('react');
var ReactDOM = require('react-dom');

//build first component
/*
   StorePicker
*/
var StorePicker = React.createClass({

    render : function(){
        return (
            <div>
              <p> </p>
              <p>hi</p>
              <p>and this is another</p>
            </div>
        )
    }
})

ReactDOM.render(<StorePicker/>,document.querySelector('#main'));

ReactDOM.render(<StorePicker/>,document.getElementById('#main'));
</code>```

The error I'm getting is:

```<code>Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
</code>```

which doesn't make any sense as it works in the first case

答:
getElementById takes an id without the # prefix as parameter. Try:

```<code>ReactDOM.render(<StorePicker/>, document.getElementById('main'));
</code>```

Body:
Why is the first render working but not the second?

// load react library
var React = require('react');
var ReactDOM = require('react-dom');

//build first component
/*
   StorePicker
*/
var StorePicker = React.createClass({

    render : function(){
        return (

hi

and this is another

        )
    }
})

ReactDOM.render(<StorePicker/>,document.querySelector('#main'));

ReactDOM.render(<StorePicker/>,document.getElementById('#main'));

The error I'm getting is:

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

which doesn't make any sense as it works in the first case

Body:
getElementById takes an id without the # prefix as parameter. Try:

ReactDOM.render(<StorePicker/>, document.getElementById('main'));


问:
How to query all values from 1rst table and fill with 2nd table
Sorry if my question isn't clear at first.

I have those 3 tables:

```<code>Table A:
ID  |   DATE_CREATED

Table B:
ID  |   DATE_CREATED

TABLE C:
ID  |   DATE_CREATED
</code>```

What I want is getting all dates from Table A when ID A and B are the same:

```<code>SELECT A.DATE_CREATED
FROM A, B
WHERE A.ID = B.ID
</code>```

Now what I don't get is how to get all the dates from Table C and put them in the query above so that only the ones that don't exist in that query are put in it.

So if the query outputs

```<code>ID  |   DATE_CREATED
1   |        2010
2   |        2009
3   |        2008
</code>```

And table C contains

```<code>ID  |   DATE_CREATED
1   |        2017
2   |        2005
3   |        2003
4   |        2007
5   |        2010
</code>```

My final result should be

```<code>ID  |   DATE_CREATED
1   |        2010
2   |        2009
3   |        2008
4   |        2007
5   |        2010
</code>```

Thank you for reading my question! I am aware that this might question might already have been answered, as it is basic, but even by reading some similar questions my brain isn't able to process how to do it. I guess it's with a left join or something like that from what I read, but I don't get how it works even by checking examples and checking those join graphs.

答:
To clarify:

You want to display

```<code>A.ID, A.DATE_CREATED
</code>```

or if there are no matches between A and B's ID fields then you want to display

```<code>C.ID, C.DATE_CREATED
</code>```

So, you've already figured out how to get the first bit:

```<code>SELECT  A.ID, A.DATE_CREATED
FROM    A
INNER JOIN  B
ON  A.ID = B.ID
</code>```

To add to the other 2 answers, here's how I'd do it old-school with temp tables:

```<code>SELECT  A.ID, A.DATE_CREATED
INTO    #tmpA
FROM    A
INNER JOIN  B
ON  A.ID = B.ID

SELECT  #tmpA.ID , #tmpA.DATE_CREATED
FROM    #tmpA
UNION SELECT    C.ID, C.DATE_CREATED
FROM    C
LEFT JOIN   #tmpA
ON  C.ID = #tmpA.ID
WHERE   #tmpA.ID IS NULL
</code>```

Body:
Sorry if my question isn't clear at first.

I have those 3 tables:

Table A:
ID  |   DATE_CREATED

Table B:
ID  |   DATE_CREATED

TABLE C:
ID  |   DATE_CREATED

What I want is getting all dates from Table A when ID A and B are the same:

SELECT A.DATE_CREATED
FROM A, B
WHERE A.ID = B.ID

Now what I don't get is how to get all the dates from Table C and put them in the query above so that only the ones that don't exist in that query are put in it.

So if the query outputs

ID  |   DATE_CREATED
1   |        2010
2   |        2009
3   |        2008

And table C contains

ID  |   DATE_CREATED
1   |        2017
2   |        2005
3   |        2003
4   |        2007
5   |        2010

My final result should be

ID  |   DATE_CREATED
1   |        2010
2   |        2009
3   |        2008
4   |        2007
5   |        2010

Thank you for reading my question! I am aware that this might question might already have been answered, as it is basic, but even by reading some similar questions my brain isn't able to process how to do it. I guess it's with a left join or something like that from what I read, but I don't get how it works even by checking examples and checking those join graphs.

Body:
To clarify:

You want to display

A.ID, A.DATE_CREATED

or if there are no matches between A and B's ID fields then you want to display

C.ID, C.DATE_CREATED

So, you've already figured out how to get the first bit:

SELECT  A.ID, A.DATE_CREATED
FROM    A
INNER JOIN  B
ON  A.ID = B.ID

To add to the other 2 answers, here's how I'd do it old-school with temp tables:

SELECT  A.ID, A.DATE_CREATED
INTO    #tmpA
FROM    A
INNER JOIN  B
ON  A.ID = B.ID

SELECT  #tmpA.ID , #tmpA.DATE_CREATED
FROM    #tmpA
UNION SELECT    C.ID, C.DATE_CREATED
FROM    C
LEFT JOIN   #tmpA
ON  C.ID = #tmpA.ID
WHERE   #tmpA.ID IS NULL


问:
Single piece of content, multiple URLs?
I have a use case that I could use some advice on.

We publish multiple products, each of which has it's own subtree on the site. Generally, a piece of content gets published to just a single product, e.g. a news article gets published to product A and can be accessed at one URL.

However, sometimes we have content that we want to publish to multiple products, e.g. a single news article gets published to products A, B, and C and will be available at 3 different URLs.

With our current CMS we end up doing this by copying and pasting the content, which is a hassle for editors, especially if the content needs to be updated.

An ideal scenario would be where and editor edits the content in one place, specifies the products to publish to, and the content is served by more than one URL and with a template that is product-specific.

It seems that RoutablePageMixin could be useful here, but I'm not sure how to handle letting the editor specify the destination products and making the routing aware of that choice.

Has anyone solved a similar problem using Wagtail?

答:
Rather than thinking of your news articles as being child objects of one or more products, it might help to think of them as one big pool of news articles which are categorised by product. Your product page will then effectively be a filtered index page of news articles.

Here's how I'd model it:

If you want your news articles to exist at a canonical URL that's independent of any particular category, or you want to make use of page moderation and/or previewing, then define NewsArticle as a page model; otherwise, define it as a snippet or a ModelAdmin-managed model.

On the NewsArticle model, have an InlinePanel where editors can associate as many related products as required:

```<code>class NewsArticle(Page):
    body = RichTextField()
    date = models.DateField()

    content_panels = Page.content_panels + [
        FieldPanel('body'),
        FieldPanel('date'),
        InlinePanel('related_products', label="Related products"),
    ]

class NewsArticleRelatedProduct(Orderable):
    news_article = ParentalKey(NewsArticle, related_name='related_products')
    product = models.ForeignKey(ProductPage, on_delete=models.CASCADE, related_name='news_articles')

    panels = [
        PageChooserPanel('product'),
    ]
</code>```

On your ProductPage model, add a method that returns a queryset of news items, filtered and sorted appropriately:

```<code>class ProductPage(Page):
    # ...
    def get_news_articles(self):
        return self.news_articles.live().order_by('-date')
</code>```

You can then loop over the news articles in your product page template, using a tag like {% for news_article in page.get_news_articles %}.

Title: Single piece of content, multiple URLs?

Body:
Rather than thinking of your news articles as being child objects of one or more products, it might help to think of them as one big pool of news articles which are categorised by product. Your product page will then effectively be a filtered index page of news articles.

Here's how I'd model it:

If you want your news articles to exist at a canonical URL that's independent of any particular category, or you want to make use of page moderation and/or previewing, then define NewsArticle as a page model; otherwise, define it as a snippet or a ModelAdmin-managed model.

On the NewsArticle model, have an InlinePanel where editors can associate as many related products as required:

class NewsArticle(Page):
    body = RichTextField()
    date = models.DateField()

    content_panels = Page.content_panels + [
        FieldPanel('body'),
        FieldPanel('date'),
        InlinePanel('related_products', label="Related products"),
    ]

class NewsArticleRelatedProduct(Orderable):
    news_article = ParentalKey(NewsArticle, related_name='related_products')
    product = models.ForeignKey(ProductPage, on_delete=models.CASCADE, related_name='news_articles')

    panels = [
        PageChooserPanel('product'),
    ]

On your ProductPage model, add a method that returns a queryset of news items, filtered and sorted appropriately:

class ProductPage(Page):
    # ...
    def get_news_articles(self):
        return self.news_articles.live().order_by('-date')

You can then loop over the news articles in your product page template, using a tag like {% for news_article in page.get_news_articles %}.


问:
Use a regex for matching the value of an attribute parsing with beautifulsoup
Hi from the clumsyland,

I'm trying to parse a forum. More specifically, the threads' names.

the threads are offered by the forum engine (vbulletin) as this

```<code><a href="http://www.example.com/showthread.php?t=555555" id="thread_title_555555">NAME OF THE TITLE</a>
</code>```

Using python and beautifulsoup, I have obtain successes with other fields. However, I'm not able to parse "id" attribute using a regex. I need that these lines of the parser find every "a" element with a six-figure id and get the text from it

something like this

```<code>for elements in soup.findAll("a"):
    if re.match("thread_title_", element['id']) is not None:
        print element.text
</code>```

or in pseudopython:

```<code>for elements in soup.finAll("a", {"id": "thread_title_".*}):
    print element.text
</code>```

I tried dozens of variations, for no avail. What can I do?

Thanks in advance

答:
You can match the id with a regex in the call to findAll()...

```<code>for element in soup.findAll("a", id=re.compile("^thread_title_")):
    print element.text
</code>```

Body:
Hi from the clumsyland,

I'm trying to parse a forum. More specifically, the threads' names.

the threads are offered by the forum engine (vbulletin) as this

NAME OF THE TITLE

Using python and beautifulsoup, I have obtain successes with other fields. However, I'm not able to parse "id" attribute using a regex. I need that these lines of the parser find every "a" element with a six-figure id and get the text from it

something like this

for elements in soup.findAll("a"):
    if re.match("thread_title_", element['id']) is not None:
        print element.text

or in pseudopython:

for elements in soup.finAll("a", {"id": "thread_title_".*}):
    print element.text

I tried dozens of variations, for no avail. What can I do?

Thanks in advance

Body:
You can match the id with a regex in the call to findAll()...

for element in soup.findAll("a", id=re.compile("^thread_title_")):
    print element.text


问:
Python regular expression to remove caption
I have the following text crawled from a webpage:

A female believed to be around 25 years old, she was captured in the
  wild in Malaysian Borneo in 2011 and lived the rest of her life at the
  Tabin Wildlife Reserve in Sabah, a fenced-in facility managed by BORA.
  [caption id="attachment_194682" align="aligncenter" width="768"] Rhino
  being cared for at the Borneo rhino sanctuary. Photo courtesy of Sabah
  Wildlife Department.[/caption] Overall, between 55 and 100 of the
  Critically Endangered species are believed to remain

You can see that there is text between squared brackets of caption. Basically, I want to remove everything between squared brackets, and the sentence

Rhino being cared for at the Borneo rhino sanctuary. Photo courtesy of
  Sabah Wildlife Department

because it is the caption for an image. So the result should be:

A female believed to be around 25 years old, she was captured in the
  wild in Malaysian Borneo in 2011 and lived the rest of her life at the
  Tabin Wildlife Reserve in Sabah, a fenced-in facility managed by BORA.
  Overall, between 55 and 100 of the Critically Endangered species are
  believed to remain ...

How can I do it?

答:
You can use the python re module to fetch data between caption like so:

```<code>import re
text = """
A female believed to be around 25 years old, she was captured in the wild in Malaysian Borneo in 2011 and lived the rest of her life at the Tabin Wildlife Reserve in Sabah, a fenced-in facility managed by BORA. [caption id="attachment_194682" align="aligncenter" width="768"] Rhino being cared for at the Borneo rhino sanctuary. Photo courtesy of Sabah Wildlife Department.[/caption] Overall, between 55 and 100 of the Critically Endangered species are believed to remain
"""

pattern = r'\[caption.*\](.*)\[/caption\]'
items = re.search(pattern, text)
print text.replace(items.group(0), '')

#  A female believed to be around 25 years old, she was captured in the wild in Malaysian Borneo in 2011 and lived the rest of her life at the Tabin Wildlife Reserve in Sabah, a fenced-in facility managed by BORA.  Overall, between 55 and 100 of the Critically Endangered species are believed to remain
</code>```

Body:
You can use the python re module to fetch data between caption like so:

import re
text = """
A female believed to be around 25 years old, she was captured in the wild in Malaysian Borneo in 2011 and lived the rest of her life at the Tabin Wildlife Reserve in Sabah, a fenced-in facility managed by BORA. [caption id="attachment_194682" align="aligncenter" width="768"] Rhino being cared for at the Borneo rhino sanctuary. Photo courtesy of Sabah Wildlife Department.[/caption] Overall, between 55 and 100 of the Critically Endangered species are believed to remain
"""

pattern = r'\[caption.*\](.*)\[/caption\]'
items = re.search(pattern, text)
print text.replace(items.group(0), '')

#  A female believed to be around 25 years old, she was captured in the wild in Malaysian Borneo in 2011 and lived the rest of her life at the Tabin Wildlife Reserve in Sabah, a fenced-in facility managed by BORA.  Overall, between 55 and 100 of the Critically Endangered species are believed to remain


问:
Function is not defined - module.exports - Express
I have a strange behavior in my Express app which I cannot understand. I have a user model file (user.js) which contains some schemas and some functions. When I require the file from my routes file (users.js) I can access Schemas but cannot call functions as they return 'myFunc is not a function'. This happens only in case I have multiple schemas, in case of one schema everything is perfect. Could you please help me to figure out?

This one returns: userModels.User.addUser is not a function

user.js

```<code>...
const UserModels = module.exports = {
    'User': mongoose.model('User', UserSchema),
    'Token': mongoose.model('Token', TokenSchema)
}

module.exports.addUser = function(newUser, callback){
    console.log('test');
}
...
</code>```

users.js

```<code>...
userModels.User.addUser(newUser, function(err, user){
    if(err){
        res.json({success: false, msg: "Failed to register."});
    } else{
        res.json({success: true, msg: 'User has been registered'});
    }
});
...
</code>```

This one passes:

```<code>...

const User = module.exports = mongoose.model('User', UserSchema);

module.exports.addUser = function(newUser, callback){
    console.log('test');
}

...

User.addUser(newUser, function(err, user){
    if(err){
        res.json({success: false, msg: "Failed to register."});
    } else{
        res.json({success: true, msg: 'User has been registered'});
    }
});

...
</code>```

答:
So I solved the issue with the following:

User.js

```<code>UserSchema.statics.addUser = function(newUser, callback){

    console.log('test');

}

module.exports = {
    'User': mongoose.model('User', UserSchema),
    'Token': mongoose.model('Token', TokenSchema)
};
</code>```

And in users.js I can access both models and it's methods like this:

```<code>const UserModels = require("../models/user");

UserModels.User;
UserModels.Token;
UserModels.User.AddUser();
</code>```

Thanks.

Body:
I have a strange behavior in my Express app which I cannot understand. I have a user model file (user.js) which contains some schemas and some functions. When I require the file from my routes file (users.js) I can access Schemas but cannot call functions as they return 'myFunc is not a function'. This happens only in case I have multiple schemas, in case of one schema everything is perfect. Could you please help me to figure out?

This one returns: userModels.User.addUser is not a function

user.js

...
const UserModels = module.exports = {
    'User': mongoose.model('User', UserSchema),
    'Token': mongoose.model('Token', TokenSchema)
}

module.exports.addUser = function(newUser, callback){
    console.log('test');
}
...

users.js

...
userModels.User.addUser(newUser, function(err, user){
    if(err){
        res.json({success: false, msg: "Failed to register."});
    } else{
        res.json({success: true, msg: 'User has been registered'});
    }
});
...

This one passes:

...

const User = module.exports = mongoose.model('User', UserSchema);

module.exports.addUser = function(newUser, callback){
    console.log('test');
}

...

User.addUser(newUser, function(err, user){
    if(err){
        res.json({success: false, msg: "Failed to register."});
    } else{
        res.json({success: true, msg: 'User has been registered'});
    }
});

...

Body:
So I solved the issue with the following:

User.js

UserSchema.statics.addUser = function(newUser, callback){

    console.log('test');

}

module.exports = {
    'User': mongoose.model('User', UserSchema),
    'Token': mongoose.model('Token', TokenSchema)
};

And in users.js I can access both models and it's methods like this:

const UserModels = require("../models/user");

UserModels.User;
UserModels.Token;
UserModels.User.AddUser();

Thanks.


问:
Static method heritation
I have a parent class with methods for writing and reading it from the db. The problem is I have a static method which I want to generalise. What is the best practice for doing this? I've came up with some solutions but all don't work with the static method.

Is there a way to force the childobject to implement the abstract method?

Parent Class:

```<code>public class Data_object  {

    public byte[] toByteArray() throws IOException  {
        return null;
    }
    public static Data_object fromByteArray(byte[] data){
        return null
    }
}
</code>```

Child class:

```<code>public class ModelObject extends Data_object {

    public static Data_object fromByteArray(byte[] data){
        ModelObject result = new ModelObject();
        //set data from byte arrray
        return result;
    }
}
</code>```

thanks

答:
A static method in Java can't be abstract and you can't override it. So you can't force a subclass to implement a certain static method.

The only way out is to require the static method by convention (like a note in the accompagnying JavaDoc) and using reflection to ensure at runtime (or at build time), that the subclass implements the required static method.

BTW - this is a common "pattern". Serializable does not define any methods, but it's documentation mentions three methods:

```<code>private void writeObject(java.io.ObjectOutputStream out)
   throws IOException
private void readObject(java.io.ObjectInputStream in)
   throws IOException, ClassNotFoundException;
private void readObjectNoData()
   throws ObjectStreamException;
</code>```

The "object serialization framework" now uses reflection to test, if those methods are implemented by a class and, if yes, invokes those methods.

But I recommend looking for other solutions before using this strategy.

Title: Static method heritation

Body:
I have a parent class with methods for writing and reading it from the db. The problem is I have a static method which I want to generalise. What is the best practice for doing this? I've came up with some solutions but all don't work with the static method.

Is there a way to force the childobject to implement the abstract method?

Parent Class:

public class Data_object  {

    public byte[] toByteArray() throws IOException  {
        return null;
    }
    public static Data_object fromByteArray(byte[] data){
        return null
    }
}

Child class:

public class ModelObject extends Data_object {

    public static Data_object fromByteArray(byte[] data){
        ModelObject result = new ModelObject();
        //set data from byte arrray
        return result;
    }
}

thanks

Body:
A static method in Java can't be abstract and you can't override it. So you can't force a subclass to implement a certain static method.

The only way out is to require the static method by convention (like a note in the accompagnying JavaDoc) and using reflection to ensure at runtime (or at build time), that the subclass implements the required static method.

BTW - this is a common "pattern". Serializable does not define any methods, but it's documentation mentions three methods:

private void writeObject(java.io.ObjectOutputStream out)
   throws IOException
private void readObject(java.io.ObjectInputStream in)
   throws IOException, ClassNotFoundException;
private void readObjectNoData()
   throws ObjectStreamException;

The "object serialization framework" now uses reflection to test, if those methods are implemented by a class and, if yes, invokes those methods.

But I recommend looking for other solutions before using this strategy.


问:
Populating an ngrx store with data shared between routes
I have a multi-page form spanning over several routes. All of the routes need the same data shared with them from an API. I can store the response of the API inside ngrx/store and trigger the API call using an effect. My question is more about where to initiate the API call. The API call needs to be made once the user is authenticated, which happens on the very first route I hit (before the first part of the multi page form is visited). The two options I've come up with are:

Triggering the effect inside each route's component meaning I'll just have to request the information every time I visit a route. A guard will prevent all pages being accessible while the user isn't authenticated.

Listen to the authenticated success action inside an effect and make the request to the API there.

I'm sure both are perfectly acceptable and have their trade offs. It'd just be good to get a few opinions!

答: The second would be the best, requesting the information on demand ergo when the user is authentified and its allowed to use it makes more sense. Inside of the guard, as u said, you should dispatch the action to load the information before you return true/of(true) to signalize that the route can be activated. The naive approach for this would trigger an information request everythime that you try to activate the guarded route.</p>


问:
Get Objects from Json
I have this Json

```<code>var data = "{"2144":{"quantity":"350"},"2095":{"quantity":"100"}}"
</code>```

how can i get each value like this order using jquery?

2144 - quantity:350
2095 - quantity:100

答:
Loop through each key/value pair in nested format like this:

 var data = JSON.parse( '{"2144":{"quantity":"350"},"2095":    {"quantity":"100"}}');

    $.each(data , function(key , value){
     $.each(value , function(k , v ){
         console.log(key + '-' + k + ':' + v)
     });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Get Objects from Json

Body:
I have this Json

var data = "{"2144":{"quantity":"350"},"2095":{"quantity":"100"}}"

how can i get each value like this order using jquery?

2144 - quantity:350
2095 - quantity:100

Body:
Loop through each key/value pair in nested format like this:

 var data = JSON.parse( '{"2144":{"quantity":"350"},"2095":    {"quantity":"100"}}');

    $.each(data , function(key , value){
     $.each(value , function(k , v ){
         console.log(key + '-' + k + ':' + v)
     });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Android Wear TextRenderer does not fill the bounds
I'm trying out the fairly new TextRenderer in the Android wear support library whilst making a watch face app.

In the onDraw method, I call setText, and then I call draw and pass in the bounds from the parent onDraw method (280x280).

```<code>    String text = String.format(Locale.getDefault(), "%02d:%02d", hour, minute);
    textRenderer.setText(text);
    textRenderer.draw(canvas, bounds);
</code>```

Unfortunately the text being printed out is tiny, it's super hard to find examples out there.

I've read through the reference page and the solution is not coming to me.

https://developer.android.com/reference/android/support/wearable/complications/rendering/TextRenderer.html

答: You can set a TextPaint on the TextRenderer and it will use the text size of that TextPaint object as the initial size of your text.</p>

Body:
I'm trying out the fairly new TextRenderer in the Android wear support library whilst making a watch face app.

In the onDraw method, I call setText, and then I call draw and pass in the bounds from the parent onDraw method (280x280).

    String text = String.format(Locale.getDefault(), "%02d:%02d", hour, minute);
    textRenderer.setText(text);
    textRenderer.draw(canvas, bounds);

Unfortunately the text being printed out is tiny, it's super hard to find examples out there.

I've read through the reference page and the solution is not coming to me.

https://developer.android.com/reference/android/support/wearable/complications/rendering/TextRenderer.html


问:
How does Rails find the correct database adapter through the database.yml?
The database.yml file has a adapter: postgresql, how does this lead the rails server to connect to the postgres program? If I'm running the server locally does Rails look through my PATH or something to find the location of where my postgres is installed?

答:
The answer is pretty much right in the database.yml comments:

```<code> # The TCP port the server listens on. Defaults to 5432.
 # If your server runs on a different port number, change accordingly.
 # port: 5432
</code>```

So, if you've done a vanilla installation, then rails just uses port 5432 to connect to your and communicate with your database.

Body:
The answer is pretty much right in the database.yml comments:

 # The TCP port the server listens on. Defaults to 5432.
 # If your server runs on a different port number, change accordingly.
 # port: 5432

So, if you've done a vanilla installation, then rails just uses port 5432 to connect to your and communicate with your database.


问:
Download large file in python with requests
Requests is a really nice library. I'd like to use it for downloading big files (>1GB).
The problem is it's not possible to keep whole file in memory; I need to read it in chunks. And this is a problem with the following code:

```<code>import requests

def DownloadFile(url)
    local_filename = url.split('/')[-1]
    r = requests.get(url)
    f = open(local_filename, 'wb')
    for chunk in r.iter_content(chunk_size=512 * 1024):
        if chunk: # filter out keep-alive new chunks
            f.write(chunk)
    f.close()
    return
</code>```

For some reason it doesn't work this way; it still loads the response into memory before it is saved to a file.

答:
Not exactly what OP was asking, but... it's ridiculously easy to do that with urllib:

```<code>from urllib.request import urlretrieve

url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
dst = 'ubuntu-16.04.2-desktop-amd64.iso'
urlretrieve(url, dst)
</code>```

Or this way, if you want to save it to a temporary file:

```<code>from urllib.request import urlopen
from shutil import copyfileobj
from tempfile import NamedTemporaryFile

url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
with urlopen(url) as fsrc, NamedTemporaryFile(delete=False) as fdst:
    copyfileobj(fsrc, fdst)
</code>```

I watched the process:

```<code>watch 'ps -p 18647 -o pid,ppid,pmem,rsz,vsz,comm,args; ls -al *.iso'
</code>```

And I saw the file growing, but memory usage stayed at 17 MB. Am I missing something?

ContentLicense: CC BY-SA 4.0

Body:
Requests is a really nice library. I'd like to use it for downloading big files (>1GB).
The problem is it's not possible to keep whole file in memory; I need to read it in chunks. And this is a problem with the following code:

import requests

def DownloadFile(url)
    local_filename = url.split('/')[-1]
    r = requests.get(url)
    f = open(local_filename, 'wb')
    for chunk in r.iter_content(chunk_size=512 * 1024):
        if chunk: # filter out keep-alive new chunks
            f.write(chunk)
    f.close()
    return

For some reason it doesn't work this way; it still loads the response into memory before it is saved to a file.

Body:
Not exactly what OP was asking, but... it's ridiculously easy to do that with urllib:

from urllib.request import urlretrieve

url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
dst = 'ubuntu-16.04.2-desktop-amd64.iso'
urlretrieve(url, dst)

Or this way, if you want to save it to a temporary file:

from urllib.request import urlopen
from shutil import copyfileobj
from tempfile import NamedTemporaryFile

url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
with urlopen(url) as fsrc, NamedTemporaryFile(delete=False) as fdst:
    copyfileobj(fsrc, fdst)

I watched the process:

watch 'ps -p 18647 -o pid,ppid,pmem,rsz,vsz,comm,args; ls -al *.iso'

And I saw the file growing, but memory usage stayed at 17 MB. Am I missing something?


问:
function to be run multiple times to generate the final dataset in R
I am new to R and have written a function that needs to be run multiple times to generate the final dataset.
So the multiple times is determined by the vector of unique years and again based on these years every single time the function gives an output.
Still I am not getting the right output.

Desired output: for eg it takes 10 samples from each year, after 10th run I should have 100 rows of correct output.

```<code>create_strsample <- function(n1,n2){
   yr <- c(2010,2011,2012,2013)
   for(i in 1:length(yr)){

     k1<-subset(data,format(as.Date(data$account_opening_date),"%Y")==yr[i])
     r1 <-sample(which(!is.na(k1$account_closing_date)),n1,replace=FALSE)
     r2<-sample(which(is.na(k1$account_closing_date)),n2,replace=FALSE)
     #final.data <-k1[c(r1,r2),]
     sample.data <- lapply(yr, function(x) {f.data<-create_strsample(200,800)})

     k1 <- do.call(rbind,k1)
     return(k1)
   }

   final <- do.call(rbind,sample.data)
   return(final)
}
stratified.sample.data <- create_strsample(200,800)
</code>```

答:
A MWE would have been nice, but I'll give you a template for these kind of questions. Note, that this is not optimized for speed (or anything else), but only for the ease of understanding.

As noted in the comments, that call to create_strsample in the loop looks weird and probably isn't what you really want.

```<code>data <- data.frame()         # we need an empty, but existing variable for the first loop iteration
for (i in 1:10) {
    temp <- runif(1,max=i)   # do something...
    data <- rbind(data,temp) # ... and add this to 'data'
}                            # repeat 10 times
rm(temp)                     # don't need this anymore
</code>```

That return(k1) in the loop also looks wrong.

Body:
I am new to R and have written a function that needs to be run multiple times to generate the final dataset.
So the multiple times is determined by the vector of unique years and again based on these years every single time the function gives an output.
Still I am not getting the right output.

Desired output: for eg it takes 10 samples from each year, after 10th run I should have 100 rows of correct output.

create_strsample <- function(n1,n2){
   yr <- c(2010,2011,2012,2013)
   for(i in 1:length(yr)){

     k1<-subset(data,format(as.Date(data$account_opening_date),"%Y")==yr[i])
     r1 <-sample(which(!is.na(k1$account_closing_date)),n1,replace=FALSE)
     r2<-sample(which(is.na(k1$account_closing_date)),n2,replace=FALSE)
     #final.data <-k1[c(r1,r2),]
     sample.data <- lapply(yr, function(x) {f.data<-create_strsample(200,800)})

     k1 <- do.call(rbind,k1)
     return(k1)
   }

   final <- do.call(rbind,sample.data)
   return(final)
}
stratified.sample.data <- create_strsample(200,800)

Body:
A MWE would have been nice, but I'll give you a template for these kind of questions. Note, that this is not optimized for speed (or anything else), but only for the ease of understanding.

As noted in the comments, that call to create_strsample in the loop looks weird and probably isn't what you really want.

data <- data.frame()         # we need an empty, but existing variable for the first loop iteration
for (i in 1:10) {
    temp <- runif(1,max=i)   # do something...
    data <- rbind(data,temp) # ... and add this to 'data'
}                            # repeat 10 times
rm(temp)                     # don't need this anymore

That return(k1) in the loop also looks wrong.


问:
How to remove all strings inside a string AND the matching string
If there's already a question for this I'll delete it, but couldn't find anything quite like the issue I have. I have a string, let's say

 string here string here string here

(usually would be a bit more complicated, but for ease of example, this is valid. I want to remove everything inside the

, which I did quite successfully using this regex:

```<code>new Regex("(\\<blockquote)(.*?)(\\</blockquote\\>)");
string Result = x.Replace(Text, "$1" + repl + "$3");
</code>```

This gets me about 90% of the way. I would like my Regex to not only remove what's in it, but also the blockquotes themselves.

Here's a test environment which has what I currently have. I have an example string in there, that looks like this:

```<code>Testing: h<sub>2</sub>0 40<sup>th</sup>.<br /> <br /> <div> <blockquote class=\"twitter-tweet\" data-lang=\"en\"><p lang=\"en\" dir=\"ltr\">Breaking: Thad Matta is out as Ohio State men's basketball coach after 13 seasons. <a href=\"{link_ommitted}\">pic.twitter.com/XhFreY9j2S</a></p>— SportsCenter (@SportsCenter) <a href=\"https://twitter.com/SportsCenter/status/871793341435965441\">June 5, 2017</a></blockquote>
</code>```

The result looks like this:

Testing: h20 40th.

 <blockquote

 <blockquote

Which like I said, gets me about 90% of the way. Now I can easily just do Result = Result.Replace("<blockquote
", string.Empty) and I'd be set to go. But I wanted to know if there was a way I can do this in my initial Regex.Replace method as shown above.

答:
You're readding group 1 and 3 in your replace-method. Try this instead</p>

```<code>string Result = x.Replace(Text, repl);
</code>```

Body:
If there's already a question for this I'll delete it, but couldn't find anything quite like the issue I have. I have a string, let's say

 string here string here string here

(usually would be a bit more complicated, but for ease of example, this is valid. I want to remove everything inside the

, which I did quite successfully using this regex:

new Regex("(\\<blockquote)(.*?)(\\
)");
string Result = x.Replace(Text, "$1" + repl + "$3");

This gets me about 90% of the way. I would like my Regex to not only remove what's in it, but also the blockquotes themselves.

Here's a test environment which has what I currently have. I have an example string in there, that looks like this:

Testing: h20 40th.

Breaking: Thad Matta is out as Ohio State men's basketball coach after 13 seasons. pic.twitter.com/XhFreY9j2S
— SportsCenter (@SportsCenter) June 5, 2017

The result looks like this:

Testing: h20 40th.

 <blockquote

 <blockquote

Which like I said, gets me about 90% of the way. Now I can easily just do Result = Result.Replace("<blockquote
", string.Empty) and I'd be set to go. But I wanted to know if there was a way I can do this in my initial Regex.Replace method as shown above.

Body:
You're readding group 1 and 3 in your replace-method. Try this instead

string Result = x.Replace(Text, repl);


问:
PHP = append a 0 to the end of a string
I have this function which takes the average user rating given to an item and converts it to a relevant class:

```<code>function get_user_rating_class($urate_ave){
    if($urate_ave==='0.0'){
        $user_rating_class='unrated_u';
    }else{
        $round_to = 0.5;
        $rounded = round($urate_ave / $round_to) * $round_to;
        $removedec = str_replace('.','',$rounded);
        if(strlen($removedec)<2){$removedec.'0';}
        $user_rating_class='rating_user_'+$removedec;
    }
    return $user_rating_class;
}
</code>```

No when I put a value, say 3.0 into the function it should come out as rating_user_30 but instead it is coming out as rating_user_3, so there must be something wrong with this line:

if(strlen($removedec)<2){$removedec.'0';}

I thought it might be because It was treating the value $removedec as a number rather than a string so I tried adding this line just before it, but no change:

```<code>$removedec = strval($removedec);
</code>```

Could someone tell me what I am doing wrong here.

答:
Suppose there is a integer variable and you do not know what the value is then:

```<code>$var = 0;
$str = "var is : " . ($var?$var:'0');
</code>```

attache the value at the end of string.

Title: PHP = append a 0 to the end of a string

Body:
I have this function which takes the average user rating given to an item and converts it to a relevant class:

function get_user_rating_class($urate_ave){
    if($urate_ave==='0.0'){
        $user_rating_class='unrated_u';
    }else{
        $round_to = 0.5;
        $rounded = round($urate_ave / $round_to) * $round_to;
        $removedec = str_replace('.','',$rounded);
        if(strlen($removedec)<2){$removedec.'0';}
        $user_rating_class='rating_user_'+$removedec;
    }
    return $user_rating_class;
}

No when I put a value, say 3.0 into the function it should come out as rating_user_30 but instead it is coming out as rating_user_3, so there must be something wrong with this line:

if(strlen($removedec)<2){$removedec.'0';}

I thought it might be because It was treating the value $removedec as a number rather than a string so I tried adding this line just before it, but no change:

$removedec = strval($removedec);

Could someone tell me what I am doing wrong here.

Body:
Suppose there is a integer variable and you do not know what the value is then:

$var = 0;
$str = "var is : " . ($var?$var:'0');

attache the value at the end of string.


问:
C - representing binary in #defines
The code snippet below works as is but if I uncomment the first #define and comment the second the compiler complains about expecting a ')' at the assignment statement. Thought it might be wanting a cast but that did not help. Please point out my stupid oversight.

Thanks,
jh

```<code>//#define SMI_READ  (0b10 << 10)
#define SMI_READ  (0x2 << 10)
    ...
    command |= SMI_READ;
</code>```

答:
From C standard (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf)

6.4.4.1 Integer constants

  ...

  octal-constant:

  0

  octal-constant octal-digit

  ...

  hexadecimal-prefix: one of

  0x 0X

No other prefixes are described, especially nothing which would cover 0b10.

Title: C - representing binary in #defines

Body:
The code snippet below works as is but if I uncomment the first #define and comment the second the compiler complains about expecting a ')' at the assignment statement. Thought it might be wanting a cast but that did not help. Please point out my stupid oversight.

Thanks,
jh

//#define SMI_READ  (0b10 << 10)
#define SMI_READ  (0x2 << 10)
    ...
    command |= SMI_READ;


问:
How to move a turtle stamp in python
How do I move a stamp in python turtle module?

Here's my code so far:

```<code>import turtle

def draw_start():
    turtle.pu()
    turtle.setpos(-350,300)
    turtle.pendown()
    turtle.right(90)
    turtle.forward(520)

def draw_finish():
    turtle.speed(15)
    turtle.pu()
    for i in range(18):
        turtle.setpos(200,(300-(i*30)))
        square()
    for j in range(18):
        turtle.setpos(215,(285-(j*30)))
        square()

def stamp_turtle(x,y,color):
    turtle.pu()
    turtle.setheading(0)
    turtle.shape("turtle")
    turtle.color(color)
    turtle.setpos(x,y)
    stamp_list.append(turtle.stamp())

def square():
    turtle.pu()
    turtle.fill(True)
    for i in range(4):
        turtle.forward(15)
        turtle.right(90)
    turtle.fill(False)

print "Welcome to Turtle Racing : "
number_of_turtles = int(raw_input("How many turtles (between 3 and 6) : "))
bet_amount = int(raw_input("How much do you want to bet? $ "))
bet_turtle = raw_input("Which turtle (1 to 5)? ")

color_list=["red","blue","green","brown","yellow","purple"]
stamp_list=[]
draw_start()
draw_finish()
for i in range(number_of_turtles):
    stamp_turtle(-370,280-i*90,color_list[i])`
</code>```

答:
The answer is you don't move stamps, you move turtles!  Stamps have to be removed and restamped whereas turtles can move without redrawing:

```<code>import random
import turtle

STAMP_SIZE = 20
SQUARE_SIZE = 15
FINISH_LINE = 200
COLOR_LIST = ['red', 'blue', 'green', 'brown', 'yellow', 'purple']

def draw_start():
    turtle.speed('fastest')
    turtle.penup()
    turtle.setpos(-350, 300)
    turtle.pendown()
    turtle.right(90)
    turtle.forward(520)

def draw_finish():
    turtle.shape('square')
    turtle.shapesize(SQUARE_SIZE / STAMP_SIZE)
    turtle.penup()

    for i in range(18):
        turtle.setpos(FINISH_LINE, (300 - (i * SQUARE_SIZE * 2)))
        turtle.stamp()

    for j in range(18):
        turtle.setpos(FINISH_LINE + SQUARE_SIZE, ((300 - SQUARE_SIZE) - (j * SQUARE_SIZE  * 2)))
        turtle.stamp()

    turtle.hideturtle()

def move_turtle(who):
    who.forward(random.randint(1, 10))
    if who.xcor() < FINISH_LINE:
        turtle.ontimer(lambda who=who: move_turtle(who), 50)

print('Welcome to Turtle Racing!')
number_of_turtles = int(input('How many turtles (between 3 and 6): '))

draw_start()
draw_finish()

turtle_list = []

for idx in range(number_of_turtles):
    racer = turtle.Turtle('turtle', visible=False)
    racer.speed('fastest')  # affects drawing speed, not forward motion
    racer.penup()
    racer.setpos(-350 - STAMP_SIZE, 280 - idx * 90)
    racer.color(COLOR_LIST[idx])
    racer.showturtle()

    turtle_list.append(racer)

for racer in turtle_list:
    turtle.ontimer(lambda who=racer: move_turtle(who), 100)

turtle.exitonclick()
</code>```

The place where stamping speeds things up is in making your finish line which takes much longer if you try to draw it.

Note that although your original code is Python 2, my answer is Python 3 so you may need to tweak a couple of things if you're still using the older version.

Title: How to move a turtle stamp in python

Body:
How do I move a stamp in python turtle module?

Here's my code so far:

import turtle

def draw_start():
    turtle.pu()
    turtle.setpos(-350,300)
    turtle.pendown()
    turtle.right(90)
    turtle.forward(520)

def draw_finish():
    turtle.speed(15)
    turtle.pu()
    for i in range(18):
        turtle.setpos(200,(300-(i*30)))
        square()
    for j in range(18):
        turtle.setpos(215,(285-(j*30)))
        square()

def stamp_turtle(x,y,color):
    turtle.pu()
    turtle.setheading(0)
    turtle.shape("turtle")
    turtle.color(color)
    turtle.setpos(x,y)
    stamp_list.append(turtle.stamp())

def square():
    turtle.pu()
    turtle.fill(True)
    for i in range(4):
        turtle.forward(15)
        turtle.right(90)
    turtle.fill(False)

print "Welcome to Turtle Racing : "
number_of_turtles = int(raw_input("How many turtles (between 3 and 6) : "))
bet_amount = int(raw_input("How much do you want to bet? $ "))
bet_turtle = raw_input("Which turtle (1 to 5)? ")

color_list=["red","blue","green","brown","yellow","purple"]
stamp_list=[]
draw_start()
draw_finish()
for i in range(number_of_turtles):
    stamp_turtle(-370,280-i*90,color_list[i])`

Body:
The answer is you don't move stamps, you move turtles!  Stamps have to be removed and restamped whereas turtles can move without redrawing:

import random
import turtle

STAMP_SIZE = 20
SQUARE_SIZE = 15
FINISH_LINE = 200
COLOR_LIST = ['red', 'blue', 'green', 'brown', 'yellow', 'purple']

def draw_start():
    turtle.speed('fastest')
    turtle.penup()
    turtle.setpos(-350, 300)
    turtle.pendown()
    turtle.right(90)
    turtle.forward(520)

def draw_finish():
    turtle.shape('square')
    turtle.shapesize(SQUARE_SIZE / STAMP_SIZE)
    turtle.penup()

    for i in range(18):
        turtle.setpos(FINISH_LINE, (300 - (i * SQUARE_SIZE * 2)))
        turtle.stamp()

    for j in range(18):
        turtle.setpos(FINISH_LINE + SQUARE_SIZE, ((300 - SQUARE_SIZE) - (j * SQUARE_SIZE  * 2)))
        turtle.stamp()

    turtle.hideturtle()

def move_turtle(who):
    who.forward(random.randint(1, 10))
    if who.xcor() < FINISH_LINE:
        turtle.ontimer(lambda who=who: move_turtle(who), 50)

print('Welcome to Turtle Racing!')
number_of_turtles = int(input('How many turtles (between 3 and 6): '))

draw_start()
draw_finish()

turtle_list = []

for idx in range(number_of_turtles):
    racer = turtle.Turtle('turtle', visible=False)
    racer.speed('fastest')  # affects drawing speed, not forward motion
    racer.penup()
    racer.setpos(-350 - STAMP_SIZE, 280 - idx * 90)
    racer.color(COLOR_LIST[idx])
    racer.showturtle()

    turtle_list.append(racer)

for racer in turtle_list:
    turtle.ontimer(lambda who=racer: move_turtle(who), 100)

turtle.exitonclick()

The place where stamping speeds things up is in making your finish line which takes much longer if you try to draw it.

Note that although your original code is Python 2, my answer is Python 3 so you may need to tweak a couple of things if you're still using the older version.


问:
Run PHP function without reloading doesnt work with AJAX
I know this question has been asked a lot, but I can't solve my problem.
I want to run the PHP function without reloading the page. Why does this not work? The php file is indexTest.php.

The page is just scrolling to the top and nothing works.

I am new to AJAX so I really dont know what to do.

HTML:

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

        function submitdata()
        {
         var nameForm=document.getElementById( "nameForm" );
         var emailForm=document.getElementById( "emailForm" );
         var messageForm=document.getElementById( "messageForm" );

         $.ajax({
          type: 'post',
          url: 'indexTest.php',
          data: {
           name:nameForm,
           email:emailForm,
           message:messageForm
          },
         });

         return false;
        }
</script>

<form onsubmit="return submitdata()" method="POST" id="contactForm">
                    <input spellcheck="false" class="first" type="text" name="name" placeholder="name" id="nameForm">
                    <input spellcheck="false" class="first" type="text" name="email" placeholder="email" id="emailForm">
                    <textarea rows="8" spellcheck="false" class="last" type="text" name="message" placeholder="message" id="messageForm"></textarea>
                    <input type="submit" name="submit" value="" id="button">
                </form>
</code>```

PHP:

```<code><?php
if(isset($_POST['submit'])){
    $to = "*"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo "Invalid email format";
    };

    $first_name = $_POST['name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = "Email from: " . $from . "\n\n" . $first_name .  " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender

    echo '<script language="javascript">';
    echo 'alert("message successfully sent")';
    echo '</script>';

    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }

?>
</code>```

答:
The problem is that you are posting through the form itself, when you actually want to post through AJAX. Essentially, because you are calling your JavaScript function in onsubmit, the JavaScript will get run in addition to the default form submission.

What you need to do is disable default form submission with e.preventDefault();, and then run your JavaScript instead:

```<code>$("#contactForm").submit(function(e) {
    e.preventDefault();
    submitdata();
});
</code>```

Hope this helps! :)

Body:
I know this question has been asked a lot, but I can't solve my problem.
I want to run the PHP function without reloading the page. Why does this not work? The php file is indexTest.php.

The page is just scrolling to the top and nothing works.

I am new to AJAX so I really dont know what to do.

HTML:

<form onsubmit="return submitdata()" method="POST" id="contactForm">
                    <input spellcheck="false" class="first" type="text" name="name" placeholder="name" id="nameForm">
                    <input spellcheck="false" class="first" type="text" name="email" placeholder="email" id="emailForm">
                    <textarea rows="8" spellcheck="false" class="last" type="text" name="message" placeholder="message" id="messageForm"></textarea>
                    <input type="submit" name="submit" value="" id="button">
                </form>

PHP:

<?php
if(isset($_POST['submit'])){
    $to = "*"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo "Invalid email format";
    };

    $first_name = $_POST['name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = "Email from: " . $from . "\n\n" . $first_name .  " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender

    echo '';

    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }

?>

Body:
The problem is that you are posting through the form itself, when you actually want to post through AJAX. Essentially, because you are calling your JavaScript function in onsubmit, the JavaScript will get run in addition to the default form submission.

What you need to do is disable default form submission with e.preventDefault();, and then run your JavaScript instead:

$("#contactForm").submit(function(e) {
    e.preventDefault();
    submitdata();
});

Hope this helps! :)


问:
WordPress Broken Images
I don't know what can cause this problem, but my WordPress web-site after migrating to new server is not showing me images. It is maybe something in .htaccess file, rewrite rule or something. Any directions please?

Please click here to see my page.
.htaccess from public_html directory:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

.htaccess file from wp-content/uploads:

```<code># BEGIN alti-watermark Plugin
<ifModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^(.*(-([1-3][\d]{1,2}|[\d]{1,2})x300|-300x([1-3][\d]{1,2}|[\d]{1,2})|-([1-1][\d]{1,3}|[\d]{1,3})x1024|-1024x([1-1][\d]{1,3}|[\d]{1,3})|-940x446)\.jpg|.*(?<!-\dx\d)(?<!-\d\dx\d)(?<!-\dx\d\d)(?<!-\d\dx\d\d)(?<!-\d\d\dx\d\d)(?<!-\d\dx\d\d\d)(?<!-\d\d\dx\d\d\d)(?<!-\d\d\d\dx\d\d\d)(?<!-\d\d\d\dx\d\d)(?<!-\d\d\dx\d\d\d\d)(?<!-\d\d\d\dx\d\d\d\d)(?<!-\d\d\d\dx\d\d\d)(?<!-\d\d\d\dx\d\d)(?<!-\d\d\d\d\dx\d\d\d\d\d)\.jpg){1}((\?|\&)([^\.\?\ ]+))*$ ../plugins/alti-watermark/public/views/alti-watermark-public-bridge.php?imageRequested=$1 [PT]
</ifModule>
# [date=2016-12-27 18:06.57] [php=5.4.45] [width=300x300|1024x1024|940x446|fullsize] [plugin_name=alti-watermark] [version=0.3]
# END alti-watermark Plugin
</code>```

Thanks in advance!

答:
Usually that's because file paths are saved as absolute paths in the database.

In this case you either need to get some plugin that changes all those filepaths for you (see https://wordpress.org/plugins/search/migration/ for resources) or export your database as a mysql file, open it in an editor and do a search/replace to replace all old filepath instances with the new one, and then import that again in your database.

Title: WordPress Broken Images

Body:
I don't know what can cause this problem, but my WordPress web-site after migrating to new server is not showing me images. It is maybe something in .htaccess file, rewrite rule or something. Any directions please?

Please click here to see my page.
.htaccess from public_html directory:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

.htaccess file from wp-content/uploads:

# BEGIN alti-watermark Plugin
<ifModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^(.*(-([1-3][\d]{1,2}|[\d]{1,2})x300|-300x([1-3][\d]{1,2}|[\d]{1,2})|-([1-1][\d]{1,3}|[\d]{1,3})x1024|-1024x([1-1][\d]{1,3}|[\d]{1,3})|-940x446)\.jpg|.*(?<!-\dx\d)(?<!-\d\dx\d)(?<!-\dx\d\d)(?<!-\d\dx\d\d)(?<!-\d\d\dx\d\d)(?<!-\d\dx\d\d\d)(?<!-\d\d\dx\d\d\d)(?<!-\d\d\d\dx\d\d\d)(?<!-\d\d\d\dx\d\d)(?<!-\d\d\dx\d\d\d\d)(?<!-\d\d\d\dx\d\d\d\d)(?<!-\d\d\d\dx\d\d\d)(?<!-\d\d\d\dx\d\d)(?<!-\d\d\d\d\dx\d\d\d\d\d)\.jpg){1}((\?|\&)([^\.\?\ ]+))*$ ../plugins/alti-watermark/public/views/alti-watermark-public-bridge.php?imageRequested=$1 [PT]
</ifModule>
# [date=2016-12-27 18:06.57] [php=5.4.45] [width=300x300|1024x1024|940x446|fullsize] [plugin_name=alti-watermark] [version=0.3]
# END alti-watermark Plugin

Thanks in advance!


问:
Why is boost::hana::experimental::types an experimental feature? what is tricky about a list of types?
I was looking into Hana and I was surprised to see that it has a concept of a type (a "container of types" of sort, something like a one-element tuple with no actual value), but types (a sequence of type) is an experimental feature.

Does anyone know why? What is complicated about a list of types as opposed to a container of a single type?

答:
The answer is basically what Jason said:

I'd like to see types as a hana::Sequence but it wouldn't pass the laws as it won't hold any kind of value (like values with run-time state).

The "problem" is that a hana::types could not be made a hana::Sequence, because a hana::Sequence is supposed to be able to hold arbitrary things, not only types. While this may not seem like a big deal, it actually is. For example, we would also not be able to satisfy hana::Monad, since that requires hana::flatten, whose signature is M<M<T>> -> M<T> for an arbitrary hana::Monad M. Since hana::types can only hold types, you could not have e.g. hana::types<hana::types<int, char>, hana::types<float, long>> without special-casing the whole thing.

Whatever the solution is, I'd like to find a solution that does not break the conceptual integrity of Hana, while still allowing for a more compile-time efficient type list.


问:
Android RunTime exception "Font asset not found" for .woff font files in android nougat
I am developing one application, where  I need to use .woff fonts. I have written the following code to get font type face from .woff file and set into textview.

```<code>     hellofont = getFont("fonts/AvenirLTStd-Black.woff");
    //welcomefont = getFont ( "fonts/AvenirLTStd-Heavy.woff");

    thankufont = getFont("fonts/RobotoCondensed-Bold.ttf");

    TextView text1 = (TextView) findViewById(R.id.text1id);
    text1.setTypeface(hellofont);

    TextView text2 = (TextView) findViewById(R.id.text2id);
    text2.setTypeface(thankufont);

public Typeface getFont( String fontName){
    try {
        Typeface content = Typeface.createFromAsset(this.getAssets(), fontName);
        return content;
    }

    catch(RuntimeException e)
    {
        Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
    }

    return  null;

}
</code>```

This code works fine on android 5.0 and 6.0 devices. But it is giving exception ( Font asset not found fonts/AvenirLTStd-Black.woff )on android 7.0 devices.
I have tested ttf and otf fonts on android 7.0 devices and it is working fine. Only woff fonts gives this exception.

I have attached the screen shot also which shows the fonts in assests/fonts folder. asset folder with woff fonts

Can anyone help me" what is the issue here?

Thanks in advance
Krishna

答: WOFF support in Android 7.0 and 7.1 appears to be at least partially broken, with such fonts being unloadable from package assets directories. Your best option, if you are supporting Nougat, is to get TTF or OTF versions of your fonts and use those instead.

Body:
I am developing one application, where  I need to use .woff fonts. I have written the following code to get font type face from .woff file and set into textview.

     hellofont = getFont("fonts/AvenirLTStd-Black.woff");
    //welcomefont = getFont ( "fonts/AvenirLTStd-Heavy.woff");

    thankufont = getFont("fonts/RobotoCondensed-Bold.ttf");

    TextView text1 = (TextView) findViewById(R.id.text1id);
    text1.setTypeface(hellofont);

    TextView text2 = (TextView) findViewById(R.id.text2id);
    text2.setTypeface(thankufont);

public Typeface getFont( String fontName){
    try {
        Typeface content = Typeface.createFromAsset(this.getAssets(), fontName);
        return content;
    }

    catch(RuntimeException e)
    {
        Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
    }

    return  null;

}

This code works fine on android 5.0 and 6.0 devices. But it is giving exception ( Font asset not found fonts/AvenirLTStd-Black.woff )on android 7.0 devices.
I have tested ttf and otf fonts on android 7.0 devices and it is working fine. Only woff fonts gives this exception.

I have attached the screen shot also which shows the fonts in assests/fonts folder. asset folder with woff fonts

Can anyone help me" what is the issue here?

Thanks in advance
Krishna


问:
SQL : Error converting data type nvarchar to float
I want to convert nvarchar data to float type.

In my case I have SalesValue column and I used this command

```<code>UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )
</code>```

My table has values like

```<code>201.01
40.50
215.12
550
304.201
</code>```

But I get an error

SQL : Error converting data type nvarchar to float.

How can I solve this problem ?

答:
It sounds like to me your data still has something that is non numerical. I'm hoping that your application side had done a pretty good job at cleaning your data before inputting and the problem is probably you have a '$' in one or more of your fields.
Cast will fail when you have a non numerical char other then '.' in it (as you probably know which is why you removed ',').
I ran the below script to test this.

```<code>declare @myFloat float;
declare @test1 nvarchar(10) = '145.88';
declare @test2 nvarchar(10) = '4,145.88';
declare @test3 nvarchar(10) = '$4,145.88';

SELECT ISNUMERIC(@TEST3)
set @myFloat = CONVERT(FLOAT, REPLACE(@test1,',','') );
select @myFloat;

set @myFloat = CONVERT(FLOAT, REPLACE(@test2,',','') );
select @myFloat;

--THIS WILL FAIL
set @myFloat = CONVERT(FLOAT, REPLACE(@test3,',','') );
select @myFloat;
--THIS WILL NOT FAIL
set @myFloat = CONVERT(FLOAT, REPLACE(REPLACE(@test3,',',''),'$','') );
select @myFloat;
</code>```

You can try running the below script on the column in question to see which columns you are having a problem with:

```<code>--run this on your table
SELECT SalesValue
FROM Overseas
WHERE ISNUMERIC(REPLACE(SalesValue,',','')) = 0

--test sample
/*
insert into #myTable
values ('145.88'),
       ('4,145.88'),
       ('$4,145.88'),
       ('$4,145.88%');

SELECT *
FROM #myTable
WHERE ISNUMERIC(REPLACE(amounts,',','')) = 0
--WHERE ISNUMERIC(REPLACE(REPLACE(amounts,',',''),'$','')) = 0 --this will remove results with $ also
*/
</code>```

So your fix will be to simply change the line you provided to:

```<code>UPDATE Overseas SET SalesValue = CONVERT(FLOAT, REPLACE(REPLACE([SalesValue],',',''),'$','') )
</code>```

Unless you found other chars in the results of prior script.

Body:
I want to convert nvarchar data to float type.

In my case I have SalesValue column and I used this command

UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )

My table has values like

201.01
40.50
215.12
550
304.201

But I get an error

SQL : Error converting data type nvarchar to float.

How can I solve this problem ?

Body:
It sounds like to me your data still has something that is non numerical. I'm hoping that your application side had done a pretty good job at cleaning your data before inputting and the problem is probably you have a '$' in one or more of your fields.
Cast will fail when you have a non numerical char other then '.' in it (as you probably know which is why you removed ',').
I ran the below script to test this.

declare @myFloat float;
declare @test1 nvarchar(10) = '145.88';
declare @test2 nvarchar(10) = '4,145.88';
declare @test3 nvarchar(10) = '$4,145.88';

SELECT ISNUMERIC(@TEST3)
set @myFloat = CONVERT(FLOAT, REPLACE(@test1,',','') );
select @myFloat;

set @myFloat = CONVERT(FLOAT, REPLACE(@test2,',','') );
select @myFloat;

--THIS WILL FAIL
set @myFloat = CONVERT(FLOAT, REPLACE(@test3,',','') );
select @myFloat;
--THIS WILL NOT FAIL
set @myFloat = CONVERT(FLOAT, REPLACE(REPLACE(@test3,',',''),'$','') );
select @myFloat;

You can try running the below script on the column in question to see which columns you are having a problem with:

--run this on your table
SELECT SalesValue
FROM Overseas
WHERE ISNUMERIC(REPLACE(SalesValue,',','')) = 0

--test sample
/*
insert into #myTable
values ('145.88'),
       ('4,145.88'),
       ('$4,145.88'),
       ('$4,145.88%');

SELECT *
FROM #myTable
WHERE ISNUMERIC(REPLACE(amounts,',','')) = 0
--WHERE ISNUMERIC(REPLACE(REPLACE(amounts,',',''),'$','')) = 0 --this will remove results with $ also
*/

So your fix will be to simply change the line you provided to:

UPDATE Overseas SET SalesValue = CONVERT(FLOAT, REPLACE(REPLACE([SalesValue],',',''),'$','') )

Unless you found other chars in the results of prior script.


问:
How to Subtracting 7hrs from a String time?
I need to convert time from GMT to PST and for that I am trying to subtract 7 hrs from the time. The issue is that the time is stored in a String and I am not sure how can I subtract 7 hrs from a String time. displayDateString gives me the date and time and it is a String. I am trying the following approach but it is not working the way I need it.

Before Code Change

```<code> public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);
    DateFormat pstFormat = new SimpleDateFormat();
    return displayDateString;
}
</code>```

above code outputs: 06/02/17 07:19 PM

After Code Change

```<code>public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);

    DateFormat pstFormat = new SimpleDateFormat();
    /*TimeZone pstZone = TimeZone.getTimeZone( "PST" );
    pstFormat.setTimeZone( pstZone );
    displayDateString = pstFormat.format(date);*/

    Calendar cal = Calendar.getInstance();
    cal = Calendar.getInstance();
    cal.add( Calendar.HOUR, -7 );
    displayDateString = pstFormat.format( cal.getTime() );
    return displayDateString;
}

public static Date convertStringToDate(String strDate, String inputFormat) {
    SimpleDateFormat dateFormat = null;
    Date date = null;
    boolean formatChagned = false;
    try {
        if(!StringUtils.isSet(strDate)){
            return date;
        }
        if(strDate.indexOf("/")>0 && inputFormat.indexOf("-")>=0){
            inputFormat = inputFormat.replaceAll("-", "/");
            formatChagned=true;
        }else if (strDate.indexOf("-")>0 && inputFormat.indexOf("/")>=0){
            inputFormat = inputFormat.replaceAll("/", "-");
            formatChagned=true;
        }

        dateFormat = new SimpleDateFormat(inputFormat);
        dateFormat.setLenient(false);
        date = dateFormat.parse(strDate);
    } catch (Exception exception) {
        log.error("Given date to parse:"+strDate);
        log.error("Given Input Date Format:"+inputFormat);

        if(formatChagned){
            log.error("Given Input Date Format is incorrcet and it is modified as :"+inputFormat);
        }

        log.error(exception);
        log.error("DateUtil.convertStringToDate :Parse exception while parsing,"+strDate+" using format :"+inputFormat);
        date = null;
    }
    return date;
}
</code>```

I added the calendar part to somehow subtract 7hrs from the existing time. This doesn't work.

答:
You may change as following

```<code>Calendar cal = Calendar.getInstance();
cal.setTime(new Date(displayDateString));
cal.add(Calendar.HOUR, -7);
</code>```

Though new Date(displayDateString) is deprecated function

Body:
I need to convert time from GMT to PST and for that I am trying to subtract 7 hrs from the time. The issue is that the time is stored in a String and I am not sure how can I subtract 7 hrs from a String time. displayDateString gives me the date and time and it is a String. I am trying the following approach but it is not working the way I need it.

Before Code Change

 public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);
    DateFormat pstFormat = new SimpleDateFormat();
    return displayDateString;
}

above code outputs: 06/02/17 07:19 PM

After Code Change

public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);

    DateFormat pstFormat = new SimpleDateFormat();
    /*TimeZone pstZone = TimeZone.getTimeZone( "PST" );
    pstFormat.setTimeZone( pstZone );
    displayDateString = pstFormat.format(date);*/

    Calendar cal = Calendar.getInstance();
    cal = Calendar.getInstance();
    cal.add( Calendar.HOUR, -7 );
    displayDateString = pstFormat.format( cal.getTime() );
    return displayDateString;
}

public static Date convertStringToDate(String strDate, String inputFormat) {
    SimpleDateFormat dateFormat = null;
    Date date = null;
    boolean formatChagned = false;
    try {
        if(!StringUtils.isSet(strDate)){
            return date;
        }
        if(strDate.indexOf("/")>0 && inputFormat.indexOf("-")>=0){
            inputFormat = inputFormat.replaceAll("-", "/");
            formatChagned=true;
        }else if (strDate.indexOf("-")>0 && inputFormat.indexOf("/")>=0){
            inputFormat = inputFormat.replaceAll("/", "-");
            formatChagned=true;
        }

        dateFormat = new SimpleDateFormat(inputFormat);
        dateFormat.setLenient(false);
        date = dateFormat.parse(strDate);
    } catch (Exception exception) {
        log.error("Given date to parse:"+strDate);
        log.error("Given Input Date Format:"+inputFormat);

        if(formatChagned){
            log.error("Given Input Date Format is incorrcet and it is modified as :"+inputFormat);
        }

        log.error(exception);
        log.error("DateUtil.convertStringToDate :Parse exception while parsing,"+strDate+" using format :"+inputFormat);
        date = null;
    }
    return date;
}

I added the calendar part to somehow subtract 7hrs from the existing time. This doesn't work.

Body:
You may change as following

Calendar cal = Calendar.getInstance();
cal.setTime(new Date(displayDateString));
cal.add(Calendar.HOUR, -7);

Though new Date(displayDateString) is deprecated function