问:
<EDITED> Python 2.7 tkinter (and IDLE) "problems"
I got some tkinter-based problems when I used the Python IDLE.

First, IDLE couldn't be opened in my computer

I use Python 2.7.12.

After openning IDLE through the windows command line, I've found where the problem is.

It's in Tkinter:

```<code>###C:\Python27\Lib\lib-tk\Tkinter.py
##Line:80
value = unicode(value, 'utf-8')
</code>```

This failed with:

```<code>Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 80, in _stringify
    value = unicode(value, 'utf-8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb2 in position 0: invalid start byte
</code>```

So I changed it to:

```<code>###C:\Python27\Lib\lib-tk\Tkinter.py
##Line:80
value = unicode(value, 'cp950')
</code>```

Then it works fine now, but does everyone have to modify their IDLE before using it?

Is this kind of a bug?

Second, my friend couldn't change IDLE's font size

Here is my debug note:

```<code>    ###C:\Python27\Lib\idlelib\idle.py
##Ln:10
import idlelib.PyShell
idlelib.PyShell.main()

###C:\Python27\Lib\idlelib\PyShell.py
##Ln:1475
def main():
    global flist, root, use_subprocess
##Ln:1552 in function main
    # start editor and/or shell windows:
    root = Tk(className="Idle")
    root.withdraw()
##Ln:1570 in function main
    flist = PyShellFileList(root)
##Ln:312
class PyShellFileList(FileList):
    "Extend base class: IDLE supports a shell and breakpoints"

    # override FileList's class variable, instances return PyShellEditorWindow
    # instead of EditorWindow when new edit windows are created.
    EditorWindow = PyShellEditorWindow

###C:\Python27\Lib\idlelib\FileList.py
##Ln:6
class FileList:

    # N.B. this import overridden in PyShellFileList.
    from idlelib.EditorWindow import EditorWindow

###C:\Python27\Lib\idlelib\PyShell.py
##Ln:125
class PyShellEditorWindow(EditorWindow):
    "Regular text edit window in IDLE, supports breakpoints"

    def __init__(self, *args):
        self.breakpoints = []
        EditorWindow.__init__(self, *args)

###C:\Python27\Lib\idlelib\PyShell.py
##Ln:262 in class EditorWindow
    text['font'] = idleConf.GetFont(self.root, 'main', 'EditorWindow')

###C:\Python27\Lib\idlelib\configHandler.py
##Ln:700 in class IdleConf
    def GetFont(self, root, configType, section):
        """Retrieve a font from configuration (font, font-size, font-bold)
        Intercept the special value 'TkFixedFont' and substitute
        the actual font, factoring in some tweaks if needed for
        appearance sakes.

        The 'root' parameter can normally be any valid Tkinter widget.

        Return a tuple (family, size, weight) suitable for passing
        to tkinter.Font
        """
        family = self.GetOption(configType, section, 'font', default='courier')
        size = self.GetOption(configType, section, 'font-size', type='int',
                              default='10')
        bold = self.GetOption(configType, section, 'font-bold', default=0,
                              type='bool')
        if (family == 'TkFixedFont'):
            if TkVersion < 8.5:
                family = 'Courier'
            else:
                f = Font(name='TkFixedFont', exists=True, root=root)
                actualFont = Font.actual(f)
                family = actualFont['family']
                size = actualFont['size']
                if size <= 0:
                    size = 10  # if font in pixels, ignore actual size
                bold = actualFont['weight']=='bold'
        return (family, size, 'bold' if bold else 'normal')

###C:\Python27\Lib\lib-tk\tkFont.py
##Ln:66 in class Font
    def __init__(self, root=None, font=None, name=None, exists=False, **options):
        if not root:
            root = Tkinter._default_root
        tk = getattr(root, 'tk', root)
##Ln:92 in class Font in method __init__
        self._split = tk.splitlist
        self._call  = tk.call
##Ln:120 in class Font
    def actual(self, option=None):
        "Return actual font attributes"
        if option:
            return self._call("font", "actual", self.name, "-"+option)
        else:
            return self._mkdict(
                self._split(self._call("font", "actual", self.name))
                )
##Ln:60 in class Font
    def _mkdict(self, args):
        options = {}
        for i in range(0, len(args), 2):
            options[args[i][1:]] = args[i+1]
        return options
</code>```

So the problem is Tkinter ...again. I ran a small test:

```<code>import Tkinter
root=Tkinter.Tk()
def _mkdict(args):
    options = {}
    for i in range(0, len(args), 2):
        options[args[i][1:]] = args[i+1]
    return options
resulta=_mkdict(root.tk.splitlist(root.tk.call("font","actual","TkFixedFont")))
print "a",resulta
resultb=_mkdict(root.tk.splitlist(root.tk.call("font","actual","細明體")))
print "b",resultb
</code>```

Then I got:

```<code>a {'family': u'\u7d30\u660e\u9ad4', 'weight': 'normal', 'slant': 'roman', 'overstrike': 0, 'underline': 0, 'size': 10}
b {'family': u'\u65b0\u7d30\u660e\u9ad4', 'weight': 'normal', 'slant': 'roman', 'overstrike': 0, 'underline': 0, 'size': 15}
</code>```

So the problem is in tkFont.Font's actual module? Or...?

Edit

Maybe I didn't describe the second "problem" very well, maybe I gave too much details, so here's the core of the second problem:

```<code>###C:\Python27\Lib\idlelib\configHandler.py
##Ln:700 in class IdleConf
def GetFont(self, root, configType, section):
    """Retrieve a font from configuration (font, font-size, font-bold)
    Intercept the special value 'TkFixedFont' and substitute
    the actual font, factoring in some tweaks if needed for
    appearance sakes.

    The 'root' parameter can normally be any valid Tkinter widget.

    Return a tuple (family, size, weight) suitable for passing
    to tkinter.Font
    """
    family = self.GetOption(configType, section, 'font', default='courier')
    size = self.GetOption(configType, section, 'font-size', type='int',
                          default='10')
    bold = self.GetOption(configType, section, 'font-bold', default=0,
                          type='bool')
    if (family == 'TkFixedFont'):
        if TkVersion < 8.5:
            family = 'Courier'
        else:
            f = Font(name='TkFixedFont', exists=True, root=root)
            actualFont = Font.actual(f)
            family = actualFont['family']
            size = actualFont['size']
            if size <= 0:
                size = 10  # if font in pixels, ignore actual size
            bold = actualFont['weight']=='bold'
    return (family, size, 'bold' if bold else 'normal')
</code>```

If the font family is not "TkFixedFont", getFont will return the right size, which is configured by user at the "configure IDLE" panel.

But if the font family is "TkFixedFont", it'll ignore user's setting and use "actualFont['size']", which is 10, as I tested.

答:
As to the second issue, which I believe is unrelated to the first.  I don't really understand the question or the point of the code quotations.

IDLE has an Option settings dialog accessed through the menu.  The initial (and default) tab has a font size setting which has always worked for me (on Windows).  The answer to 'How to change fontsize?' is to use the intended font size change widget.

I just rechecked with 2.7.13 and it still works for me.  There was a bug in 2.7.11 that manifested as an inability to open the dialog on some Linux systems.  But that was fixed in 2.7.12.  I checked the 2.7.13 patch list and none should have affected font sizing.  Still, as far as IDLE goes, I would recommend upgrading.

Body:
I got some tkinter-based problems when I used the Python IDLE.

First, IDLE couldn't be opened in my computer

I use Python 2.7.12.

After openning IDLE through the windows command line, I've found where the problem is.

It's in Tkinter:

###C:\Python27\Lib\lib-tk\Tkinter.py
##Line:80
value = unicode(value, 'utf-8')

This failed with:

Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 80, in _stringify
    value = unicode(value, 'utf-8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb2 in position 0: invalid start byte

So I changed it to:

###C:\Python27\Lib\lib-tk\Tkinter.py
##Line:80
value = unicode(value, 'cp950')

Then it works fine now, but does everyone have to modify their IDLE before using it?

Is this kind of a bug?

Second, my friend couldn't change IDLE's font size

Here is my debug note:

    ###C:\Python27\Lib\idlelib\idle.py
##Ln:10
import idlelib.PyShell
idlelib.PyShell.main()

###C:\Python27\Lib\idlelib\PyShell.py
##Ln:1475
def main():
    global flist, root, use_subprocess
##Ln:1552 in function main
    # start editor and/or shell windows:
    root = Tk(className="Idle")
    root.withdraw()
##Ln:1570 in function main
    flist = PyShellFileList(root)
##Ln:312
class PyShellFileList(FileList):
    "Extend base class: IDLE supports a shell and breakpoints"

    # override FileList's class variable, instances return PyShellEditorWindow
    # instead of EditorWindow when new edit windows are created.
    EditorWindow = PyShellEditorWindow

###C:\Python27\Lib\idlelib\FileList.py
##Ln:6
class FileList:

    # N.B. this import overridden in PyShellFileList.
    from idlelib.EditorWindow import EditorWindow

###C:\Python27\Lib\idlelib\PyShell.py
##Ln:125
class PyShellEditorWindow(EditorWindow):
    "Regular text edit window in IDLE, supports breakpoints"

    def __init__(self, *args):
        self.breakpoints = []
        EditorWindow.__init__(self, *args)

###C:\Python27\Lib\idlelib\PyShell.py
##Ln:262 in class EditorWindow
    text['font'] = idleConf.GetFont(self.root, 'main', 'EditorWindow')

###C:\Python27\Lib\idlelib\configHandler.py
##Ln:700 in class IdleConf
    def GetFont(self, root, configType, section):
        """Retrieve a font from configuration (font, font-size, font-bold)
        Intercept the special value 'TkFixedFont' and substitute
        the actual font, factoring in some tweaks if needed for
        appearance sakes.

        The 'root' parameter can normally be any valid Tkinter widget.

        Return a tuple (family, size, weight) suitable for passing
        to tkinter.Font
        """
        family = self.GetOption(configType, section, 'font', default='courier')
        size = self.GetOption(configType, section, 'font-size', type='int',
                              default='10')
        bold = self.GetOption(configType, section, 'font-bold', default=0,
                              type='bool')
        if (family == 'TkFixedFont'):
            if TkVersion < 8.5:
                family = 'Courier'
            else:
                f = Font(name='TkFixedFont', exists=True, root=root)
                actualFont = Font.actual(f)
                family = actualFont['family']
                size = actualFont['size']
                if size <= 0:
                    size = 10  # if font in pixels, ignore actual size
                bold = actualFont['weight']=='bold'
        return (family, size, 'bold' if bold else 'normal')

###C:\Python27\Lib\lib-tk\tkFont.py
##Ln:66 in class Font
    def __init__(self, root=None, font=None, name=None, exists=False, **options):
        if not root:
            root = Tkinter._default_root
        tk = getattr(root, 'tk', root)
##Ln:92 in class Font in method __init__
        self._split = tk.splitlist
        self._call  = tk.call
##Ln:120 in class Font
    def actual(self, option=None):
        "Return actual font attributes"
        if option:
            return self._call("font", "actual", self.name, "-"+option)
        else:
            return self._mkdict(
                self._split(self._call("font", "actual", self.name))
                )
##Ln:60 in class Font
    def _mkdict(self, args):
        options = {}
        for i in range(0, len(args), 2):
            options[args[i][1:]] = args[i+1]
        return options

So the problem is Tkinter ...again. I ran a small test:

import Tkinter
root=Tkinter.Tk()
def _mkdict(args):
    options = {}
    for i in range(0, len(args), 2):
        options[args[i][1:]] = args[i+1]
    return options
resulta=_mkdict(root.tk.splitlist(root.tk.call("font","actual","TkFixedFont")))
print "a",resulta
resultb=_mkdict(root.tk.splitlist(root.tk.call("font","actual","細明體")))
print "b",resultb

Then I got:

a {'family': u'\u7d30\u660e\u9ad4', 'weight': 'normal', 'slant': 'roman', 'overstrike': 0, 'underline': 0, 'size': 10}
b {'family': u'\u65b0\u7d30\u660e\u9ad4', 'weight': 'normal', 'slant': 'roman', 'overstrike': 0, 'underline': 0, 'size': 15}

So the problem is in tkFont.Font's actual module? Or...?

Edit

Maybe I didn't describe the second "problem" very well, maybe I gave too much details, so here's the core of the second problem:

###C:\Python27\Lib\idlelib\configHandler.py
##Ln:700 in class IdleConf
def GetFont(self, root, configType, section):
    """Retrieve a font from configuration (font, font-size, font-bold)
    Intercept the special value 'TkFixedFont' and substitute
    the actual font, factoring in some tweaks if needed for
    appearance sakes.

    The 'root' parameter can normally be any valid Tkinter widget.

    Return a tuple (family, size, weight) suitable for passing
    to tkinter.Font
    """
    family = self.GetOption(configType, section, 'font', default='courier')
    size = self.GetOption(configType, section, 'font-size', type='int',
                          default='10')
    bold = self.GetOption(configType, section, 'font-bold', default=0,
                          type='bool')
    if (family == 'TkFixedFont'):
        if TkVersion < 8.5:
            family = 'Courier'
        else:
            f = Font(name='TkFixedFont', exists=True, root=root)
            actualFont = Font.actual(f)
            family = actualFont['family']
            size = actualFont['size']
            if size <= 0:
                size = 10  # if font in pixels, ignore actual size
            bold = actualFont['weight']=='bold'
    return (family, size, 'bold' if bold else 'normal')

If the font family is not "TkFixedFont", getFont will return the right size, which is configured by user at the "configure IDLE" panel.

But if the font family is "TkFixedFont", it'll ignore user's setting and use "actualFont['size']", which is 10, as I tested.


来源: stackexchange

问:
I am Not Able to run my Maven Project
I am not able to run my Maven Project as it show the error as "Server Tomcat v8.5 Server at localhost failed to start." as shown in below diagram

My pom.xml file is :

and my web.xml file is

and my project structure is

i did all the steps for maven projects from the refered site http://crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ and i got my maven build as success but not able to run a project as it shows error in console as

```<code>SEVERE: The required Server component failed to start so Tomcat is unable to start.
</code>```

i tried , but still it coming as error..
Kindly help  me to rectify this
Thank You

答:
I guess you need to increase the Timeout of the Tomcat server, by default it times out after 45 seconds.

The Dependencies are taking time to load [more than 45 sec] and the server is timing out

ContentLicense: CC BY-SA 3.0

Title: I am Not Able to run my Maven Project

Body:
I am not able to run my Maven Project as it show the error as "Server Tomcat v8.5 Server at localhost failed to start." as shown in below diagram

My pom.xml file is :

and my web.xml file is

and my project structure is

i did all the steps for maven projects from the refered site http://crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ and i got my maven build as success but not able to run a project as it shows error in console as

SEVERE: The required Server component failed to start so Tomcat is unable to start.

i tried , but still it coming as error..
Kindly help  me to rectify this
Thank You


问:
Mouse right click on Firefox triggers click event
I noticed that the mouse right click on Firefox triggers an addEventListener.

I tried this code on more browsers and more OS (IE 11-10-9, Safari, Chrome) and by pressing the mouse right click, only on Firefox the console.log message is always printed.

```<code><div id="one-div" style="height:400px;width:500px;background-color:#000;"> click me </div>
<script>
    function cb(event, from){
        // if click is fired on <div> with:
        // left click, both EventListener will be printed.
        // right click, only the 'document' one will be printed.
        event.preventDefault();
        console.log(event + ' from: ' + from );
    }
    document.addEventListener('click', function(e){
        cb(e,'document');
    }, false);
    document.getElementById("one-div").addEventListener('click', function(e){
        cb(e,'one-div');
    }, false);
</script>
</code>```

And also I noticed that, when the click is fired into the div, it triggers the document.addEventListener only.
I searched on Firefox changelog but no news about this.

Can anyone explain this behavior?
Thanks!

答:
By default, in all browsers right click event is captured by
addEventListener('contextmenu'), otherwise a right click will open a window with some options (each browser has different one).

In Firefox, when you add addEventListener('click') to the document object, it will capture any mouse clicking events (left, right, wheel) on the document and it will disable this right click behavior.

In addition, this is what Mozilla documentation says in Mouse Events section, although the (ANY button) stuff is not activated until you add the listener to the document object

click:  A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.

*Note: still the above window is shown when you double click right mouse button, but not with a single click.

ContentLicense: CC BY-SA 4.0

Body:
I noticed that the mouse right click on Firefox triggers an addEventListener.

I tried this code on more browsers and more OS (IE 11-10-9, Safari, Chrome) and by pressing the mouse right click, only on Firefox the console.log message is always printed.

 click me

And also I noticed that, when the click is fired into the div, it triggers the document.addEventListener only.
I searched on Firefox changelog but no news about this.

Can anyone explain this behavior?
Thanks!


问:
Auto remove class seconds after it becomes active
I have a script working so that the background image of a div switches at a certain distance from the top of the page. What I want is for it to switch back to the original after say 2 seconds.

The following removes the class 170px later:

```<code><script>
jQuery(document).scroll(function(){
var fromTopPx = 2800; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#image').addClass('scrolled');
}else{
    jQuery('#image').removeClass('scrolled');
}
var fromTopPx = 2970; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#image').removeClass('scrolled');
}
});
</script>
</code>```

but I was hoping for it to switch back automatically:

```<code><script>
jQuery(document).scroll(function(){
var fromTopPx = 2800; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#neediioneimg').addClass('scrolled');
}else{
    jQuery('#neediioneimg').removeClass('scrolled');
}
setTimeout(function(){
$('.scrolled').removeClass('scrolled');
},2000);
});
</script>
</code>```

I'm not sure about the setTimout part, does anyone have an idea?

答:
Here is what you are wanting, now with fiddle example

```<code>var fromTopPx = 2800; // distance to trigger
var hasTriggered = false;

jQuery(document).scroll(function(){
    var scrolledFromtop = jQuery(window).scrollTop();

    if((scrolledFromtop > fromTopPx) && !hasTriggered ){
        hasTriggered = true;
        jQuery('#neediioneimg').addClass('scrolled');

        setTimeout(function(){
            $('.scrolled').removeClass('scrolled');
        },2000);
    }
});
</code>```

edit: forgot to set flag to true once fired

Body:
I have a script working so that the background image of a div switches at a certain distance from the top of the page. What I want is for it to switch back to the original after say 2 seconds.

The following removes the class 170px later:

but I was hoping for it to switch back automatically:

I'm not sure about the setTimout part, does anyone have an idea?

Body:
Here is what you are wanting, now with fiddle example

var fromTopPx = 2800; // distance to trigger
var hasTriggered = false;

jQuery(document).scroll(function(){
    var scrolledFromtop = jQuery(window).scrollTop();

    if((scrolledFromtop > fromTopPx) && !hasTriggered ){
        hasTriggered = true;
        jQuery('#neediioneimg').addClass('scrolled');

        setTimeout(function(){
            $('.scrolled').removeClass('scrolled');
        },2000);
    }
});

edit: forgot to set flag to true once fired


问:
Get number before a specified string
Given the string

```<code>RAM Statistics: 5954 / 8174 743=InUse 746=Peak
</code>```

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"
</code>```

But that's returning nothing.

UPDATE:
Per Joshua I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"
</code>```

And both $matches[0] and [1] return everything before the =Peak. So

```<code>Statistics:     5954 /     8174       743=InUse      746!
</code>```

答:
Another answer with a more complex RegEx with named groups which works on regex101.com but fails with the script. I guess due to differences in the RegEx implementation.

```<code>$string = @'
RAM Statistics:     1954 /     8174       743=InUse      746=Peak
RAM Statistics:     2954 /     8174       746=Peak
RAM Statistics:     3954 /     8174       743=InUse
RAM Statistics:     4954 /     8174
'@

$Pattern = '(?sm)^RAM Statistics: *(?<Ram>\d+) *\/ *(?<Ratio>\d+)( *(?<InUse>\d+)=InUse)?( *(?<Peak>\d+)=Peak)?'

$string.split('`n') |ForEach{
  $_ -match $Pattern|out-null
  "RAM {0}/{1}  {2} InUse  {3} Peak" -f $Matches.Ram,$Matches.Ratio,$Matches.InUse,$Matches.Peak
}
</code>```

```<code>RAM 1954/8174   InUse   Peak
RAM 2954/8174   InUse  746 Peak
RAM 4954/8174   InUse   Peak
</code>```

Title: Get number before a specified string

Body:
Given the string

RAM Statistics: 5954 / 8174 743=InUse 746=Peak

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"

But that's returning nothing.

UPDATE:
Per Joshua I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"

And both $matches[0] and [1] return everything before the =Peak. So

Statistics:     5954 /     8174       743=InUse      746!

Body:
Another answer with a more complex RegEx with named groups which works on regex101.com but fails with the script. I guess due to differences in the RegEx implementation.

$string = @'
RAM Statistics:     1954 /     8174       743=InUse      746=Peak
RAM Statistics:     2954 /     8174       746=Peak
RAM Statistics:     3954 /     8174       743=InUse
RAM Statistics:     4954 /     8174
'@

$Pattern = '(?sm)^RAM Statistics: *(?<Ram>\d+) *\/ *(?<Ratio>\d+)( *(?<InUse>\d+)=InUse)?( *(?<Peak>\d+)=Peak)?'

$string.split('`n') |ForEach{
  $_ -match $Pattern|out-null
  "RAM {0}/{1}  {2} InUse  {3} Peak" -f $Matches.Ram,$Matches.Ratio,$Matches.InUse,$Matches.Peak
}

RAM 1954/8174   InUse   Peak
RAM 2954/8174   InUse  746 Peak
RAM 4954/8174   InUse   Peak


问:
Xilinx VHDL latch warning troubleshooting
Xilinx is inferring a latch for a VHDL code i've written. I've looked up the possible causes for this and found that it's often due to incomplete if or case statements. I've gone through and made sure to include else and when others statements, but i'm still receiving the warning. I believe this is also affecting another project i'm working on so i'd like to understand why this is the case.

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity state_machine is
    port(trig, en: in std_logic; cstate,nstate: out std_logic_vector(0 to 2));
end state_machine;

architecture Behavioral of state_machine is
signal cstate_s,nstate_s: std_logic_vector(0 to 2);

begin
cstate <= cstate_s;
nstate <= nstate_s;

process(en, cstate_s)
begin
    if en = '1' then
        nstate_s <= "111";
        if cstate_s = "111" then
            nstate_s <= "011";
        elsif cstate_s = "011" then
            nstate_s <= "100";
        elsif cstate_s = "100" then
            nstate_s <= "101";
        elsif cstate_s = "101" then
            nstate_s <= "110";
        elsif cstate_s = "110" then
            nstate_s <= "111";
        else
            null;
        end if;
    else
        null;
    end if;
end process;

process(trig, nstate_s)
begin
    if rising_edge(trig) then
        cstate_s <= nstate_s;
    else
        null;
    end if;
end process;

end Behavioral;
</code>```

WARNING:Xst:737 - Found 3-bit latch for signal . Latches may
  be generated from incomplete case or if statements. We do not
  recommend the use of latches in FPGA/CPLD designs, as they may lead to
  timing problems.

答:
For there to be no latches synthesised when a combinational process is synthesised, there must be no path between begin and end process; where all the outputs of the process are not assigned. This is called complete assignment. An output of the process is any signal assigned anywhere within it.

You have such paths. When any path with your null statements are executed, the output of your first process (nstate_s) is not assigned to. Therefore, you will get latches synthesised. There is no point in just having a null statement. If you genuinely don't care what value is assigned to your outputs in these paths, assign the outputs to '-', which means don't care in VHDL.

By the way (assuming trig is a clock), your second process is not combinational (it is sequential) and so you don't need to obey complete assignment; your else branch is unnecessary.

Body:
Xilinx is inferring a latch for a VHDL code i've written. I've looked up the possible causes for this and found that it's often due to incomplete if or case statements. I've gone through and made sure to include else and when others statements, but i'm still receiving the warning. I believe this is also affecting another project i'm working on so i'd like to understand why this is the case.

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity state_machine is
    port(trig, en: in std_logic; cstate,nstate: out std_logic_vector(0 to 2));
end state_machine;

architecture Behavioral of state_machine is
signal cstate_s,nstate_s: std_logic_vector(0 to 2);

begin
cstate <= cstate_s;
nstate <= nstate_s;

process(en, cstate_s)
begin
    if en = '1' then
        nstate_s <= "111";
        if cstate_s = "111" then
            nstate_s <= "011";
        elsif cstate_s = "011" then
            nstate_s <= "100";
        elsif cstate_s = "100" then
            nstate_s <= "101";
        elsif cstate_s = "101" then
            nstate_s <= "110";
        elsif cstate_s = "110" then
            nstate_s <= "111";
        else
            null;
        end if;
    else
        null;
    end if;
end process;

process(trig, nstate_s)
begin
    if rising_edge(trig) then
        cstate_s <= nstate_s;
    else
        null;
    end if;
end process;

end Behavioral;

WARNING:Xst:737 - Found 3-bit latch for signal . Latches may
  be generated from incomplete case or if statements. We do not
  recommend the use of latches in FPGA/CPLD designs, as they may lead to
  timing problems.


问:
jenkins complicated buildflow, is it possible?

I would like to have a Jenkins build flow that looks like this.

After the build is triggered all slaves run the same job in parallel (a setup job).

If any slaves fail this job they should not continue on.

For the all the slaves that to pass that job, they should grab a job out of a pool of jobs that need to be completed. And once a slave completes a job they should go back to complete another job in the pool.

I have only started working with Jenkins a few weeks ago and they way I have it setup now is as each job is picked up by a slave they have to run the setup job first. This really slows down build times because I have about 30 jobs and the setup takes ~2 minutes.

I am using Jenkins as an automated testing platform and all the jobs in the job pool can run independently of each other. I have 5 slaves currently and ~30 jobs.

答:
The following should do the trick:

```<code>def jobPool = new ArrayDeque()
jobPool.add({
    echo "Doing stuff on ${env.NODE_NAME}"
});
jobPool.add({
    echo "Doing other stuff on ${env.NODE_NAME}, a little slower"
    sleep 4
});
jobPool.add({
    echo "Doing more stuff on ${env.NODE_NAME}, even slower"
    sleep 10
});
jobPool.add({
    echo "Doing stuff quick on ${env.NODE_NAME}"
});
jobPool.add({
    echo "Doing stuff quicker on ${env.NODE_NAME}"
});

def par = [:]

for (x in ["master", "urban"]) {
    def nodeName = x; // needed due to variable scoping
    par[nodeName] = {
        node (nodeName) {
            try {
               echo "Doing setup on ${env.NODE_NAME}!"
               // Do you're setup
               echo "Done with setup"
            } catch (Exception e) {
               echo "Will not use this node as it failed setup!"
               return;
            }
            while (true) {
               // echo "${jobPool.size()}"
                def subTask = jobPool.poll()
                //echo "${jobPool.size()} ${subTask}"
                if (subTask == null) {
                    break;
                }
                // Might wan't try catch around the next line if you wan't to continue if a job fails
                subTask()
            }
        }
    }
}
parallel par
if (!jobPool.isEmpty()) {
  error "Not all tasks was done!"
}
</code>```

Simply add your "job pool jobs" to the jobPool variable and modify the setup part.

Body:
The following should do the trick:

def jobPool = new ArrayDeque()
jobPool.add({
    echo "Doing stuff on ${env.NODE_NAME}"
});
jobPool.add({
    echo "Doing other stuff on ${env.NODE_NAME}, a little slower"
    sleep 4
});
jobPool.add({
    echo "Doing more stuff on ${env.NODE_NAME}, even slower"
    sleep 10
});
jobPool.add({
    echo "Doing stuff quick on ${env.NODE_NAME}"
});
jobPool.add({
    echo "Doing stuff quicker on ${env.NODE_NAME}"
});

def par = [:]

for (x in ["master", "urban"]) {
    def nodeName = x; // needed due to variable scoping
    par[nodeName] = {
        node (nodeName) {
            try {
               echo "Doing setup on ${env.NODE_NAME}!"
               // Do you're setup
               echo "Done with setup"
            } catch (Exception e) {
               echo "Will not use this node as it failed setup!"
               return;
            }
            while (true) {
               // echo "${jobPool.size()}"
                def subTask = jobPool.poll()
                //echo "${jobPool.size()} ${subTask}"
                if (subTask == null) {
                    break;
                }
                // Might wan't try catch around the next line if you wan't to continue if a job fails
                subTask()
            }
        }
    }
}
parallel par
if (!jobPool.isEmpty()) {
  error "Not all tasks was done!"
}

Simply add your "job pool jobs" to the jobPool variable and modify the setup part.


问:
Handling two observables in canDeactivate
In my canDeactivate() route guard, I am calling a modal that has two buttons: ok and cancel. I want to return true if the ok button gets clicked so that the user can continue leaving the page, and return false if the cancel button gets clicked. Here is my current code:

```<code>canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    let can =  component.canDeactivate();
    //let result = new Observable<boolean>();
    let okResult = new Observable<boolean>();
    let cancelResult = new Observable<boolean>();

    if (!can) {
      component.myChangesModal.show('Warning', 'You are about to leave this page with unsaved changes.');

      okResult = component.myChangesModal.okEvent.map(() => true);
      //okResult.subscribe();

      cancelResult = component.myChangesModal.cancelEvent.map(() => false);
      //cancelResult.subscribe();
      console.log(okResult);
      console.log(cancelResult);

      const observablesArray = [okResult, cancelResult];

      let result = Observable.combineLatest.apply(this, observablesArray).take(1);
      result.subscribe();

      return result;
    }
    return true;
  }
</code>```

Initially when testing this out, I only had a single observable for checking when the ok button gets called, and would then subscribe to that, and return the result. This worked, however it only worked for one button and whenever clicking on the cancel button this broke everything. Here is what I had initially that worked perfectly for only one button.

```<code>canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    let can =  component.canDeactivate();
    let result = new Observable<boolean>();

    if (!can) {
      component.myChangesModal.show('Warning', 'You are about to leave this page with unsaved changes.');

      result = component.myChangesModal.okEvent.map(() => true);
      result.subscribe();

      return result;
    }
    return true;
  }
</code>```

What am I doing wrong when trying to get my canDeactivate modal to work with more than one observable, and what should I do?

答:
CombineLatest will wait til both observables emit a value.  That never happens for your case.  You want Observable.merge instead.

```<code>return okResult.merge(cancelResult).take(1)
</code>```

or

```<code>return Observable.merge(okResult, cancelResult).take(1)
</code>```

Body:
In my canDeactivate() route guard, I am calling a modal that has two buttons: ok and cancel. I want to return true if the ok button gets clicked so that the user can continue leaving the page, and return false if the cancel button gets clicked. Here is my current code:

canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    let can =  component.canDeactivate();
    //let result = new Observable<boolean>();
    let okResult = new Observable<boolean>();
    let cancelResult = new Observable<boolean>();

    if (!can) {
      component.myChangesModal.show('Warning', 'You are about to leave this page with unsaved changes.');

      okResult = component.myChangesModal.okEvent.map(() => true);
      //okResult.subscribe();

      cancelResult = component.myChangesModal.cancelEvent.map(() => false);
      //cancelResult.subscribe();
      console.log(okResult);
      console.log(cancelResult);

      const observablesArray = [okResult, cancelResult];

      let result = Observable.combineLatest.apply(this, observablesArray).take(1);
      result.subscribe();

      return result;
    }
    return true;
  }

Initially when testing this out, I only had a single observable for checking when the ok button gets called, and would then subscribe to that, and return the result. This worked, however it only worked for one button and whenever clicking on the cancel button this broke everything. Here is what I had initially that worked perfectly for only one button.

canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    let can =  component.canDeactivate();
    let result = new Observable<boolean>();

    if (!can) {
      component.myChangesModal.show('Warning', 'You are about to leave this page with unsaved changes.');

      result = component.myChangesModal.okEvent.map(() => true);
      result.subscribe();

      return result;
    }
    return true;
  }

What am I doing wrong when trying to get my canDeactivate modal to work with more than one observable, and what should I do?

Body:
CombineLatest will wait til both observables emit a value.  That never happens for your case.  You want Observable.merge instead.

return okResult.merge(cancelResult).take(1)

or

return Observable.merge(okResult, cancelResult).take(1)


问:
Trying to parse and convert JSON from server
I'm trying to receive a JSON string and feed it into a canvasJS graph. I'm having a hard time trying to figure out how to convert my string to work properly.  Here's what I'm trying, which isn't working:

```<code>function loadGraph(serialNum){

    $.post("../Modules/LoadGraph_Mod/load_graph_mod.php",
    {
      submit: 'loadGraph',

      serial:serialNum

    },
    function(data,status){

newDataPoints=data;

                });

            var chart = new CanvasJS.Chart("chartContainer",
                {
                interactivityEnabled: true,
                zoomEnabled: true,
                          panEnabled: true,
                          backgroundColor:"#000",

                          axisX: {  lineThickness: 1,
                lineColor: "#333",
                 interval: 4

                 ,
                 intervalType: "minutes",
                 valueFormatString: "h:mm",
                 labelFontColor: "#777"
                           },

                          axisY: {  tickColor:"#333",
                          gridColor: "#222",
                          lineThickness: 1,
                lineColor: "#333",
                valueFormatString: ""   ,
                maximum: 100          },
                          data: [{
                              dataPoints : newDataPoints,
                  markerType: "none",
                              color: "#9c9a0c",
                               type: "area",
                              xValueType: "dateTime"

                          }]
                      });

             chart.render();

}
</code>```

I've tried testing it but inserting my server response directly:

```<code>newDataPoints='[{"x":1483648595798,"y":62},{"x":1483648598843,"y":63},{"x":1483648601969,"y":64},{"x":1483648605088,"y":65},{"x":1483648779011,"y":0},{"x":1483648847224,"y":16}]';
</code>```

Which gives me the error:  undefined is not an object.  I've tried running JSON.parse  and end up with a error that says unrecognized token '<'.

It works when I paste the string directly into the chart like this:

```<code>data: [{
                          dataPoints : [{"x":1483648595798,"y":62},{"x":1483648598843,"y":63},{"x":1483648601969,"y":64},{"x":1483648605088,"y":65},{"x":1483648779011,"y":0},{"x":1483648847224,"y":16},{"x":1483648860414,"y":17},{"x":1483648862560,"y":18},{"x":1483648865650,"y":19},{"x":1483648868773,"y":20}],
              markerType: "none",
                          color: "#9c9a0c",
                           type: "area",
                          xValueType: "dateTime"

                      }]
</code>```

So I'm trying to figure out how to convert the JSON string I get back from my servers that it works properly in my chart.  I'd appreciate any help. Thanks.

答:
If you are trying to make a simple request from the server and return a JSON object, I would do the following</p>

```<code>var http = require('http');
http.get(yourUrl, (res) => {
    const statusCode = res.statusCode;

    let error;
    if (statusCode !== 200) {
        error = new Error('Request Failed' + statusCode);
    }

    if (error) {
        console.log(error.message);
    }

    let body = '';
    res.on('data', (chunk) => {
        //individual pre-processing here
        body += chunk;
    }).on('end', () => {
        let parsedBody = JSON.parse(body);
        //Whatever you want to do with the object
    }).on('error', (err) => {
        console.log(err);
    });
});
</code>```

Body:
I'm trying to receive a JSON string and feed it into a canvasJS graph. I'm having a hard time trying to figure out how to convert my string to work properly.  Here's what I'm trying, which isn't working:

function loadGraph(serialNum){

    $.post("../Modules/LoadGraph_Mod/load_graph_mod.php",
    {
      submit: 'loadGraph',

      serial:serialNum

    },
    function(data,status){

newDataPoints=data;

                });

            var chart = new CanvasJS.Chart("chartContainer",
                {
                interactivityEnabled: true,
                zoomEnabled: true,
                          panEnabled: true,
                          backgroundColor:"#000",

                          axisX: {  lineThickness: 1,
                lineColor: "#333",
                 interval: 4

                 ,
                 intervalType: "minutes",
                 valueFormatString: "h:mm",
                 labelFontColor: "#777"
                           },

                          axisY: {  tickColor:"#333",
                          gridColor: "#222",
                          lineThickness: 1,
                lineColor: "#333",
                valueFormatString: ""   ,
                maximum: 100          },
                          data: [{
                              dataPoints : newDataPoints,
                  markerType: "none",
                              color: "#9c9a0c",
                               type: "area",
                              xValueType: "dateTime"

                          }]
                      });

             chart.render();

}

I've tried testing it but inserting my server response directly:

newDataPoints='[{"x":1483648595798,"y":62},{"x":1483648598843,"y":63},{"x":1483648601969,"y":64},{"x":1483648605088,"y":65},{"x":1483648779011,"y":0},{"x":1483648847224,"y":16}]';

Which gives me the error:  undefined is not an object.  I've tried running JSON.parse  and end up with a error that says unrecognized token '<'.

It works when I paste the string directly into the chart like this:

data: [{
                          dataPoints : [{"x":1483648595798,"y":62},{"x":1483648598843,"y":63},{"x":1483648601969,"y":64},{"x":1483648605088,"y":65},{"x":1483648779011,"y":0},{"x":1483648847224,"y":16},{"x":1483648860414,"y":17},{"x":1483648862560,"y":18},{"x":1483648865650,"y":19},{"x":1483648868773,"y":20}],
              markerType: "none",
                          color: "#9c9a0c",
                           type: "area",
                          xValueType: "dateTime"

                      }]

So I'm trying to figure out how to convert the JSON string I get back from my servers that it works properly in my chart.  I'd appreciate any help. Thanks.

Body:
If you are trying to make a simple request from the server and return a JSON object, I would do the following

var http = require('http');
http.get(yourUrl, (res) => {
    const statusCode = res.statusCode;

    let error;
    if (statusCode !== 200) {
        error = new Error('Request Failed' + statusCode);
    }

    if (error) {
        console.log(error.message);
    }

    let body = '';
    res.on('data', (chunk) => {
        //individual pre-processing here
        body += chunk;
    }).on('end', () => {
        let parsedBody = JSON.parse(body);
        //Whatever you want to do with the object
    }).on('error', (err) => {
        console.log(err);
    });
});


问:
formatting in xslt
I want to display a set of data
in pivoted form

The data retrieved from query is in this format

```
AccID                Month                Year       FTE

1                     Jan                  2009       10
1                     Feb                  2009      20
2                     Jan                  2010      30
```

I want to display it as

```
AccID  Jan 2009  Feb 2009  Jan 2010
1        10        20
2                            30
```

答:
This stylesheet:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="kItemByDate" match="item" use="concat(Month,Year)"/>
    <xsl:key name="kItemByAccID" match="item" use="AccID"/>
    <xsl:variable name="vDates"
         select="/root/item[count(.|key('kItemByDate',
                                        concat(Month,Year))[1])=1]"/>
    <xsl:template match="text()"/>
    <xsl:template match="/">
        <table>
            <tr>
                <th>AccID</th>
                <xsl:for-each select="$vDates">
                    <th>
                        <xsl:value-of select="concat(Month,' ',Year)"/>
                    </th>
                </xsl:for-each>
            </tr>
            <xsl:apply-templates/>
        </table>
    </xsl:template>
    <xsl:template match="item[count(.|key('kItemByAccID',AccID)[1])=1]">
        <xsl:variable name="vItems" select="key('kItemByAccID',AccID)"/>
        <tr>
            <td>
                <xsl:value-of select="AccID"/>
            </td>
            <xsl:for-each select="$vDates">
                <td>
                    <xsl:value-of select="$vItems[Month=current()/Month]
                                                 [Year=current()/Year]
                                                 /FTE"/>
                </td>
            </xsl:for-each>
        </tr>
    </xsl:template>
</xsl:stylesheet>
</code>```

With this input:

```<code><root>
    <item>
        <AccID>1</AccID>
        <Month>Jan</Month>
        <Year>2009</Year>
        <FTE>10</FTE>
    </item>
    <item>
        <AccID>1</AccID>
        <Month>Feb</Month>
        <Year>2009</Year>
        <FTE>20</FTE>
    </item>
    <item>
        <AccID>2</AccID>
        <Month>Jan</Month>
        <Year>2010</Year>
        <FTE>30</FTE>
    </item>
</root>
</code>```

Output:

```<code><table>
    <tr>
        <th>AccID</th>
        <th>Jan 2009</th>
        <th>Feb 2009</th>
        <th>Jan 2010</th>
    </tr>
    <tr>
        <td>1</td>
        <td>10</td>
        <td>20</td>
        <td></td>
    </tr>
    <tr>
        <td>2</td>
        <td></td>
        <td></td>
        <td>30</td>
    </tr>
</table>
</code>```

ContentLicense: CC BY-SA 2.5

Title: formatting in xslt

Body:
I want to display a set of data
in pivoted form

The data retrieved from query is in this format

AccID                Month                Year       FTE

1                     Jan                  2009       10
1                     Feb                  2009      20
2                     Jan                  2010      30

I want to display it as

AccID  Jan 2009  Feb 2009  Jan 2010
1        10        20
2                            30

Body:
This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="kItemByDate" match="item" use="concat(Month,Year)"/>
    <xsl:key name="kItemByAccID" match="item" use="AccID"/>
    <xsl:variable name="vDates"
         select="/root/item[count(.|key('kItemByDate',
                                        concat(Month,Year))[1])=1]"/>
    <xsl:template match="text()"/>
    <xsl:template match="/">
        <table>
            <tr>
                <th>AccID</th>
                <xsl:for-each select="$vDates">
                    <th>
                        <xsl:value-of select="concat(Month,' ',Year)"/>
                    </th>
                </xsl:for-each>
            </tr>
            <xsl:apply-templates/>
        </table>
    </xsl:template>
    <xsl:template match="item[count(.|key('kItemByAccID',AccID)[1])=1]">
        <xsl:variable name="vItems" select="key('kItemByAccID',AccID)"/>
        <tr>
            <td>
                <xsl:value-of select="AccID"/>
            </td>
            <xsl:for-each select="$vDates">
                <td>
                    <xsl:value-of select="$vItems[Month=current()/Month]
                                                 [Year=current()/Year]
                                                 /FTE"/>
                </td>
            </xsl:for-each>
        </tr>
    </xsl:template>
</xsl:stylesheet>

With this input:

<root>
    <item>
        <AccID>1</AccID>
        <Month>Jan</Month>
        <Year>2009</Year>
        <FTE>10</FTE>
    </item>
    <item>
        <AccID>1</AccID>
        <Month>Feb</Month>
        <Year>2009</Year>
        <FTE>20</FTE>
    </item>
    <item>
        <AccID>2</AccID>
        <Month>Jan</Month>
        <Year>2010</Year>
        <FTE>30</FTE>
    </item>
</root>

Output:

<table>
    <tr>
        <th>AccID</th>
        <th>Jan 2009</th>
        <th>Feb 2009</th>
        <th>Jan 2010</th>
    </tr>
    <tr>
        <td>1</td>
        <td>10</td>
        <td>20</td>
        <td></td>
    </tr>
    <tr>
        <td>2</td>
        <td></td>
        <td></td>
        <td>30</td>
    </tr>
</table>


问:
Wordpress ajax request return 0
Hello I have a problem with wordpress I can not get an ajax call and I can not find the reason. My query returns me all the time 0.

my javascript code :

updateButton.onclick = function (e) {

```<code>var donne = {
'action': 'my_action',
'lodges': updateDeleteArray
};

$(function () {
$.ajax({
type: "POST",
data: donne,
url: ajaxurl,
contentType: "application/json",
dataType: 'json',
success: function (data) {
console.log(data);
                },
            });
        });
};
</code>```

my php code :

```<code>add_action('wp_ajax_my_action',        'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

function my_action() {
    echo 'salut';
    die();
}
</code>```

答:
Try deleting contentType and dataType, because you are not returning a JSON into your function.

Or

modify your function like this

```<code>function my_action() {
    echo json_encode('salut');
    die();
}
</code>```

hope it helps

Title: Wordpress ajax request return 0

Body:
Hello I have a problem with wordpress I can not get an ajax call and I can not find the reason. My query returns me all the time 0.

my javascript code :

updateButton.onclick = function (e) {

var donne = {
'action': 'my_action',
'lodges': updateDeleteArray
};

$(function () {
$.ajax({
type: "POST",
data: donne,
url: ajaxurl,
contentType: "application/json",
dataType: 'json',
success: function (data) {
console.log(data);
                },
            });
        });
};

my php code :

add_action('wp_ajax_my_action',        'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

function my_action() {
    echo 'salut';
    die();
}

Body:
Try deleting contentType and dataType, because you are not returning a JSON into your function.

Or

modify your function like this

function my_action() {
    echo json_encode('salut');
    die();
}

hope it helps


问:
Mysql get randomly but try to get with the smallest values
I have got a row in MySQL table named number_of_times,i sent this query to SQL SELECT * FROM Vocab ORDER BY Rand() LIMIT 3 and it returns 3 random datas,how can i select 3 random numbers,but from the ones where the number_of_times row is the smallest

答:
You need to choose the smallest values.  Just use number_of_times as the first key in the order by:

```<code>SELECT *
FROM Vocab
ORDER BY number_of_times asc, Rand()
LIMIT 3;
</code>```

Note:  If you only want values with the smallest number_of_times -- even if there are not 3 of them -- then this may be faster:

```<code>SELECT *
FROM Vocab
WHERE number_of_times = (SELECT MIN(number_of_times) from Vocab)
ORDER BY Rand()
LIMIT 3;
</code>```

This can take advantage of an index on Vocab(number_of_times).

Body:
You need to choose the smallest values.  Just use number_of_times as the first key in the order by:

SELECT *
FROM Vocab
ORDER BY number_of_times asc, Rand()
LIMIT 3;

Note:  If you only want values with the smallest number_of_times -- even if there are not 3 of them -- then this may be faster:

SELECT *
FROM Vocab
WHERE number_of_times = (SELECT MIN(number_of_times) from Vocab)
ORDER BY Rand()
LIMIT 3;

This can take advantage of an index on Vocab(number_of_times).


问:
Internet Explorer conditional formatting works when using greater than, but not less than
Adding this to the head of the page

```<code><!--[if gt IE 6]>
    <link rel="stylesheet" type="text/css" href="css/ie.css">
    <script src="js/html5shiv.min.js"></script>
    <script src="js/respond.min.js"></script>
<![endif]-->
</code>```

works perfectly, however attempting this

```<code><!--[if lt IE 9]>
    <link rel="stylesheet" type="text/css" href="css/ie.css">
    <script src="js/html5shiv.min.js"></script>
    <script src="js/respond.min.js"></script>

<![endif]-->
</code>```

does nothing. As far as I can tell, if one works so should the other. Am I missing something?

答:
Could try using lte instead of lt?

Or, since 10 and 11 don't support conditional comments, what about trying this instead:

```<code><!--[if IE]>
    <link rel="stylesheet" type="text/css" href="css/ie.css">
    <script src="js/html5shiv.min.js"></script>
    <script src="js/respond.min.js"></script>
<![endif]-->
</code>```

https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx

Body:
Adding this to the head of the page

works perfectly, however attempting this

does nothing. As far as I can tell, if one works so should the other. Am I missing something?

Body:
Could try using lte instead of lt?

Or, since 10 and 11 don't support conditional comments, what about trying this instead:

<!--[if IE]>
    <link rel="stylesheet" type="text/css" href="css/ie.css">
    <script src="js/html5shiv.min.js"></script>
    <script src="js/respond.min.js"></script>
<![endif]-->

https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx


问:
React - elegant way to re-render just one child component?
I'm working on a table component.  When I scroll left and right on the
 I want it to update the xOffset of just the <theader /> which is in a separate component I'll call .  Here's the structure:

```<code><Parent Component >
    <Header Component />
    <Very Expensive Body divs/>
    <Very Expensive Body divs/>
    <Very Expensive Body divs/>
</Parent Component >
</code>```

The scroll listener is on the parent component and the xOffset is part of the Parent Component's state.  When I scroll left and right, it also re-renders the very expensive to re-render body components.

What are my options for just the Header Component to re-render?

1) Use Redux and selectors.  Parent component dispatches an xOffset to app state and the  listens just for that on a selector.  Seems like overkill...

2) I break out all the <Very Expensive Body Comp divs > into their own component, and use ShouldComponentUpdate so that it doesn't re-render if everything stays the same besides xOffset.  This doesn't seem like overkill, but I feel like I'm going to be dealing with the same problem because I'll have to put the scroll listener on this new component... and then use the parent component as an intermediary.. oof.

Is there a third more elegant solution?

I'm hoping there's a way to pass a function into the  so that when the parent component scrolls left and right, it uses that function to update the state of the  which would cause just it to re-render.

答:
If I understand correctly, one option is to do something like:

```<code><Parent Component >
    <Header Component />
    { this.getVeryExpensiveBodyDivs() }
</Parent Component >
</code>```

And have getVeryExpensiveBodyDivs generate and cache the divs the first time and then just access them from the cache afterward if they're in the cache. The cache would just be an instance variable (this.cachedVeryExpensiveBodyDivs).

Then, in your table component's componentWillReceiveProps, you can check if any props are changing that should affect the very expensive body divs. If the prop changes should affect the very expensive body divs, clear the cache. The next time getVeryExpensiveBodyDivs is called it will regenerate and recache the divs.

Body:
I'm working on a table component.  When I scroll left and right on the
 I want it to update the xOffset of just the <theader /> which is in a separate component I'll call .  Here's the structure:

<Parent Component >

    <Very Expensive Body divs/>
    <Very Expensive Body divs/>
    <Very Expensive Body divs/>
</Parent Component >

The scroll listener is on the parent component and the xOffset is part of the Parent Component's state.  When I scroll left and right, it also re-renders the very expensive to re-render body components.

What are my options for just the Header Component to re-render?

1) Use Redux and selectors.  Parent component dispatches an xOffset to app state and the  listens just for that on a selector.  Seems like overkill...

2) I break out all the <Very Expensive Body Comp divs > into their own component, and use ShouldComponentUpdate so that it doesn't re-render if everything stays the same besides xOffset.  This doesn't seem like overkill, but I feel like I'm going to be dealing with the same problem because I'll have to put the scroll listener on this new component... and then use the parent component as an intermediary.. oof.

Is there a third more elegant solution?

I'm hoping there's a way to pass a function into the  so that when the parent component scrolls left and right, it uses that function to update the state of the  which would cause just it to re-render.

Body:
If I understand correctly, one option is to do something like:

<Parent Component >
    <Header Component />
    { this.getVeryExpensiveBodyDivs() }
</Parent Component >

And have getVeryExpensiveBodyDivs generate and cache the divs the first time and then just access them from the cache afterward if they're in the cache. The cache would just be an instance variable (this.cachedVeryExpensiveBodyDivs).

Then, in your table component's componentWillReceiveProps, you can check if any props are changing that should affect the very expensive body divs. If the prop changes should affect the very expensive body divs, clear the cache. The next time getVeryExpensiveBodyDivs is called it will regenerate and recache the divs.


问:
How to wait for a SQL Server database rollback to complete?
When using the ADO.NET SqlClient classes, there are a few ways in which a transaction can be rolled back. Either by explicitly calling SqlTransaction.Rollback, or having a command timeout, or a transaction timeout within a transaction scope etc.

But how can I detect when this rollback has completed when using SQL Server (2012 or later)? For a long running transaction the rollback may take a long time, and it is usually quite IO-intensive on the database, so it may not be wise to retry the transaction immediately. In our situation we would like to wait for the rollback to complete.

(In our specific case the rollback occurs because of a transaction timeout using the TransactionScope class, but I would prefer a method that would work for any kind of rollback).

I have looked at the sys.dm_exec_requests which looked promising at first. It had a command type of KILL/ROLLBACK at first, and reported the progress percentage. (If I captured the SPID from the original transaction I would be able to poll this table and wait for it to complete). However, about halfway through I noticed it changed to AWAITING COMMAND instead (while the rollback was still being performed).

I also looked at KILL <SPID> WITH STATUSONLY. This seems to generate an error if there is no rollback in progress, so it could work as well for a polling approach, but I noticed that if I ran a BEGIN TRAN ... ROLLBACK TRAN batch from SSMS, this reported an error saying that no rollback was in progress when it was rolling back. The dm_exec_requests table reported ROLLBACK TRANSACTION as the command type in this case.

So how can I wait for a rollback to complete in a reliable way?

答:
```<code>SqlRollback.cs

using System;
using System.Data.SqlClient;
using System.Threading;

namespace Events
{
    public class SqlRollback
    {
        private string _connString = "Server=(localdb)\\mssqllocaldb;Database=QueryIt.EmployeeDb;Trusted_Connection=true";
        public event EventHandler TransactionRolledBack;

        public void Transact()
        {
            using (SqlConnection conn = new SqlConnection(_connString))
            {
                conn.Open();

                var command = conn.CreateCommand();
                SqlTransaction transaction;
                transaction = conn.BeginTransaction("Transaction");

                command.Connection = conn;
                command.Transaction = transaction;

                try
                {
                    transaction.Save("checkpoint");
                    command.CommandText = "INSERT INTO Employees (name, discriminator) VALUES ('Dimitar', 'Bastun')";
                    command.ExecuteNonQuery();
                    throw new Exception();

                } catch (Exception ex)
                {
                    transaction.Rollback("checkpoint"); //Rolling back to the checkpoint
                    Thread.Sleep(5000); //Simulating some time
                    transaction.Commit();
                    this.OnTransactionRollingBack(EventArgs.Empty);
                }
            }
        }

        private void OnTransactionRollingBack(EventArgs e)
        {
            EventHandler handler = TransactionRolledBack;
            if(handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Events
{
    class Program
    {
        static void Main(string[] args)
        {
            var rollBack = new SqlRollback();
            rollBack.TransactionRolledBack += RollBack_TransactionRolledBack;

            try
            {
                rollBack.Transact();
            } catch (Exception e)
            {

            }
        }

        private static void RollBack_TransactionRolledBack(object sender, EventArgs e)
        {
            Console.WriteLine("Rooled!");
        }
    }
}
</code>```


问:
calling quit() method of QApplication
if i try to use quit() method directly, it is compiling perfectly,
however during runtime there comes an error saying "Object::connect: No such slot myClass::quit()."
so to avoid this, is there any way?
by using a method quitPicture()(defined as slot) the application is working fine.
is this the only solution?</p>

```<code>myClass::myClass(QWidget *parent)
    : QWidget(parent)
{
    QWidget *window = new QWidget;
    window->setWindowTitle(QObject::tr("Class"));

    QPushButton *quitButton = new QPushButton("&Quit");
//    QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));      //showing run time error
    QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(quitPicture())); //working perfectly

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(this);
    layout->addWidget(quitButton);
    window->setLayout(layout);
    window->show();
}

void myClass::quitPicture()
{
    std::cout << "calling quitPicture" << std::endl;
    QApplication::quit();
}
</code>```

答:
```<code>void my_exit_func()
{
    // in mainwindow.cpp
    delete MainWindow;
}
</code>```

Title: calling quit() method of QApplication

Body:
if i try to use quit() method directly, it is compiling perfectly,
however during runtime there comes an error saying "Object::connect: No such slot myClass::quit()."
so to avoid this, is there any way?
by using a method quitPicture()(defined as slot) the application is working fine.
is this the only solution?

myClass::myClass(QWidget *parent)
    : QWidget(parent)
{
    QWidget *window = new QWidget;
    window->setWindowTitle(QObject::tr("Class"));

    QPushButton *quitButton = new QPushButton("&Quit");
//    QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));      //showing run time error
    QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(quitPicture())); //working perfectly

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(this);
    layout->addWidget(quitButton);
    window->setLayout(layout);
    window->show();
}

void myClass::quitPicture()
{
    std::cout << "calling quitPicture" << std::endl;
    QApplication::quit();
}


问:
How to convert a 2D array to a value object in ruby
I have a 2D array:

```<code>a = [["john doe", "01/03/2017", "01/04/2017", "event"], ["jane doe", "01/05/2017", "01/06/2017", "event"]...]
</code>```

I would like to convert it to a value object in ruby. I found how to do it with a hash Ruby / Replace value in array of hash in the second answer of this question but not a 2D array. I would like to assign the value at a[0][0] to an attribute named "name", a[0][1] to "date1", a[0][2] to "date2" and a[0][3] to "event".

This is something like what I'd like to accomplish although it is not complete and I dont know how to assign multiple indexes to the different attributes in one loop:

```<code>class Schedule_info
   arrt_accessor :name, :date1, :date2, :event

   def initialize arr
       #I would like this loop to contain all 4 attr assignments
       arr.each {|i| instance_variable_set(:name, i[0])}
</code>```

答:
Try this:</p>

```<code>class Schedule_info
  arrt_accessor :name, :date1, :date2, :event

  def initialize arr
    @name = []
    @date1 = []
    @date2 = []
    @event = []
    arr.each |i| do
      name << i[0]
      date1 << i[1]
      date2 << i[2]
      event << i[3]
    end
  end

end
</code>```

Body:
I have a 2D array:

a = [["john doe", "01/03/2017", "01/04/2017", "event"], ["jane doe", "01/05/2017", "01/06/2017", "event"]...]

I would like to convert it to a value object in ruby. I found how to do it with a hash Ruby / Replace value in array of hash in the second answer of this question but not a 2D array. I would like to assign the value at a[0][0] to an attribute named "name", a[0][1] to "date1", a[0][2] to "date2" and a[0][3] to "event".

This is something like what I'd like to accomplish although it is not complete and I dont know how to assign multiple indexes to the different attributes in one loop:

class Schedule_info
   arrt_accessor :name, :date1, :date2, :event

   def initialize arr
       #I would like this loop to contain all 4 attr assignments
       arr.each {|i| instance_variable_set(:name, i[0])}

Body:
Try this:

class Schedule_info
  arrt_accessor :name, :date1, :date2, :event

  def initialize arr
    @name = []
    @date1 = []
    @date2 = []
    @event = []
    arr.each |i| do
      name << i[0]
      date1 << i[1]
      date2 << i[2]
      event << i[3]
    end
  end

end


问:
Is the order in which function arguments are resolved guaranteed?
say I have this:

function write3(a, b, c) {
  document.write(a + " " + b + " " + c);
}

var arr = [1, 2, 3];
var i = 0;

write3(arr[i++], arr[i++], arr[i++]);```

It results in 1 2 3 as expected, however, I'm not sure that this is guaranteed behavior. Could the arguments passed to write3 hypothetically be resolved in any other order than left to right?

答:
Yes, the order of argument evaluation is guaranteed to be left-to-right.

According to sections 11.2.3 and 11.2.4 of the ES5 spec, function arguments are Argument Lists, and Argument Lists should always be evaluated left to right.

Specifically, the function to call gets evaluated, and then the function's arguments are evaluated from left to right.

Body:
say I have this:

function write3(a, b, c) {
  document.write(a + " " + b + " " + c);
}

var arr = [1, 2, 3];
var i = 0;

write3(arr[i++], arr[i++], arr[i++]);

It results in 1 2 3 as expected, however, I'm not sure that this is guaranteed behavior. Could the arguments passed to write3 hypothetically be resolved in any other order than left to right?


问:
Python - How to improve performance of subsetting tuple key dictionaries through for loop?
I have two dictionaries with tuple keys. I subsetted each dictionary into 3 small dictionaries and then applied the prediction model to each dictionary. See below,

```<code># Subset dictionaries from df_dict140 and df_dict150
# df_dict140 has 456 rows and df_dict150 has 415
# I subsetted the them by 200
dic1 = {k: df_dic[k] for k in df_dict140[:200]}
dic2 = {k: df_dic[k] for k in df_dict140[200:400]}
dic3 = {k: df_dic[k] for k in df_dict140[400:456]}

dic4 = {k: df_dic[k] for k in df_dict150[:200]}
dic5 = {k: df_dic[k] for k in df_dict150[200:400]}
dic6 = {k: df_dic[k] for k in df_dict150[400:415]}
</code>```

Applied the model to each dictionary,

```<code>def predictionModel(pred_dict):
    prediction = {}
    for (key1, key2), value in pred_dict.items():
        m = Prophet().fit(value)
        future = m.make_future_dataframe(periods = 365)
        forecast = m.predict(future)
        prediction[key2] = forecast[['ds','yhat']].tail()
    return prediction
</code>```

Prediction results,

```<code>prediction1 = predictionModel(dic1)
prediction2 = predictionModel(dic2)
prediction3 = predictionModel(dic3)
prediction4 = predictionModel(dic4)
prediction5 = predictionModel(dic5)
prediction6 = predictionModel(dic6)
</code>```

Is it possible to write a function or for loop to do the above work so that no need to subset the dictionaries twice and can get the results by once.

答:
I still don't understand what you are doing with Prophet, but if you just want to slice the dictionaries programmatically:</p>

```<code>for i in range(0,max(len(dict140),len(dict150)),200):
    d140_slice = {k: df_dic[k] for k in dict140[i:i+200]}
    d150_slice = {k: df_dic[k] for k in dict150[i:i+200]}
    #do something with the slices.
</code>```

Body:
I have two dictionaries with tuple keys. I subsetted each dictionary into 3 small dictionaries and then applied the prediction model to each dictionary. See below,

# Subset dictionaries from df_dict140 and df_dict150
# df_dict140 has 456 rows and df_dict150 has 415
# I subsetted the them by 200
dic1 = {k: df_dic[k] for k in df_dict140[:200]}
dic2 = {k: df_dic[k] for k in df_dict140[200:400]}
dic3 = {k: df_dic[k] for k in df_dict140[400:456]}

dic4 = {k: df_dic[k] for k in df_dict150[:200]}
dic5 = {k: df_dic[k] for k in df_dict150[200:400]}
dic6 = {k: df_dic[k] for k in df_dict150[400:415]}

Applied the model to each dictionary,

def predictionModel(pred_dict):
    prediction = {}
    for (key1, key2), value in pred_dict.items():
        m = Prophet().fit(value)
        future = m.make_future_dataframe(periods = 365)
        forecast = m.predict(future)
        prediction[key2] = forecast[['ds','yhat']].tail()
    return prediction

Prediction results,

prediction1 = predictionModel(dic1)
prediction2 = predictionModel(dic2)
prediction3 = predictionModel(dic3)
prediction4 = predictionModel(dic4)
prediction5 = predictionModel(dic5)
prediction6 = predictionModel(dic6)

Is it possible to write a function or for loop to do the above work so that no need to subset the dictionaries twice and can get the results by once.

Body:
I still don't understand what you are doing with Prophet, but if you just want to slice the dictionaries programmatically:

for i in range(0,max(len(dict140),len(dict150)),200):
    d140_slice = {k: df_dic[k] for k in dict140[i:i+200]}
    d150_slice = {k: df_dic[k] for k in dict150[i:i+200]}
    #do something with the slices.


问:
How to save changes twice in one method using Entity Framework Core
Using Entity Framework Core i am trying to save changes twice for the same entity collection.

```<code>    public async Task Save(IEnumerable<Request> request)
    {
        var entities = request.Select(x => new MyEntity()
        {
            FileName = x.FileName,
            Status = Status.Downloading
        });

        // save as downloading
        await _dbContext.MyFiles.AddRangeAsync(entities).ConfigureAwait(false);
        await _dbContext.SaveChangesAsync().ConfigureAwait(false);

        // start downloading
        await _storage.DownloadFilesAsync(request).ConfigureAwait(false);

        // save as downloaded
        foreach (var entity in entities)
        {
            entity.Status = Status.Downloaded;
        }

        // this save DOES NOT update the entities with status Downloaded
        await _dbContext.SaveChangesAsync().ConfigureAwait(false);
    }
</code>```

The first call to SaveChanges() method creates entities in the DB with status Downloading.

Then i am modifying entity's status to Downloaded and call SaveChanges() again. However this time entities does not get updated in DB.

I thought entities are already loaded in the Db context, so i dont have to reload them before second SaveChanges. Just modifying the property would mark them modified. But its not working.

Update 1

I updated code as below and explicitly set State as Modified

```<code> // save as downloaded
 foreach (var entity in entities)
 {
    entity.Status = Status.Downloaded;

    // The exception occurs at line below on 2nd loop
   _dbContext.Entry(entity).State = EntityState.Modified;
 }
</code>```

Now im getting exception

System.InvalidOperationException: The instance of entity type
  'MyEntity' cannot be tracked because another instance of this type
  with the same key is already being tracked. When adding new entities,
  for most key types a unique temporary key value will be created if no
  key is set (i.e. if the key property is assigned the default value for
  its type). If you are explicitly setting key values for new entities,
  ensure they do not collide with existing entities or temporary values
  generated for other new entities. When attaching existing entities,
  ensure that only one entity instance with a given key value is
  attached to the context.    at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey
  key, InternalEntityEntry entry)    at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry
  entry)    at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
  oldState, EntityState newState, Boolean acceptChanges)

The entity has Id property of type int and The Id property also has [Key] attribute.

```<code>public class MyEntity
{
   [System.ComponentModel.DataAnnotations.Key]
   public int Id {get;set;}
   public string FileName {get;set;}
   public string Status {get;set;}
}
</code>```

Update 2

So after doing little more debugging, i found the first SaveChanges() operation is creating the records in the database and also assigning unique Ids to each record as expected. The Id is auto incremented identity column in the database.
However the entities are not refreshed with new Ids. so all the entities still have value 0 after first savechanges.

How do i refresh these entities with newly created Ids?

Inside foreach loop i tried reloading as

```<code>   _dbContext.Entry<OcrFile>(entity).ReloadAsync().ConfigureAwait(false);
</code>```

but that didn't refresh.

答:
Resolved!!. I have to eagerly load entities using ToList() or ToArray() before i pass them to AddRange method

```<code>    var entities = request.Select(x => new MyEntity()
    {
        FileName = x.FileName,
        Status = Status.Downloading
    }).ToList();
</code>```

I am not sure that is a bug in EF but i created a separate SO thread for that question

Body:
Using Entity Framework Core i am trying to save changes twice for the same entity collection.

    public async Task Save(IEnumerable<Request> request)
    {
        var entities = request.Select(x => new MyEntity()
        {
            FileName = x.FileName,
            Status = Status.Downloading
        });

        // save as downloading
        await _dbContext.MyFiles.AddRangeAsync(entities).ConfigureAwait(false);
        await _dbContext.SaveChangesAsync().ConfigureAwait(false);

        // start downloading
        await _storage.DownloadFilesAsync(request).ConfigureAwait(false);

        // save as downloaded
        foreach (var entity in entities)
        {
            entity.Status = Status.Downloaded;
        }

        // this save DOES NOT update the entities with status Downloaded
        await _dbContext.SaveChangesAsync().ConfigureAwait(false);
    }

The first call to SaveChanges() method creates entities in the DB with status Downloading.

Then i am modifying entity's status to Downloaded and call SaveChanges() again. However this time entities does not get updated in DB.

I thought entities are already loaded in the Db context, so i dont have to reload them before second SaveChanges. Just modifying the property would mark them modified. But its not working.

Update 1

I updated code as below and explicitly set State as Modified

 // save as downloaded
 foreach (var entity in entities)
 {
    entity.Status = Status.Downloaded;

    // The exception occurs at line below on 2nd loop
   _dbContext.Entry(entity).State = EntityState.Modified;
 }

Now im getting exception

System.InvalidOperationException: The instance of entity type
  'MyEntity' cannot be tracked because another instance of this type
  with the same key is already being tracked. When adding new entities,
  for most key types a unique temporary key value will be created if no
  key is set (i.e. if the key property is assigned the default value for
  its type). If you are explicitly setting key values for new entities,
  ensure they do not collide with existing entities or temporary values
  generated for other new entities. When attaching existing entities,
  ensure that only one entity instance with a given key value is
  attached to the context.    at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey
  key, InternalEntityEntry entry)    at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry
  entry)    at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
  oldState, EntityState newState, Boolean acceptChanges)

The entity has Id property of type int and The Id property also has [Key] attribute.

public class MyEntity
{
   [System.ComponentModel.DataAnnotations.Key]
   public int Id {get;set;}
   public string FileName {get;set;}
   public string Status {get;set;}
}

Update 2

So after doing little more debugging, i found the first SaveChanges() operation is creating the records in the database and also assigning unique Ids to each record as expected. The Id is auto incremented identity column in the database.
However the entities are not refreshed with new Ids. so all the entities still have value 0 after first savechanges.

How do i refresh these entities with newly created Ids?

Inside foreach loop i tried reloading as

   _dbContext.Entry<OcrFile>(entity).ReloadAsync().ConfigureAwait(false);

but that didn't refresh.

Body:
Resolved!!. I have to eagerly load entities using ToList() or ToArray() before i pass them to AddRange method

    var entities = request.Select(x => new MyEntity()
    {
        FileName = x.FileName,
        Status = Status.Downloading
    }).ToList();

I am not sure that is a bug in EF but i created a separate SO thread for that question


问:
how to get only fully matched string from match
I need to match "test" or "test," from a string like

```<code>"test, testhellowowo, wowtest,"
</code>```

Attempt 1

```<code>test[,]?
</code>```

it will match all three since all of the string include the test regardless what comes after.

Attempt 2

```<code>^test[,]?$
</code>```

it won't match any unless the string is test or test,

Expected results

```<code>"test, testhellowowo, wowtest,".match(x) // should match `test,`
"testhellowowo, wowtest,".match(x)  // should not match anything
</code>```

答:
If you need to include the punctuation mark you could also do /^test[,]?$/gm

^ matches beginning of string
$ matches end of string

Body:
I need to match "test" or "test," from a string like

"test, testhellowowo, wowtest,"

Attempt 1

test[,]?

it will match all three since all of the string include the test regardless what comes after.

Attempt 2

^test[,]?$

it won't match any unless the string is test or test,

Expected results

"test, testhellowowo, wowtest,".match(x) // should match `test,`
"testhellowowo, wowtest,".match(x)  // should not match anything


问:
After Jenkins2.5 update serenity reports are broken
can anyone help me to resolve below issue

I have updated my jenkins version 2.5 ,serenity reports are broken and screenshots are displayed but i can't open them to see those screenshots i have to manually save those.

答: This is a Jenkins bug (or "feature", depending on who you ask). Recent versions of Jenkins by default don't render complex HTML reports correctly. The problem and a solution are discussed here: Jenkins - HTML Publisher Plugin - No CSS is displayed when report is viewed in Jenkins Server</p>


问:
Changing App title - Google Play store issue
Trying to release a new version of my app on the play store - and I'm changing the App's name from the 'Store Listing' section. But I keep getting this error :

You need to choose a different title for your app.

This one is already the title of tmp.xxxxxxxxxxxxx.xxxxxxxxxxxxx.

I realized that the name I'm trying to enter is what is stored in the @string/app_name variable for the APK that is in release right now - is this why I'm getting the error? Will changing this name in the new APK fix the issue? Or am I missing out on something?

答:
No, But you can set same or differ name from @string/app_name & its not affect your app, so don't worried about that.
But which Name you tried, that already taken by other so please add any extra phrase to your app name. Its only for show on Play Store.


问:
Java API for SSH Secondary Login Validation
Currently when I connect from windows to our linux host server, I use putty with my credentials in a .bat file to automatically access the machine. However the connection does not automatically direct me to the terminal shell but there's a secondary interactive login prompt that requires me to manually input another username and password, as of now I don't know how to get pass these with automation.

My question, is it possible to automate these specifically on java or just a .bat?

One of my co-workers managed to do it on VB script using the "sendkey" method. The information online states "sendkey" send one or more keystrokes to the active window as if they were typed at the keyboard. May I know is there a counterpart of sendkey in Java in JSCH or SSHJ?

NOTE: I'm not after to connect directly to the terminal, what I'm after is to automate the interactive login as if I were manually typing it like what the sendkey does.

答:
Injecting typed characters into a ssh session is pretty simple. Just inject the characters to be written into the OutputStream provided by sshj. I assume that you log-in and then execute something that requires the interactive console login.

I simulate the executed process using the following simple script named test.sh. It reads a typed line and prints it.

```<code>#/bin/bash
read varname
echo You typed $varname
</code>```

I am executing this script using a modified Exec example from sshj:

```<code>final Session session = ssh.startSession();
try {
    Command cmd = session.exec("/home/username/test.sh");
    OutputStream out = cmd.getOutputStream();
    out.write("1234567\n".getBytes()); // we type 1234567
    out.flush();
    System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
    cmd.join(5, TimeUnit.SECONDS);
    System.out.println("\n** exit status: " + cmd.getExitStatus());
} finally {
    session.close();
}
</code>```

If you execute the script using the sshj code you will get the result

You typed 1234567

By reading the inputStream line by line you can wait for the line that asks for the username or password and send the right data to the server, simulating your input.

Body:
Injecting typed characters into a ssh session is pretty simple. Just inject the characters to be written into the OutputStream provided by sshj. I assume that you log-in and then execute something that requires the interactive console login.

I simulate the executed process using the following simple script named test.sh. It reads a typed line and prints it.

#/bin/bash
read varname
echo You typed $varname

I am executing this script using a modified Exec example from sshj:

final Session session = ssh.startSession();
try {
    Command cmd = session.exec("/home/username/test.sh");
    OutputStream out = cmd.getOutputStream();
    out.write("1234567\n".getBytes()); // we type 1234567
    out.flush();
    System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
    cmd.join(5, TimeUnit.SECONDS);
    System.out.println("\n** exit status: " + cmd.getExitStatus());
} finally {
    session.close();
}

If you execute the script using the sshj code you will get the result

You typed 1234567

By reading the inputStream line by line you can wait for the line that asks for the username or password and send the right data to the server, simulating your input.


答:
Could the arguments passed to write3 hypothetically be resolved in any other order than left to right?

No, they will always be resolved left-to-right. This is guaranteed behavior.

I also feel like I should point out that you can call a function with an array of arguments using apply:

```<code>write3.apply(null, arr)
</code>```

. . . or the spread operator in ES6+ (may not be supported in all browsers):

```<code>write3(...arr)
</code>```

Demo Snippet:

function write3(a, b, c) {
  document.write(a + " " + b + " " + c)
}

var arr = [1, 2, 3]

write3.apply(null, arr)

write3(...arr)```

Title: Is the order in which function arguments are resolved guaranteed?

Body:
Could the arguments passed to write3 hypothetically be resolved in any other order than left to right?

No, they will always be resolved left-to-right. This is guaranteed behavior.

I also feel like I should point out that you can call a function with an array of arguments using apply:

write3.apply(null, arr)

. . . or the spread operator in ES6+ (may not be supported in all browsers):

write3(...arr)

Demo Snippet:

function write3(a, b, c) {
  document.write(a + " " + b + " " + c)
}

var arr = [1, 2, 3]

write3.apply(null, arr)

write3(...arr)


问:
When creating a menu in Python 3.6 and tkinter, drop down doesnt stay in Frame
Edit: OS is Windows 10 64 Bit

Ok, so I have googled my rear-end off on this one. I am building a simple tkinter app and upon setting it up and just generally messing around with options to add to it, my drop down from the menu created doesn't stay constrained inside the Frame.

```<code>import tkinter as tk

class Window(tk.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.main_window()
        self.widgets()

    # All main window parameters go here
    def main_window(self):
        self.master.title("Calculate Commission")
        self.master.geometry("800x600")
        self.pack()

    def widgets(self):
        main_menu = tk.Menu(self.master, tearoff=0)
        self.master.config(menu=main_menu)

        # Create File Menu and Drop Down
        file = tk.Menu(main_menu, tearoff=0)
        file.add_command(label="Save")
        file.add_command(label="Exit", command=exit)
        main_menu.add_cascade(label="File", menu=file)

        # Create Edit Menu and Drop Down
        edit = tk.Menu(main_menu, tearoff=0)
        edit.add_command(label="undo")
        main_menu.add_cascade(label="Edit", menu=edit)

main = tk.Tk()
comm_prog = Window(master=main)
main.mainloop()
</code>```

Please see this attached screenshot to see what I am referring too:

I am fairly confident this may end up either of two ways. Either it's a rookie mistake I am making somewhere, or its system dependent and its just specific to my computer for some reason. If anyone has any insight, I would greatly appreciate it.

Adding screenshot of Tcl Version:

答: There is nothing wrong with your code. This behavior is system dependent. Menus are under the control of the OS rather than tkinter on OSX and Windows. </p>

Body:
Edit: OS is Windows 10 64 Bit

Ok, so I have googled my rear-end off on this one. I am building a simple tkinter app and upon setting it up and just generally messing around with options to add to it, my drop down from the menu created doesn't stay constrained inside the Frame.

import tkinter as tk

class Window(tk.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.main_window()
        self.widgets()

    # All main window parameters go here
    def main_window(self):
        self.master.title("Calculate Commission")
        self.master.geometry("800x600")
        self.pack()

    def widgets(self):
        main_menu = tk.Menu(self.master, tearoff=0)
        self.master.config(menu=main_menu)

        # Create File Menu and Drop Down
        file = tk.Menu(main_menu, tearoff=0)
        file.add_command(label="Save")
        file.add_command(label="Exit", command=exit)
        main_menu.add_cascade(label="File", menu=file)

        # Create Edit Menu and Drop Down
        edit = tk.Menu(main_menu, tearoff=0)
        edit.add_command(label="undo")
        main_menu.add_cascade(label="Edit", menu=edit)

main = tk.Tk()
comm_prog = Window(master=main)
main.mainloop()

Please see this attached screenshot to see what I am referring too:

I am fairly confident this may end up either of two ways. Either it's a rookie mistake I am making somewhere, or its system dependent and its just specific to my computer for some reason. If anyone has any insight, I would greatly appreciate it.

Adding screenshot of Tcl Version:


问:
Accessing the properties of an IEnumerable
I'm using TweetInvi to grab a bunch of tweets that match a specified hashtag. I do this with the following:

```<code>var matchingTweets = Search.SearchTweets(hashtag);
</code>```

This returns an IEnumerable (named ITweet, interface of Tweet), however I cannot create a List<> of Tweets, because Tweet is a static type.

I made, instead, a list of objects, using:

```<code>List<object> matches = matchingTweets.Cast<object>().ToList();
</code>```

However, although each member of the matchingTweets IEnumerable has a number of properties, I cannot access them using:

```<code>long tweetID = matches[i].<property>;
</code>```

Using matches[i].ToString() returns the tweet content, so how can I effectively cast the results in matchingTweets to a list, and subsequently access the properties of those list members? I would ideally like to avoid using dynamic.

答:
It makes sense you cannot access the properties. You cast it into object so you can only access the objects properties and methods (that like you said might have been overridden).

It should be fine to just access it like this:

```<code>List<ITweet> tweets = matchingTweets.Take(5).ToList();
</code>```

What you can do is project it to a new object of yours:

```<code>var tweets = matchingTweets.Select(item => new {
                                       property1 = item.property1,
                                       property2 = item.property2
                                   })
                           .Take(5).ToList();
</code>```

Then you will be able to access what you need. Now, if you need to share this data outside the scope of that function create a DTO object and initialize it instead of the anonymous type.

Depending on the size of the project and amount of effort usually it is in any case a good practice to create a layer of DTO objects when you interact with an external service like this. Then if their models changed you can contain your changes only to the DTOs.

If all you want are the ids of the first 5 then:

```<code>var ids = matchingTweets.Take(5).Select(item => item.id).ToList();
</code>```

Body:
I'm using TweetInvi to grab a bunch of tweets that match a specified hashtag. I do this with the following:

var matchingTweets = Search.SearchTweets(hashtag);

This returns an IEnumerable (named ITweet, interface of Tweet), however I cannot create a List<> of Tweets, because Tweet is a static type.

I made, instead, a list of objects, using:

List<object> matches = matchingTweets.Cast<object>().ToList();

However, although each member of the matchingTweets IEnumerable has a number of properties, I cannot access them using:

long tweetID = matches[i].<property>;

Using matches[i].ToString() returns the tweet content, so how can I effectively cast the results in matchingTweets to a list, and subsequently access the properties of those list members? I would ideally like to avoid using dynamic.

Body:
It makes sense you cannot access the properties. You cast it into object so you can only access the objects properties and methods (that like you said might have been overridden).

It should be fine to just access it like this:

List<ITweet> tweets = matchingTweets.Take(5).ToList();

What you can do is project it to a new object of yours:

var tweets = matchingTweets.Select(item => new {
                                       property1 = item.property1,
                                       property2 = item.property2
                                   })
                           .Take(5).ToList();

Then you will be able to access what you need. Now, if you need to share this data outside the scope of that function create a DTO object and initialize it instead of the anonymous type.

Depending on the size of the project and amount of effort usually it is in any case a good practice to create a layer of DTO objects when you interact with an external service like this. Then if their models changed you can contain your changes only to the DTOs.

If all you want are the ids of the first 5 then:

var ids = matchingTweets.Take(5).Select(item => item.id).ToList();


问:
Excel Count Unique Values From SUMPRODUCT
I have a sheet that is supposed to count the number of unique reservations an agent has done. It currently counts duplicates though and I need to only count unique ones.

Here is the formula being used in the sheet:

=SUMPRODUCT((Table_Query_from_db[client_code]=$B7)*(Table_Query_from_db[created_date_time]>=D$1)*(Table_Query_from_db[created_date_time]<D$1+1))

This counts the number of lines/records that show up for a specific person ($B7) for a specific date (D$1).

Here is the sample of the sheet:

As you can see B7 contains the agents number and D1 contains the date.

Here is the dataset for that specific agent on that specific date:

There is indeed 5 reservations - but only 3 unique ones.

How do I go about getting D7 in the first picture to come out as 3 instead of 5?

答:
Use this array formula:

```<code>=SUM(IF((Table_Query_from_db[client_code]=$B7)*(Table_Query_from_db[created_date_time]>=D$1)*(Table_Query_from_db[created_date_time]<D$1+1),1/COUNTIFS(Table_Query_from_db[reservation_number],Table_Query_from_db[reservation_number],Table_Query_from_db[client_code],$B7,Table_Query_from_db[created_date_time],">=" & D$1,Table_Query_from_db[created_date_time],"<" & D$1+1)))
</code>```

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

Body:
Use this array formula:

=SUM(IF((Table_Query_from_db[client_code]=$B7)*(Table_Query_from_db[created_date_time]>=D$1)*(Table_Query_from_db[created_date_time]<D$1+1),1/COUNTIFS(Table_Query_from_db[reservation_number],Table_Query_from_db[reservation_number],Table_Query_from_db[client_code],$B7,Table_Query_from_db[created_date_time],">=" & D$1,Table_Query_from_db[created_date_time],"<" & D$1+1)))

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.


问:
Will F# perform well when writing math functions for a C# program?
Does anyone know how well F# measures with regards to performance, compared to C#. I have a C# raytracer with a lot of vector manipulations, ray-collission algorithms etc. and thought they might be more easily expressed in F#. I'm not asking for how well F# is at expressing math problems, something which has been answered here, but rather if I should expect better or worse performance? As raytracing is very performance intensive, even small cases of poor performance can be a problem in the wrong places.

Edit:

It seems that there are already a lot of questions on the subject that I couldn't find (there are no results if you actually search for anything with the term 'F#'). One good point here was the following answer:

F# provides some performance-related
  features that can make a difference.

Firstly, the implementation of
  delegates on .NET is currently quite
  inefficient and, consequently, F# uses
  its own FastFunc type for
  high-performance first-class
  functions.

Secondly, F# uses .NET metadata to
  convey inline functions so that they
  can be exported across APIs and, of
  course, that can dramatically improve
  performance in certain circumstances.

Finally, pattern matching can be
  extremely laborious to express in C#
  because the language lacks pattern
  matching but it is almost impossible
  to maintain optimized C# code
  equivalent to many non-trivial pattern
  matches. In contrast, the F# compiler
  aggressively optimizes pattern matches
  during compilation.

Conversely, the C# compiler is better
  at optimizing loops using IEnumerables
  and is better at optimizing
  computations over value types (e.g.
  complex arithmetic).

Cheers, Jon Harrop.

答: In fact, in theory, an x86 machine can only execute x86 assembly which is of an imperative nature, therefore, theoretically it's possible to achieve the performance of a functional language imperatively. So you can write C# programs that are equal or better than their F# counterparts. The keyword here is can. It doesn't mean all C# programs are better than F# programs or anything like that. Generally, F# performance is very acceptable in most problems. There are some cases where F# performance lags too much behind C#, but generally, it's OK for most applications. However, if you want to have fine-grained control on what your code actually does, functional languages are not for you. You have more optimization opportunity in C# than you have in F#. By the way, by F#, I don't mean writing imperative code, but normal functional approach (if you want to write code imperatively, I don't think F# makes much sense).

OwnerDisplayName: Morten Christiansen

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: Mehrdad Afshari