问:
Sort list of alphanumeric strings
I have a list of strings, each of which will something like ';2234661;E3006345_2234661_FRONT_Image_Container;\n' that I need to sort. Each string will start with a semi-colon and different numbers, but I need them all to be sorted according to the image angle (ex. FRONT, BACK, LEFT) in a non-alphabetical order following this ranking:
FRONT
BACK
LEFT
RIGHT
INGREDIENTS
INSTRUCTIONS
INFO
NUTRITION
PRODUCT

Example Input:

```<code>[';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']
</code>```

Desired Output

```<code>[';2234661;FRONT;', ';2234661;BACK;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;INGREDIENTS;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;', ';2234661;NUTRITION;', ';2234661;PRODUCT;']
</code>```

Here is my code, based off of the solution to a similar issue I found here on stackexchange. However, it returns the error "ValueError: substring not found

```<code>galleryImages = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

alphabet = 'FBLRINP'

newGallery = sorted(galleryImages, key=lambda word: [alphabet.index(c) for c in word])

print(newGallery)
</code>```

Title: Sort list of alphanumeric strings

Body:
I have a list of strings, each of which will something like ';2234661;E3006345_2234661_FRONT_Image_Container;\n' that I need to sort. Each string will start with a semi-colon and different numbers, but I need them all to be sorted according to the image angle (ex. FRONT, BACK, LEFT) in a non-alphabetical order following this ranking:
FRONT
BACK
LEFT
RIGHT
INGREDIENTS
INSTRUCTIONS
INFO
NUTRITION
PRODUCT

Example Input:

[';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

Desired Output

[';2234661;FRONT;', ';2234661;BACK;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;INGREDIENTS;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;', ';2234661;NUTRITION;', ';2234661;PRODUCT;']

Here is my code, based off of the solution to a similar issue I found here on stackexchange. However, it returns the error "ValueError: substring not found

galleryImages = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

alphabet = 'FBLRINP'

newGallery = sorted(galleryImages, key=lambda word: [alphabet.index(c) for c in word])

print(newGallery)

Body:
data = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']
keys = ['FRONT', 'BACK', 'LEFT', 'RIGHT', 'INGREDIENTS', 'INSTRUCTIONS', 'INFO', 'NUTRITION', 'PRODUCT']

res = [key for x in keys for key in data if key.split(';')[2] == x]

Output:

[';2234661;FRONT;', ';2234661;BACK;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;INGREDIENTS;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;', ';2234661;NUTRITION;', ';2234661;PRODUCT;']


来源: stackexchange

问:
How can I turn this jquery into a function?
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the href> tag somewhere.

html code

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink1">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink2">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink3">Link 3</a></li>
</ul>
</code>```

jquery

```<code>$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});
</code>```

答:
Add a data attribute called data-src:

```<code><a href="linkpage.htm" class="newslink" data-src="1.png">Link 1</a>
</code>```

jQuery:

```<code>$("a.newslink").bind("mouseover", function() {
    $("img#storyimg").attr("src", $(this).data("src"));
});
</code>```

Works with jQuery 1.5+.

ContentLicense: CC BY-SA 3.0

Body:
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the  tag somewhere.

html code

Link 1

Link 2

Link 3

jquery

$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});

Body:
Add a data attribute called data-src:

<a href="linkpage.htm" class="newslink" data-src="1.png">Link 1</a>

jQuery:

$("a.newslink").bind("mouseover", function() {
    $("img#storyimg").attr("src", $(this).data("src"));
});

Works with jQuery 1.5+.


问:
My VB code appends two nodes instead of only one
I have the following XML file

<?xml version="1.0"?>
<Config>
    <ImgFileName>W10-00</ImgFileName>
    <Index>1</Index>
    <Diag>0</Diag>
</Config>
```

<p>And I want to add a new node 'CanSS' and make the value = '1'.</p>

<p>This is the code I am calling</p>

<pre class="lang-vb prettyprint-override"><code>Private Sub AddNode(ByVal CFGFile As String, ByVal Node As String, ByVal ValStr As String)
    Dim docXMLDOM As DOMDocument
    Dim nodeRoot As IXMLDOMElement
    Dim nodeNewElement As IXMLDOMElement

    ' Initialize the document model
    docXMLDOM = New DOMDocument

    ' Open the XML document
    docXMLDOM.load(CFGFile)

    ' Get a reference to the root node
    nodeRoot = docXMLDOM.documentElement

    nodeNewElement = docXMLDOM.createElement(Node)
    nodeNewElement.text = ValStr
    nodeRoot.appendChild(nodeNewElement)

    ' Save the file
    docXMLDOM.save(CFGFile)

    docXMLDOM = Nothing
End Sub
</code>```

which changes my XML to this

    <?xml version="1.0"?>
<Config>
    <ImgFileName>W10-00</ImgFileName>
    <Index>1</Index>
    <Diag>0</Diag>
<CanSS>1</CanSS><CanSS>1</CanSS></Config>
```

Can anyone see where I'm going wrong?

答:
Since this is VB you can make use of XElement and XElement literals.

Private Sub AddNode(CFGFile As String, Node As XElement, ValStr As String)
    'to use this method, note the use of the literal
    '  AddNode("PATH to xml", <CanSS/>, "The value")
    Dim xe As XElement
    Try
        xe = XElement.Load(CFGFile)
        Dim nd As XElement = New XElement(Node)
        nd.Value = ValStr
        xe.Add(nd)
        xe.Save(CFGFile)
    Catch ex As Exception
        'todo Error
    End Try
End Sub
```

ContentLicense: CC BY-SA 4.0

Body:
I have the following XML file

<?xml version="1.0"?>
<Config>
    <ImgFileName>W10-00</ImgFileName>
    <Index>1</Index>
    <Diag>0</Diag>
</Config>

And I want to add a new node 'CanSS' and make the value = '1'.

This is the code I am calling

Private Sub AddNode(ByVal CFGFile As String, ByVal Node As String, ByVal ValStr As String)
    Dim docXMLDOM As DOMDocument
    Dim nodeRoot As IXMLDOMElement
    Dim nodeNewElement As IXMLDOMElement

    ' Initialize the document model
    docXMLDOM = New DOMDocument

    ' Open the XML document
    docXMLDOM.load(CFGFile)

    ' Get a reference to the root node
    nodeRoot = docXMLDOM.documentElement

    nodeNewElement = docXMLDOM.createElement(Node)
    nodeNewElement.text = ValStr
    nodeRoot.appendChild(nodeNewElement)

    ' Save the file
    docXMLDOM.save(CFGFile)

    docXMLDOM = Nothing
End Sub

which changes my XML to this

    <?xml version="1.0"?>
<Config>
    <ImgFileName>W10-00</ImgFileName>
    <Index>1</Index>
    <Diag>0</Diag>
<CanSS>1</CanSS><CanSS>1</CanSS></Config>

Can anyone see where I'm going wrong?


问:
Best way to make decorator for unique class instances Python
I am working with Python code that calls into C wrappers, but the C code is very buggy (and I have no other alternative) and causes a segfault when a Python object managed in C goes out of scope, so I have to keep references to each object created.

Is there any good way to make an ergonomic "unique" wrapper where each class can only have one instance per set of constructor arguments, e.g.

@unique
class Test:
    cls_val = 0
    def __init__(self, val):
        self.val = val

a = Test(1)
b = Test(1)

assert a is b

c = Test(2)
d = Test(2)

assert c is not b and c is not a
assert c is d
```

<p>I've made this decorator, but it prevents any @unique-decorated class from being used as a base class (constructing an instance of the derived class calls the <code>__new__</code> of the decorator).</p>

<pre class="lang-py prettyprint-override"><code>def unique(unique_cls):
    class Unique:
        instances = {}
        unique_class = unique_cls
        def __new__(cls, *args, **kwargs):
            if not Unique.instances.get(
                (
                     cls.unique_class,
                     f_args := frozenset(args),
                     f_kwargs := frozenset(kwargs),
                )
            ):
                Unique.instances[
                     (Unique.unique_class, f_args, f_kwargs)
                ] = Unique.unique_class(*args, **kwargs)
            return Unique.instances[(Unique.unique_class, f_args, f_kwargs)]
        def __getattr__(self, name):
            # Overloaded to get class attributes working for decorated classes
            return object.__getattribute__(Unique.unique_class, name)
    return Unique
</code>```

答:
You can use functools.lru_cache to store all instances in a cache, and set no limit on the cache size. When you call the constructor, you'll get a new instance, and it will be stored in the cache. Then whenever you call the constructor with the same arguments again, you'll get the cached instance. This also means that every object always has a reference from the cache.

from functools import lru_cache

@lru_cache(maxsize=None)
class Test:
    def __init__(self, val):
        self.val = val
```

<p>Demonstration:</p>

<pre class="lang-py prettyprint-override"><code>>>> a = Test(1)
>>> a2 = Test(1)
>>> a is a2
True
>>> b = Test(2)
>>> b2 = Test(2)
>>> b is b2
True
>>> a is b
False
</code>```

If you need to be able to subclass Test (or really, do anything with Test itself except create instances), then you can override __new__ and apply the decorator there. This works because cls is an argument to __new__, so the cache will distinguish between different instances by their class as well as by their __init__ arguments.

class Test:
    @lru_cache(maxsize=None)
    def __new__(cls, *args, **kwargs):
        return object.__new__(cls)
    def __init__(self, val):
        self.val = val
```

<p>Demonstration:</p>

<pre class="lang-py prettyprint-override"><code>>>> Test(1) is Test(1)
True
>>> Test(1) is Test(2)
False
>>> class SubTest(Test): pass
...
>>> Test(1) is SubTest(1)
False
>>> SubTest(1) is SubTest(1)
True
</code>```

Body:
I am working with Python code that calls into C wrappers, but the C code is very buggy (and I have no other alternative) and causes a segfault when a Python object managed in C goes out of scope, so I have to keep references to each object created.

Is there any good way to make an ergonomic "unique" wrapper where each class can only have one instance per set of constructor arguments, e.g.

@unique
class Test:
    cls_val = 0
    def __init__(self, val):
        self.val = val

a = Test(1)
b = Test(1)

assert a is b

c = Test(2)
d = Test(2)

assert c is not b and c is not a
assert c is d

I've made this decorator, but it prevents any @unique-decorated class from being used as a base class (constructing an instance of the derived class calls the __new__ of the decorator).

def unique(unique_cls):
    class Unique:
        instances = {}
        unique_class = unique_cls
        def __new__(cls, *args, **kwargs):
            if not Unique.instances.get(
                (
                     cls.unique_class,
                     f_args := frozenset(args),
                     f_kwargs := frozenset(kwargs),
                )
            ):
                Unique.instances[
                     (Unique.unique_class, f_args, f_kwargs)
                ] = Unique.unique_class(*args, **kwargs)
            return Unique.instances[(Unique.unique_class, f_args, f_kwargs)]
        def __getattr__(self, name):
            # Overloaded to get class attributes working for decorated classes
            return object.__getattribute__(Unique.unique_class, name)
    return Unique

Body:
You can use functools.lru_cache to store all instances in a cache, and set no limit on the cache size. When you call the constructor, you'll get a new instance, and it will be stored in the cache. Then whenever you call the constructor with the same arguments again, you'll get the cached instance. This also means that every object always has a reference from the cache.

from functools import lru_cache

@lru_cache(maxsize=None)
class Test:
    def __init__(self, val):
        self.val = val

Demonstration:

>>> a = Test(1)
>>> a2 = Test(1)
>>> a is a2
True
>>> b = Test(2)
>>> b2 = Test(2)
>>> b is b2
True
>>> a is b
False

If you need to be able to subclass Test (or really, do anything with Test itself except create instances), then you can override __new__ and apply the decorator there. This works because cls is an argument to __new__, so the cache will distinguish between different instances by their class as well as by their __init__ arguments.

class Test:
    @lru_cache(maxsize=None)
    def __new__(cls, *args, **kwargs):
        return object.__new__(cls)
    def __init__(self, val):
        self.val = val

Demonstration:

>>> Test(1) is Test(1)
True
>>> Test(1) is Test(2)
False
>>> class SubTest(Test): pass
...
>>> Test(1) is SubTest(1)
False
>>> SubTest(1) is SubTest(1)
True


问:
How to Create a view that shows all existing attributes DOORS in all formal modules under a single project?
I have a project under which there are 50+ formal modules in IBM DOORS,

I want to create a single view for all modules ( As default view )
This view should display all the attributes that are available for that particular module when I open it.

And the number of attributes in some modules vary.
If anyone in stack-overflow knows a way on this, It would be really helpful!

答:
Before anything, you should probably be aware that there is a maximum number of attributes that can be loaded into a view. You can check out this thread for more information regarding max columns:
https://www.ibm.com/developerworks/community/forums/html/topic?id=1861480b-7aa0-43b2-bf77-be677f5f778e

Now as for how to do this. If you're looking for an automated solution using DXL here's some sample code that you can modify for your purposes. The current code will add object-level attributes that aren't system attributes to the current view of the module you run this code from.

```<code>AttrDef ad
Module m = current Module
string sAttrName
int count = 0
Column col

for col in m do {count++}

for ad in m do
{
   if ((ad.object) && (!ad.system))
   {
      sAttrName = ad.name
      col = insert (column count)
      attribute(col, sAttrName)
      width(col, 200)
      count++
   }
}
</code>```

Note: This code will only generate a view with all attributes in the module it is run from, it will not loop through all modules in a project or save the view.

To loop through a project and get all modules you'll need to create a recursive function using for itemRef in folder do {...}. Something like the following:

```<code>Folder f = current Folder

void recurseFolder(Folder f)
{
    Item iRef

    for iRef in f do
    {
        if (type(iRef) == "Formal")
            (call your create views function here with parameter iRef)
        else if (type(iRef) == "Folder" || type(iRef) == "Project")
            recurseFolder(folder(iRef))
    }
}

recurseFolder(f)
</code>```

And then if you need additional code to save the view, you'll have to add appropriate code for that too using save(View v). You can look up additional information pertaining to setting view preferences and saving them in the DXL Reference Manual.

Body:
Before anything, you should probably be aware that there is a maximum number of attributes that can be loaded into a view. You can check out this thread for more information regarding max columns:
https://www.ibm.com/developerworks/community/forums/html/topic?id=1861480b-7aa0-43b2-bf77-be677f5f778e

Now as for how to do this. If you're looking for an automated solution using DXL here's some sample code that you can modify for your purposes. The current code will add object-level attributes that aren't system attributes to the current view of the module you run this code from.

AttrDef ad
Module m = current Module
string sAttrName
int count = 0
Column col

for col in m do {count++}

for ad in m do
{
   if ((ad.object) && (!ad.system))
   {
      sAttrName = ad.name
      col = insert (column count)
      attribute(col, sAttrName)
      width(col, 200)
      count++
   }
}

Note: This code will only generate a view with all attributes in the module it is run from, it will not loop through all modules in a project or save the view.

To loop through a project and get all modules you'll need to create a recursive function using for itemRef in folder do {...}. Something like the following:

Folder f = current Folder

void recurseFolder(Folder f)
{
    Item iRef

    for iRef in f do
    {
        if (type(iRef) == "Formal")
            (call your create views function here with parameter iRef)
        else if (type(iRef) == "Folder" || type(iRef) == "Project")
            recurseFolder(folder(iRef))
    }
}

recurseFolder(f)

And then if you need additional code to save the view, you'll have to add appropriate code for that too using save(View v). You can look up additional information pertaining to setting view preferences and saving them in the DXL Reference Manual.


问:
STDOUT and STDERR out of order
I have a perl script which writes messages to STDOUT and STDERR (via print/croak statements), but I also redirect the STDOUT and STDERR to a logfile:

```<code>File::Tee::tee STDOUT, ">>", "$logFile" ;
File::Tee::tee STDERR, ">>", "$logFile" ;
</code>```

Now the output logfile has messages from STDOUT and STDERR displayed out of order. Also the actual output on terminal is also out of order. I have tried flushing the buffers (as recommended here: https://perl.plover.com/FAQs/Buffering.html) but it doesn't help:

```<code>select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
</code>```

Does anyone know what I must do to see the output in order (I also tried additionally flushing the filehandle corresponding to $logfile, but its still the same)?

EDIT:

Thanks to all of you who have replied. A lot of the discussion over this ended up in comments, so I am going to list the few things which I tried based on feedback from all of you.

I already was flushing the STDOUT and STDERR before I used File::Tee. As @jimtut suspected, File::Tee was indeed the culprit - removing it restored the ordering on console. But I did want to redirect the STDOUT and STDERR.

@mob suggested using IO::Tee instead, but I haven't fully understood how to make that work they way I want in my code.

@briandfoy pointed out that there isn't a reliable way to ensure 2 seperate filehandles are seen in the correct order in realtime and also suggested using a logging routine which is the only place which can write to STDOUT/STDERR. @zimd further pointed out that File::Tee uses fork which is the heart of the issue since 2 processes cannot guarantee any order on output.

Since the File::Tee is to blame, I attempted to remove this from the code. I updated my logger function to print to STDOUT/STDERR as well as to additionally print to $log filehandle. Further for capturing the warns in the log, I did the following:

```<code>sub warning_handler {
  my $msg = $_[0] ;
  print STDERR $msg ;
  print $log $msg if defined $log ;
}
$SIG{__WARN__} = \&warning_handler ;
</code>```

This worked great for all of the code under my control. Everything was printing in order now both on console and logfile. However I realized I can't use this solution since I was also calling someone else's perl packages for some functionality and clearly I couldn't intercept the print/croak etc which wrote to STDOUT/STDERR within the 'off the shelf' package. So right now, I don't have a good solution. However I suspect if I can find someway to intercept STDOUT/STDERR within perl, I might be able to get what I need.

EDIT2:
I added my own answer which is probably the closest I got to solving the problem by modifying mob's solution of using IO::Tee instead of File::Tee, but even this misses some messages (though it fixes ordering).

EDIT3:
Finally found the 'solution'

```<code>use IO::Tee ;
use Capture::Tiny qw(capture);
...
...
select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
open (my $log, ">", $logfilename) ;
*REALSTDOUT = *STDOUT ;
*REALSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*REALSTDOUT, $log);
*STDERR = IO::Tee->new(\*REALSTDERR, $log);

# Regular Perl code here which sends output to STDOUT/STDERR
...
...
# system calls / calls to .so needs to be catpured
&log_streams(sub { &some_func_which_calls_shared_object() ; }) ;

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments
    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print STDOUT $out;
    }
    if ($err) {
        print STDERR $err;
    }
}
</code>```

The use of IO::Tee ensures all perl generated outputs to console also go to logfile, and this happens immediately thereby updating the log and console in realtime. Since IO::Tee is changing the meaning of STDOUT/STDERR filehandles to now refer to the teed handles, it can only intercept stdio from perl statements, it misses sys calls since they bypass perl's STDOUT/STDERR handles. So we capture the syscall output and then use the log_streams routine to forward it to the now aliased STDOUT/STDERR streams. This creates a delay in the system call generated output showing up in log/terminal but there is no delay for perl generated output - i.e. best of both worlds. Do note that the ordering of stderr and stdout generated by an invocation of subroutine some_func_which_calls_shared_object is not preserved since in the log_streams routine, we first print to STDOUT and then to STDERR - as long as the system call is atomic and doesn't do much in terms of interleaving stdout/stderr messages we should be ok.
Appreciate solutions from briandfoy, mob and zimd whose answers I combined to arrive at this solution! Never thought it would require to go through this detail for what seems a very simple problem.

答:
With two separate file handles, there's no contract or guarantee that you'll see them in real time. Various settings and buffers affect that, which is why you see the auto flush stuff ($|). It's the same idea for files or the terminal.

Realize this is an architectural issue rather than a syntactic one. You have two things competing for the same resource. That usually ends in tears. I hesitate to suggest a solution when I don't know what the problem is, but consider having whatever is trying to write to STDOUT or STDERR write to some sort of message broker that collects all the messages and is the only thing that writes to the final (shared) destination. For example, things that want to add entries to the syslog don't write to the syslog; they send messages to the thing that writes to the syslog.

A more Perly example: in Log4perl, you don't write to the final destinations. You simply log a message and the logger is the single thing figures out how to handle it. When I want this sort of behavior with the module, I don't use output facilities directly:

```<code>debug( "Some debug message" );

sub debug {
    my $message = shift;
    output( "DEBUG: $message" );
    }

sub output { # single thing that can output message
    ...
    }
</code>```

Then do whatever you need to do in output.

But, you can't always control that in other things that are also trying to output things. Perl let's you get around this by redefining what warn and friends do by putting a coderef in $SIG{__WARN__}. You can capture warning messages and do whatever you like with them (such as sending them to standard output). Beyond that is black magic that reopens STDERR onto something you can control. It's not that bad and it's isolated in one place.

At some point where another person doesn't want merged output, and the intrusive solutions make it impossible to separate them. I'd much prefer flexibility than hard-coded constraint. If I want just the errors, I want a way to get just the errors. There are many other sorts of workarounds, such as wrappers that collect both output streams (so, not at all intrusive) and various command-redirections.

Title: STDOUT and STDERR out of order

Body:
I have a perl script which writes messages to STDOUT and STDERR (via print/croak statements), but I also redirect the STDOUT and STDERR to a logfile:

File::Tee::tee STDOUT, ">>", "$logFile" ;
File::Tee::tee STDERR, ">>", "$logFile" ;

Now the output logfile has messages from STDOUT and STDERR displayed out of order. Also the actual output on terminal is also out of order. I have tried flushing the buffers (as recommended here: https://perl.plover.com/FAQs/Buffering.html) but it doesn't help:

select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;

Does anyone know what I must do to see the output in order (I also tried additionally flushing the filehandle corresponding to $logfile, but its still the same)?

EDIT:

Thanks to all of you who have replied. A lot of the discussion over this ended up in comments, so I am going to list the few things which I tried based on feedback from all of you.

I already was flushing the STDOUT and STDERR before I used File::Tee. As @jimtut suspected, File::Tee was indeed the culprit - removing it restored the ordering on console. But I did want to redirect the STDOUT and STDERR.

@mob suggested using IO::Tee instead, but I haven't fully understood how to make that work they way I want in my code.

@briandfoy pointed out that there isn't a reliable way to ensure 2 seperate filehandles are seen in the correct order in realtime and also suggested using a logging routine which is the only place which can write to STDOUT/STDERR. @zimd further pointed out that File::Tee uses fork which is the heart of the issue since 2 processes cannot guarantee any order on output.

Since the File::Tee is to blame, I attempted to remove this from the code. I updated my logger function to print to STDOUT/STDERR as well as to additionally print to $log filehandle. Further for capturing the warns in the log, I did the following:

sub warning_handler {
  my $msg = $_[0] ;
  print STDERR $msg ;
  print $log $msg if defined $log ;
}
$SIG{__WARN__} = \&warning_handler ;

This worked great for all of the code under my control. Everything was printing in order now both on console and logfile. However I realized I can't use this solution since I was also calling someone else's perl packages for some functionality and clearly I couldn't intercept the print/croak etc which wrote to STDOUT/STDERR within the 'off the shelf' package. So right now, I don't have a good solution. However I suspect if I can find someway to intercept STDOUT/STDERR within perl, I might be able to get what I need.

EDIT2:
I added my own answer which is probably the closest I got to solving the problem by modifying mob's solution of using IO::Tee instead of File::Tee, but even this misses some messages (though it fixes ordering).

EDIT3:
Finally found the 'solution'

use IO::Tee ;
use Capture::Tiny qw(capture);
...
...
select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
open (my $log, ">", $logfilename) ;
*REALSTDOUT = *STDOUT ;
*REALSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*REALSTDOUT, $log);
*STDERR = IO::Tee->new(\*REALSTDERR, $log);

# Regular Perl code here which sends output to STDOUT/STDERR
...
...
# system calls / calls to .so needs to be catpured
&log_streams(sub { &some_func_which_calls_shared_object() ; }) ;

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments
    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print STDOUT $out;
    }
    if ($err) {
        print STDERR $err;
    }
}

The use of IO::Tee ensures all perl generated outputs to console also go to logfile, and this happens immediately thereby updating the log and console in realtime. Since IO::Tee is changing the meaning of STDOUT/STDERR filehandles to now refer to the teed handles, it can only intercept stdio from perl statements, it misses sys calls since they bypass perl's STDOUT/STDERR handles. So we capture the syscall output and then use the log_streams routine to forward it to the now aliased STDOUT/STDERR streams. This creates a delay in the system call generated output showing up in log/terminal but there is no delay for perl generated output - i.e. best of both worlds. Do note that the ordering of stderr and stdout generated by an invocation of subroutine some_func_which_calls_shared_object is not preserved since in the log_streams routine, we first print to STDOUT and then to STDERR - as long as the system call is atomic and doesn't do much in terms of interleaving stdout/stderr messages we should be ok.
Appreciate solutions from briandfoy, mob and zimd whose answers I combined to arrive at this solution! Never thought it would require to go through this detail for what seems a very simple problem.

Body:
With two separate file handles, there's no contract or guarantee that you'll see them in real time. Various settings and buffers affect that, which is why you see the auto flush stuff ($|). It's the same idea for files or the terminal.

Realize this is an architectural issue rather than a syntactic one. You have two things competing for the same resource. That usually ends in tears. I hesitate to suggest a solution when I don't know what the problem is, but consider having whatever is trying to write to STDOUT or STDERR write to some sort of message broker that collects all the messages and is the only thing that writes to the final (shared) destination. For example, things that want to add entries to the syslog don't write to the syslog; they send messages to the thing that writes to the syslog.

A more Perly example: in Log4perl, you don't write to the final destinations. You simply log a message and the logger is the single thing figures out how to handle it. When I want this sort of behavior with the module, I don't use output facilities directly:

debug( "Some debug message" );

sub debug {
    my $message = shift;
    output( "DEBUG: $message" );
    }

sub output { # single thing that can output message
    ...
    }

Then do whatever you need to do in output.

But, you can't always control that in other things that are also trying to output things. Perl let's you get around this by redefining what warn and friends do by putting a coderef in $SIG{__WARN__}. You can capture warning messages and do whatever you like with them (such as sending them to standard output). Beyond that is black magic that reopens STDERR onto something you can control. It's not that bad and it's isolated in one place.

At some point where another person doesn't want merged output, and the intrusive solutions make it impossible to separate them. I'd much prefer flexibility than hard-coded constraint. If I want just the errors, I want a way to get just the errors. There are many other sorts of workarounds, such as wrappers that collect both output streams (so, not at all intrusive) and various command-redirections.


问:
Running Nightwatch without Selenium Server in a Docker container
I read that:

Starting with Nightwatch 1.0, using Selenium Standalone Server is no longer required, nor is it recommended for testing against a single browser...

But I'm unable to find any documentation about interacting directly with the WebDriver and especially to run Nightwatch+Chromedriver in a Docker container.

Any specific help?

答:
I haven't tried this myself but have found the below discussion and docs useful.

https://github.com/nightwatchjs/nightwatch/issues/1270

https://medium.com/@kenfehling/ui-testing-with-nightwatch-js-headless-chrome-and-docker-part-1-f0ce2e8a23a1

If you consider using selenium grid,

https://github.com/mycargus/nightwatch-docker-grid

Cheers!


问:
How do I change the _Click() event on a MS Access Form?
I am hoping to be able to streamline my UI.  I want to have a set of command buttons change the _On_Click() event based on a user selection.  For example:

Main topic selections: cmd1:"Membership Reports", cmd2: "Administration Reports", cmd3: "Other Reports - TBD"

If the user selects cmd1 then the subtopic buttons properties change to allow the user to open reports in that category.

Sub Topic Selections: cmd4: "All Members", cmd5: "Active Members", etc.

If the user selects cmd2: then the on_Click event would change to open reports in the "Administration Reports" group.

Thanks in advance for your help.

答:
I would use 3 main Toggle Buttons and put hem into an Option group frame (Let's call it FrameMain). Set the Option Value for the buttons as 1,2,3. Create as many regular buttons a you have sub topics (let's call them cmd1_1, cmd1_2, cmd2_1....) and set theirs property Visible to False and Tag to Sub. Now create event FrameMain_AfterUpdate:

Private Sub FrameMain_AfterUpdate()
    Dim ctl As Control
    For Each ctl In Me.Controls
        If ctl.Tag = "Sub" Then
            ctl.Visible = False
        End If
    Next
    Select Case Me.FrameMain
        Case 1
            cmd1_1.Visible = True
            cmd1_2.Visible = True
        Case 2
            cmd2_1.Visible = True
            cmd2_2.Visible = True
        Case 3
            cmd3_1.Visible = True
            cmd3_2.Visible = True
    End Select
End Sub
```

You can create now On_Click() event for all your sub-buttons to open the report you want.

You can also use a Switch board (search the Internet how to create it).

Body:
I would use 3 main Toggle Buttons and put hem into an Option group frame (Let's call it FrameMain). Set the Option Value for the buttons as 1,2,3. Create as many regular buttons a you have sub topics (let's call them cmd1_1, cmd1_2, cmd2_1....) and set theirs property Visible to False and Tag to Sub. Now create event FrameMain_AfterUpdate:

Private Sub FrameMain_AfterUpdate()
    Dim ctl As Control
    For Each ctl In Me.Controls
        If ctl.Tag = "Sub" Then
            ctl.Visible = False
        End If
    Next
    Select Case Me.FrameMain
        Case 1
            cmd1_1.Visible = True
            cmd1_2.Visible = True
        Case 2
            cmd2_1.Visible = True
            cmd2_2.Visible = True
        Case 3
            cmd3_1.Visible = True
            cmd3_2.Visible = True
    End Select
End Sub

You can create now On_Click() event for all your sub-buttons to open the report you want.

You can also use a Switch board (search the Internet how to create it).


问:
Firebase Authentication - How To Deal With Delay
I have set-up my Firebase project as per the video from David East, as below with this in my app.js file. I have removed my config parameters.

#topName refers to an element on the page that displays the authenticated user's username. Unfortunately what happens is that someone logs in, or is logged in and goes to the page, it initially displays guest and then after some time it switches to the username of that user. This is quick (<500ms) but causes the page to render twice which is confusing.

How can I avoid this, do I need to store something in local storage?

```<code>    (function() {

    //Initialise Firebase
    var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: ""
    };

    firebase.initializeApp(config);

    //Add a realtime listener.
    firebase.auth().onAuthStateChanged(firebaseUser => {
        if (firebaseUser) {
            console.log(firebaseUser);
            $('#topName').text(firebaseUser.email);
        }
        else
        {
            console.log('not logged in');
            $('#topName').text("Guest");
        }
    });

}());
</code>```

答:
i solved this with the next code, just show a loader component while waiting for auth.onAuthStateChanged, the var has three values null, true and false.</p>

```<code>const Routes = () => {
  const dispatch = useDispatch();

  // firebase observer for user auth
  useEffect(() => {
    let unsubscribeFromAuth = null;
    unsubscribeFromAuth = auth.onAuthStateChanged(user => {
      if (user) {
        dispatch(setCurrentUser(user));
      } else {
        dispatch(clearCurrentUser());
      }
    });
    return () => unsubscribeFromAuth();
  }, [dispatch]);

  return (
    <Switch>
      <Route exact path="/" component={Dashboard} />
      <Route path="/signin">
        <SignIn />
      </Route>
      <ProtectedRoute path="/protected">
        <Dashboard />
      </ProtectedRoute>
      <Route path="*">
        <NoMatch />
      </Route>
    </Switch>
  );
};

const ProtectedRoute = ({ children, ...rest }) => {
  const currentUser = useSelector(state => state.auth.currentUser);
  if (currentUser === null) {
    // handle the delay in firebase auth info if current user is null show a loader if is false user sign out
    // TODO create a loading nice component
    return <h1>Loading</h1>;
  }
  return (
    <Route
      // eslint-disable-next-line react/jsx-props-no-spreading
      {...rest}
      render={({ location }) =>
        currentUser ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: '/signin',
              state: { from: location }
            }}
          />
        )
      }
    />
  );
};

export default Routes;
</code>```

Body:
I have set-up my Firebase project as per the video from David East, as below with this in my app.js file. I have removed my config parameters.

#topName refers to an element on the page that displays the authenticated user's username. Unfortunately what happens is that someone logs in, or is logged in and goes to the page, it initially displays guest and then after some time it switches to the username of that user. This is quick (<500ms) but causes the page to render twice which is confusing.

How can I avoid this, do I need to store something in local storage?

    (function() {

    //Initialise Firebase
    var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: ""
    };

    firebase.initializeApp(config);

    //Add a realtime listener.
    firebase.auth().onAuthStateChanged(firebaseUser => {
        if (firebaseUser) {
            console.log(firebaseUser);
            $('#topName').text(firebaseUser.email);
        }
        else
        {
            console.log('not logged in');
            $('#topName').text("Guest");
        }
    });

}());

Body:
i solved this with the next code, just show a loader component while waiting for auth.onAuthStateChanged, the var has three values null, true and false.

const Routes = () => {
  const dispatch = useDispatch();

  // firebase observer for user auth
  useEffect(() => {
    let unsubscribeFromAuth = null;
    unsubscribeFromAuth = auth.onAuthStateChanged(user => {
      if (user) {
        dispatch(setCurrentUser(user));
      } else {
        dispatch(clearCurrentUser());
      }
    });
    return () => unsubscribeFromAuth();
  }, [dispatch]);

  return (
    <Switch>
      <Route exact path="/" component={Dashboard} />
      <Route path="/signin">
        <SignIn />
      </Route>
      <ProtectedRoute path="/protected">
        <Dashboard />
      </ProtectedRoute>
      <Route path="*">
        <NoMatch />
      </Route>
    </Switch>
  );
};

const ProtectedRoute = ({ children, ...rest }) => {
  const currentUser = useSelector(state => state.auth.currentUser);
  if (currentUser === null) {
    // handle the delay in firebase auth info if current user is null show a loader if is false user sign out
    // TODO create a loading nice component
    return <h1>Loading</h1>;
  }
  return (
    <Route
      // eslint-disable-next-line react/jsx-props-no-spreading
      {...rest}
      render={({ location }) =>
        currentUser ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: '/signin',
              state: { from: location }
            }}
          />
        )
      }
    />
  );
};

export default Routes;


问:
Printing only a part of an array
I have something I'm working on where I'm trying to display a tracking number from an order in a table on a "My  Account" page. I was able to get everything and I'm so close, but I can't seem to figure out arrays with my limited knowledge of PHP.

```<code>    if ( $value = $order->get_meta( '_wc_shipment_tracking_items' ) ) {
        print_r( $value );
    }
</code>```

And that displays:

```<code>Array (
    [0] => Array (
        [tracking_provider] => fedex,
        [tracking_number] => 99999999999,
        [date_shipped] => 1581552000,
        [tracking_id] => 6c382ea3f6d8b1e217599eb95dda7dab
    )
)
</code>```

How would I be able to display just that tracking number, and better yet, could I get it as a link to track it on fedex?

答: echo $value[0]['tracking_number']</p>

Title: Printing only a part of an array

Body:
I have something I'm working on where I'm trying to display a tracking number from an order in a table on a "My  Account" page. I was able to get everything and I'm so close, but I can't seem to figure out arrays with my limited knowledge of PHP.

    if ( $value = $order->get_meta( '_wc_shipment_tracking_items' ) ) {
        print_r( $value );
    }

And that displays:

Array (
    [0] => Array (
        [tracking_provider] => fedex,
        [tracking_number] => 99999999999,
        [date_shipped] => 1581552000,
        [tracking_id] => 6c382ea3f6d8b1e217599eb95dda7dab
    )
)

How would I be able to display just that tracking number, and better yet, could I get it as a link to track it on fedex?

Body: echo $value[0]['tracking_number']


问:
How to remove space bottom mat-form-field

I use angular 7 with angular material and i want to remove the space bottom as you can see. I tried many way but no sucess.

答:
You can add height:4em to mat-form-field as such:</p>

```<code>    <mat-form-field
        class="height-4em"
        appearance="outline"
        >
        <mat-label>Favorite food</mat-label>
        <input matInput placeholder="Ex. Pizza" value="Sushi">
    </mat-form-field>
</code>```

Body:
You can add height:4em to mat-form-field as such:

    <mat-form-field
        class="height-4em"
        appearance="outline"
        >
        <mat-label>Favorite food</mat-label>
        <input matInput placeholder="Ex. Pizza" value="Sushi">
    </mat-form-field>


问:
Azure Stack On-premise Deployment
I cant seem to understand from reading the relevant material in the internet if it is even possible deploying and installing the azure stack deployment kit for on-premise if my environment will; ALWAYS not connected to the internet AT ALL, even at the installation phase?</p>

答:
You can install ASDK disconnected, however it is recommended to install connected.

https://learn.microsoft.com/en-us/azure-stack/asdk/asdk-install?view=azs-1910

For best results, even if you want to use a disconnected Azure Stack
  environment using AD FS as the identity provider, it's best to install
  the ASDK while connected to the internet. That way, the Windows Server
  2016 evaluation version included with the ASDK installation can be
  activated at deployment time.

Title: Azure Stack On-premise Deployment


答:
You can add a data-img attribute to your links:

```<code><a href="linkpage.htm" class="newslink1" data-img="1.png">
</code>```

which you can then access in the event handler using:

```<code>$(this).data('img');
</code>```

e.g.:

```<code>$('.sb_menu a').bind('mouseover', function() {
    $('#storyimg').attr(src, $(this).data('img'));
});
</code>```

Title: How can I turn this jquery into a function?

Body:
You can add a data-img attribute to your links:

<a href="linkpage.htm" class="newslink1" data-img="1.png">

which you can then access in the event handler using:

$(this).data('img');

e.g.:

$('.sb_menu a').bind('mouseover', function() {
    $('#storyimg').attr(src, $(this).data('img'));
});


问:
How to get value of element using text in BeautifulSoup
I've got a problem using BeautifulSoup. I need to get the value of the element using only some text inside but I've got no idea how to do that. There's some HTML code:

<option class="" value="9_72"> 42,5 EUR · 9 US </option>
<option class="" value="9_73"> 43 EUR · 9,5 US </option>
<option class="" value="9_74"> 44 EUR · 10 US </option>
```

<p>Is there any posibility to get it?</p>

<p>I tried this code:</p>

<pre class="lang-py prettyprint-override"><code>scraper = cfscrape.create_scraper()
content_rdy = scraper.get(link, headers=headers).text
soup = bs4.BeautifulSoup(content_rdy, 'lxml')

input_id = soup.find_all('option', text='44 EUR')
print(input_id)
</code>```

but it gives me empty [].  If I use:

input_id = soup.find_all('option')
```

I can't get exact the value of the option. And the problem is that the only thing how I can get this value is the size inside this element.

I want to get this -> value="9_72"

答:
```<code>from bs4 import BeautifulSoup as bs

html = """
<option class="" value="9_72"> 42,5 EUR · 9 US </option>
<option class="" value="9_73"> 43 EUR · 9,5 US </option>
<option class="" value="9_74"> 44 EUR · 10 US </option>"""

soup = bs(html, 'html.parser')

options = [option for option in soup.find_all('option') if '44 EUR' in option.text]
values = [option.get("value") for option in options]
</code>```

it returns all tags, who text contains "44 EUR" string

Body:
I've got a problem using BeautifulSoup. I need to get the value of the element using only some text inside but I've got no idea how to do that. There's some HTML code:

<option class="" value="9_72"> 42,5 EUR · 9 US </option>
<option class="" value="9_73"> 43 EUR · 9,5 US </option>
<option class="" value="9_74"> 44 EUR · 10 US </option>

Is there any posibility to get it?

I tried this code:

scraper = cfscrape.create_scraper()
content_rdy = scraper.get(link, headers=headers).text
soup = bs4.BeautifulSoup(content_rdy, 'lxml')

input_id = soup.find_all('option', text='44 EUR')
print(input_id)

but it gives me empty [].  If I use:

input_id = soup.find_all('option')

I can't get exact the value of the option. And the problem is that the only thing how I can get this value is the size inside this element.

I want to get this -> value="9_72"

Body:
from bs4 import BeautifulSoup as bs

html = """
<option class="" value="9_72"> 42,5 EUR · 9 US </option>
<option class="" value="9_73"> 43 EUR · 9,5 US </option>
<option class="" value="9_74"> 44 EUR · 10 US </option>"""

soup = bs(html, 'html.parser')

options = [option for option in soup.find_all('option') if '44 EUR' in option.text]
values = [option.get("value") for option in options]

it returns all tags, who text contains "44 EUR" string


问:
Retrieve column name based on cell value using matlab and excel

I use matlab software for programming language. I stored my data first is color as column & second value as number from Matlab to excel file.

How can I retrieve color name (column / text /string) where color value as number is greater than 1.6155 for example if my threshold = 1.6155 then i retrieve column name such as ("Merah ma","Kuning","Hijau")

答:
Apply transpose to your data so that column name such as ("Merah ma","Kuning","Hijau") and their respective values are converted into 2 columns.

Apply a simple condition in 3rd column that if(A2>1.6155,"Match","") and it will display match against those names which have a higher value than your threshold limit.

For Excel, this will work


问:
throw checked Exceptions from mocks with Mockito
I'm trying to have one of my mocked objects throw a checked Exception when a particular method is called. I'm trying the following.

```<code>@Test(expectedExceptions = SomeException.class)
public void throwCheckedException() {
    List<String> list = mock(List.class);
    when(list.get(0)).thenThrow(new SomeException());
    String test = list.get(0);
}

public class SomeException extends Exception {
}
</code>```

However, that produces the following error.

```<code>org.testng.TestException:
Expected exception com.testing.MockitoCheckedExceptions$SomeException but got org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: com.testing.MockitoCheckedExceptions$SomeException
</code>```

Looking at the Mockito documentation, they only use RuntimeException, is it not possible to throw checked Exceptions from a mock object with Mockito?

答:
This works for me in Kotlin:

```<code>when(list.get(0)).thenThrow(new ArrayIndexOutOfBoundsException());
</code>```

Note : Throw any defined exception other than Exception()

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to have one of my mocked objects throw a checked Exception when a particular method is called. I'm trying the following.

@Test(expectedExceptions = SomeException.class)
public void throwCheckedException() {
    List<String> list = mock(List.class);
    when(list.get(0)).thenThrow(new SomeException());
    String test = list.get(0);
}

public class SomeException extends Exception {
}

However, that produces the following error.

org.testng.TestException:
Expected exception com.testing.MockitoCheckedExceptions$SomeException but got org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: com.testing.MockitoCheckedExceptions$SomeException

Looking at the Mockito documentation, they only use RuntimeException, is it not possible to throw checked Exceptions from a mock object with Mockito?

Body:
This works for me in Kotlin:

when(list.get(0)).thenThrow(new ArrayIndexOutOfBoundsException());

Note : Throw any defined exception other than Exception()


问:
Breaking out of nested loops
Is there an easier way to break out of nested loops than throwing an exception? (In Perl, you can give labels to each loop and at least continue an outer loop.)

```<code>for x in range(10):
    for y in range(10):
        print x*y
        if x*y > 50:
            "break both loops"
</code>```

I.e., is there a nicer way than:

```<code>class BreakIt(Exception): pass

try:
    for x in range(10):
        for y in range(10):
            print x*y
            if x*y > 50:
                raise BreakIt
except BreakIt:
    pass
</code>```

答:
Sometimes I use a boolean variable. Naive, if you want, but I find it quite flexible and comfortable to read. Testing a variable may avoid testing again complex conditions and may also collect results from several tests in inner loops.</p>

```<code>    x_loop_must_break = False
    for x in range(10):
        for y in range(10):
            print x*y
            if x*y > 50:
                x_loop_must_break = True
                break
        if x_loop_must_break: break
</code>```

Title: Breaking out of nested loops

Body:
Is there an easier way to break out of nested loops than throwing an exception? (In Perl, you can give labels to each loop and at least continue an outer loop.)

for x in range(10):
    for y in range(10):
        print x*y
        if x*y > 50:
            "break both loops"

I.e., is there a nicer way than:

class BreakIt(Exception): pass

try:
    for x in range(10):
        for y in range(10):
            print x*y
            if x*y > 50:
                raise BreakIt
except BreakIt:
    pass

LastEditorDisplayName: unwind

Body:
Sometimes I use a boolean variable. Naive, if you want, but I find it quite flexible and comfortable to read. Testing a variable may avoid testing again complex conditions and may also collect results from several tests in inner loops.

    x_loop_must_break = False
    for x in range(10):
        for y in range(10):
            print x*y
            if x*y > 50:
                x_loop_must_break = True
                break
        if x_loop_must_break: break


问:
Is it possible to get single result in aggregate?
Is it possible to get a single document on db.collection.aggregate like as in db.collection.findOne?

答:
If "by a single result" you mean a findOne style return type, it should be impossible to do so. While not saying that it is impossible, it should be and should be treated as such. Aggregate operations are documented to return aggregate cursors only, so the only robust conclusion to an aggregate operation should be either an aggregate cursor or an error. When you receive your aggregate cursor, you can then use its exposed methods to access your single document. To expect anything else is akin to courting chaos.

Ps: Arrived massively late to this thread. Hope to help others who might end up here later on.


问:
Open file with specific cursor location
I'm trying to write a program that can search a word in a .txt file and open that file with the cursor at the specific location where the word was found (In front of the word). I've already implemented the searching and I know how to open a file, but I can't seem to find a way to open the file with the cursor at a specific position. Is there a way to do such a thing? Thanks :)

Edit : Just to clarify, when I say 'Open', I mean literally opening the file with Notepad, not opening the file with a Streamreader.

Edit 2 : I can't assume Notepad is the default text editor, but if needs be, I can force the file to be opened with it.

答:
XAML:

```<code><Window x:Class="WpfApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <TextBox x:Name="TextBox1"/>
</Grid>
</code>```

C#

```<code>using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            TextBox1.Focus(); // So the caret shows up
            string word = "hello";
            TextBox1.Text = File.ReadAllText("file.txt");
            var i = TextBox1.Text.IndexOf(word);
            if (i != -1) TextBox1.CaretIndex = i;
        }
    }
}
</code>```

This will place the caret in front of the first occurance of the word 'hello'. You can even highlight the text by using TextBox1.Select(int offset, int length).

Title: Open file with specific cursor location

Body:
XAML:

<Window x:Class="WpfApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <TextBox x:Name="TextBox1"/>
</Grid>

C#

using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            TextBox1.Focus(); // So the caret shows up
            string word = "hello";
            TextBox1.Text = File.ReadAllText("file.txt");
            var i = TextBox1.Text.IndexOf(word);
            if (i != -1) TextBox1.CaretIndex = i;
        }
    }
}

This will place the caret in front of the first occurance of the word 'hello'. You can even highlight the text by using TextBox1.Select(int offset, int length).


问:
How to get time difference Duration totals grouped by Name and when Value changes in certain way?
I'm looking for the Sum of time value differences between rows where Value was initially 1 and is now 0, grouped by Name.

Example data for a single Name, but there are many different Names in the real data.

```<code>+--------+---------------+---------------------+--------+
| RowNum |     Name      |      Timestamp      | Value  |
+--------+---------------+---------------------+--------+
|      1 | D1_HS_308_ALM | 2020-02-10 11:55:00 | 0      |
|      2 | D1_HS_308_ALM | 2020-02-10 11:51:00 | 0      |
|      3 | D1_HS_308_ALM | 2020-02-10 11:49:00 | NULL   |
|      4 | D1_HS_308_ALM | 2020-02-10 11:46:00 | 1      |
|      5 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      6 | D1_HS_308_ALM | 2020-02-10 08:02:00 | NULL   |
|      7 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      8 | D1_HS_308_ALM | 2020-02-10 07:56:00 | 1      |
|      9 | D1_HS_308_ALM | 2020-02-10 07:51:00 | 1      |
|     10 | D1_HS_308_ALM | 2020-02-10 07:50:00 | 0      |
+--------+---------------+---------------------+--------+
</code>```

This data should return 11 minutes for Row 9-->7 transition and 5 minutes for Row 4-->2 transition; totaling 16 minutes for this Name.

I'm not sure how to accomplish this when it's not guaranteed that the next row has the correct Value change - sometimes it will be several or many rows later.

答:
You can use window functions:

min() conditionally to get the next timestamp at value 0.

lag() to see the previous value.

Then filter down to the transition from 0 to 1 and do some date arithmetic:

```<code>select t.*,
       datediff(seconds, timestamp, next_ts_0) as duration
from (select t.*,
             min(case when value = 0 then timestamp end) over (partition by name order by timestamp desc) as next_ts_0,
             lag(value) over (partition by name order by timestamp) as prev_value
      from t.*
     ) t
where (prev_value = 0 or prev_value is null) and value = 1
</code>```

Body:
I'm looking for the Sum of time value differences between rows where Value was initially 1 and is now 0, grouped by Name.

Example data for a single Name, but there are many different Names in the real data.

+--------+---------------+---------------------+--------+
| RowNum |     Name      |      Timestamp      | Value  |
+--------+---------------+---------------------+--------+
|      1 | D1_HS_308_ALM | 2020-02-10 11:55:00 | 0      |
|      2 | D1_HS_308_ALM | 2020-02-10 11:51:00 | 0      |
|      3 | D1_HS_308_ALM | 2020-02-10 11:49:00 | NULL   |
|      4 | D1_HS_308_ALM | 2020-02-10 11:46:00 | 1      |
|      5 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      6 | D1_HS_308_ALM | 2020-02-10 08:02:00 | NULL   |
|      7 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      8 | D1_HS_308_ALM | 2020-02-10 07:56:00 | 1      |
|      9 | D1_HS_308_ALM | 2020-02-10 07:51:00 | 1      |
|     10 | D1_HS_308_ALM | 2020-02-10 07:50:00 | 0      |
+--------+---------------+---------------------+--------+

This data should return 11 minutes for Row 9-->7 transition and 5 minutes for Row 4-->2 transition; totaling 16 minutes for this Name.

I'm not sure how to accomplish this when it's not guaranteed that the next row has the correct Value change - sometimes it will be several or many rows later.

Body:
You can use window functions:

min() conditionally to get the next timestamp at value 0.

lag() to see the previous value.

Then filter down to the transition from 0 to 1 and do some date arithmetic:

select t.*,
       datediff(seconds, timestamp, next_ts_0) as duration
from (select t.*,
             min(case when value = 0 then timestamp end) over (partition by name order by timestamp desc) as next_ts_0,
             lag(value) over (partition by name order by timestamp) as prev_value
      from t.*
     ) t
where (prev_value = 0 or prev_value is null) and value = 1


问:
Apollo client mutation with writeQuery not triggering UI update
I have a mutation to create a new card object, and I expect it should be added to the user interface after update.  Cache, Apollo Chrome tool, and console logging reflect the changes, but the UI does not without a manual reload.

```<code> const [createCard, { loading, error }] = useMutation(CREATE_CARD, {
    update(cache, { data: { createCard } }) {
      let localData = cache.readQuery({
        query: CARDS_QUERY,
        variables: { id: deckId }
      });

      localData.deck.cards = [...localData.deck.cards, createCard];
;

  client.writeQuery({
    query: CARDS_QUERY,
    variables: { id: parseInt(localData.deck.id, 10) },
    data: { ...localData }
  });
</code>```

I have changed cache.writeQuery to client.writeQuery, but that didn't solve the problem.

For reference, here is the Query I am running...

```<code>const CARDS_QUERY = gql`
  query CardsQuery($id: ID!) {
    deck(id: $id) {
      id
      deckName
      user {
        id
      }
      cards {
        id
        front
        back
        pictureName
        pictureUrl
        createdAt
      }
    }
    toggleDeleteSuccess @client
  }
`;
</code>```

答:
I managed the same result without the cloneDeep method. Just using the spread operator solved my problem.

const update = (cache, {data}) => {
  const queryData = cache.readQuery({query: USER_QUERY})
  const cartItemId = data.cartItem.id
  queryData.me.cart = queryData.me.cart.filter(v => v.id !== cartItemId)
  cache.writeQuery({query: USER_QUERY, data: {...queryData}})
}
```

Hope this helps someone else.

Body:
I have a mutation to create a new card object, and I expect it should be added to the user interface after update.  Cache, Apollo Chrome tool, and console logging reflect the changes, but the UI does not without a manual reload.

 const [createCard, { loading, error }] = useMutation(CREATE_CARD, {
    update(cache, { data: { createCard } }) {
      let localData = cache.readQuery({
        query: CARDS_QUERY,
        variables: { id: deckId }
      });

      localData.deck.cards = [...localData.deck.cards, createCard];
;

  client.writeQuery({
    query: CARDS_QUERY,
    variables: { id: parseInt(localData.deck.id, 10) },
    data: { ...localData }
  });

I have changed cache.writeQuery to client.writeQuery, but that didn't solve the problem.

For reference, here is the Query I am running...

const CARDS_QUERY = gql`
  query CardsQuery($id: ID!) {
    deck(id: $id) {
      id
      deckName
      user {
        id
      }
      cards {
        id
        front
        back
        pictureName
        pictureUrl
        createdAt
      }
    }
    toggleDeleteSuccess @client
  }
`;

Body:
I managed the same result without the cloneDeep method. Just using the spread operator solved my problem.

const update = (cache, {data}) => {
  const queryData = cache.readQuery({query: USER_QUERY})
  const cartItemId = data.cartItem.id
  queryData.me.cart = queryData.me.cart.filter(v => v.id !== cartItemId)
  cache.writeQuery({query: USER_QUERY, data: {...queryData}})
}

Hope this helps someone else.


问:
react-tranisition-group use flex-box for react-router transition
I'm following the tutorial to add transition for react-router page use react-transition-group.
My page content all wrapped into the container, and I use flex-box to center the container.

However, it leads to transition cannot apply properly.

I expect page transition should be in the container, either from left to right or right to left.
I'm trying to use position:relative in container and position:absolute for transition class, seems doesn't work at all

code is here

Any ideas are welcome!

cheers.

答:
You can use react-tiger-transition for full page transitions with react-router.

Here is the demo:

(I'm the author)


问:
Can I use Emmet to populate a script source?
I would like to be able to to use Emmet shorthand to populate the script source.

What I type script:src and press tab:

```<code>
<script src=""></script> // Emmet produces this

<script src="script.js"></script>  // I want to produce this

</code>```

答:
From https://docs.emmet.io/cheat-sheet/

Custom attributes

p[title="Hello world"]

So, script[src="script.js"] should be what you're looking to do.

Body:
I would like to be able to to use Emmet shorthand to populate the script source.

What I type script:src and press tab:

 // Emmet produces this

  // I want to produce this

Body:
From https://docs.emmet.io/cheat-sheet/

Custom attributes

p[title="Hello world"]

<p title="Hello world"></p>

So, script[src="script.js"] should be what you're looking to do.


问:
Subtracting datetime UTC and datetime not UTC
From my dataframe I am trying to subtract one datetime64[ns, UTC] column against a datetime64[ns]. I believe I should normalize one of the columns and then subtract (should add UTC to the datetime64[ns] column or subtract UTC to the datetime64[ns, UTC] so afterwards I could subtract them).

```<code>df
estimated_delivery_time_local                  time_check
          2020-01-22 23:48:52   2020-01-22 23:48:52+00:00
          2020-01-23 00:45:05   2020-01-23 00:45:05+00:00
          2020-01-23 03:31:38   2020-01-23 03:31:38+00:00
          2020-01-23 00:19:06   2020-01-23 00:19:06+00:00
</code>```

I want to subtract this both column so as to check wether if all values are equal to zero

答:
You can first start by removing the local timestamp with:

```<code>df['time_check'] = df['time_check'].dt.tz_localize(None)
</code>```

Afterwards you can perform use np.where() to make the comparison whether the rows are equal for the columns or not.

```<code>df['quality_check'] = np.where(df['estimated_delivery_time_local'] == df['time_check'],0,1)
</code>```

This will return 1 for the rows that do not match and 0 for those that do match. You can very quickly filter the rows that do not match, or perform df['quality_check'].sum() to know the amount of rows that do not match.

Body:
From my dataframe I am trying to subtract one datetime64[ns, UTC] column against a datetime64[ns]. I believe I should normalize one of the columns and then subtract (should add UTC to the datetime64[ns] column or subtract UTC to the datetime64[ns, UTC] so afterwards I could subtract them).

df
estimated_delivery_time_local                  time_check
          2020-01-22 23:48:52   2020-01-22 23:48:52+00:00
          2020-01-23 00:45:05   2020-01-23 00:45:05+00:00
          2020-01-23 03:31:38   2020-01-23 03:31:38+00:00
          2020-01-23 00:19:06   2020-01-23 00:19:06+00:00

I want to subtract this both column so as to check wether if all values are equal to zero

Body:
You can first start by removing the local timestamp with:

df['time_check'] = df['time_check'].dt.tz_localize(None)

Afterwards you can perform use np.where() to make the comparison whether the rows are equal for the columns or not.

df['quality_check'] = np.where(df['estimated_delivery_time_local'] == df['time_check'],0,1)

This will return 1 for the rows that do not match and 0 for those that do match. You can very quickly filter the rows that do not match, or perform df['quality_check'].sum() to know the amount of rows that do not match.


问:
What algorithm does Verdaccio use to encrypt the npm registry?
Can't find the information anywhere. I'm a noob in computer security so my question might sound a bit dumb.

I understand we can communicate with Verdaccio using HTTPS and we can set up an authentication with htpasswd so I'm guessing a Verdaccio npm registry configured to use HTTPS and authentication is encrypted. If I'm right, what is/are the algorithm(s) used to encrypt the registry?

答:
Verdaccio uses crypto.createCipher(algorithm, password[, options]) for encrypt by default tokens.

A simple example would be:

```<code>import { createDecipher, createCipher, createHash, pseudoRandomBytes, Hash } from 'crypto';

const const payload = Buffer.from(`${name}:${password}`, 'utf8'));
const c = createCipher('aes192', SOME_RANDOM_SALT_VALUE);
const b1 = c.update(payload);
const b2 = c.final();
return Buffer.concat([b1, b2]);
</code>```

Furthermore, it has the option to use a standard JWT (jsonwebtoken), but it not enabled by default.

According the docs, the possible answer to your question might be

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On recent OpenSSL releases, openssl list -cipher-algorithms (openssl list-cipher-algorithms for older versions of OpenSSL) will display the available cipher algorithms.

Body:
Verdaccio uses crypto.createCipher(algorithm, password[, options]) for encrypt by default tokens.

A simple example would be:

import { createDecipher, createCipher, createHash, pseudoRandomBytes, Hash } from 'crypto';

const const payload = Buffer.from(`${name}:${password}`, 'utf8'));
const c = createCipher('aes192', SOME_RANDOM_SALT_VALUE);
const b1 = c.update(payload);
const b2 = c.final();
return Buffer.concat([b1, b2]);

Furthermore, it has the option to use a standard JWT (jsonwebtoken), but it not enabled by default.

According the docs, the possible answer to your question might be

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On recent OpenSSL releases, openssl list -cipher-algorithms (openssl list-cipher-algorithms for older versions of OpenSSL) will display the available cipher algorithms.


问:
Multicore Processing Python dosent print the output of a function
I don't understand why is the reason that the code dosen't print the output in console of this very fool programm.</p>

```<code>import numpy as np
from multiprocessing import Process

def calc2(nucleo, tope):
    for i in range(0, tope):
        print(str(np.sqrt(i)) + "  el nucleo es  " + str(nucleo))

processes = []

for i in range(os.cpu_count()):
    print("registering process %d" % i)
    processes.append(Process(target=calc2, args=(i, 100, )))

for process in processes:
    process.start()

for process in processes:
    process.join()
</code>```

答:
As for how to get return values, here is one option</p>

```<code>import os
import numpy as np
import multiprocessing as mp

def calc2worker(args):
    return calc2(*args)

def calc2(nucleo, tope):
    return ["{} el nucleo es {}".format(np.sqrt(i), nucleo)
        for i in range(0, tope)]

if __name__ == "__main__":
    pool = mp.Pool() # defaults to os.cpu_count()
    data_generator = ((i, 100) for i in range(os.cpu_count()))
    for result in pool.map(calc2worker, data_generator):
        for line in result:
            print(line)
    pool.close()
</code>```

Body:
I don't understand why is the reason that the code dosen't print the output in console of this very fool programm.

import numpy as np
from multiprocessing import Process

def calc2(nucleo, tope):
    for i in range(0, tope):
        print(str(np.sqrt(i)) + "  el nucleo es  " + str(nucleo))

processes = []

for i in range(os.cpu_count()):
    print("registering process %d" % i)
    processes.append(Process(target=calc2, args=(i, 100, )))

for process in processes:
    process.start()

for process in processes:
    process.join()

Body:
As for how to get return values, here is one option

import os
import numpy as np
import multiprocessing as mp

def calc2worker(args):
    return calc2(*args)

def calc2(nucleo, tope):
    return ["{} el nucleo es {}".format(np.sqrt(i), nucleo)
        for i in range(0, tope)]

if __name__ == "__main__":
    pool = mp.Pool() # defaults to os.cpu_count()
    data_generator = ((i, 100) for i in range(os.cpu_count()))
    for result in pool.map(calc2worker, data_generator):
        for line in result:
            print(line)
    pool.close()


问:
Find all possible Euler cycles
I have implemented an algorithm to find an Euler cycle for a given starting vertex in an undirected graph (using DFS and removing visited edges), but it always returns only one path. How do I modify the algorithm to search for all possible Euler cycles for a vertex?

Here is relevant code:

```<code>typedef int Graph[200][200]; // adjacency matrix
int v, e; // vertex count, edge count

......

void DFS(Graph &G, int x) {
    int i;
    Push(x);
    for (i = 0; i < v; i++)
        if (G[i][x] > 0) {
            G[i][x] = 0;
            G[x][i] = 0;
            DFS(G, i);
            break;
    }
</code>```

}

答: You want to loop through all vertex.</p>

Title: Find all possible Euler cycles

Body:
I have implemented an algorithm to find an Euler cycle for a given starting vertex in an undirected graph (using DFS and removing visited edges), but it always returns only one path. How do I modify the algorithm to search for all possible Euler cycles for a vertex?

Here is relevant code:

typedef int Graph[200][200]; // adjacency matrix
int v, e; // vertex count, edge count

......

void DFS(Graph &G, int x) {
    int i;
    Push(x);
    for (i = 0; i < v; i++)
        if (G[i][x] > 0) {
            G[i][x] = 0;
            G[x][i] = 0;
            DFS(G, i);
            break;
    }

}

Body: You want to loop through all vertex.


问:
JSF Primefaces application doesn't render properly on upgraded WildFly 18
I upgraded my server in Eclipse from WildFly v10.x to WildFly 18.0.0 Final and now one of my JSF/Primefaces applications doesn't render properly after updating the view.  On initial page load the view looks fine but if I select some filters (Primeface dropdowns, checkboxes, etc..) and click a command button to refresh the view (AJAX), it renders as if Primefaces is no longer available. See screenshots

Initial View Renders Fine:

After View Is Updated:

The error while debugging in Chrome:

```<code>SCRIPT5007: Unable to get property 'cw' of undefined or null reference
</code>```

.

```<code>$(function(){PrimeFaces.cw('Growl','widget_growl',{id:'growl',sticky:false,life:5000,escape:true,msgs:[]});});
</code>```

Not sure why the application is now not working after just upgrading WildFly.

答:
I fixed by replacing @all on the p:commandButton with a more specific target

```<code><p:commandButton action="#{...}" update="@all" />
<p:commandButton action="#{...}" update=":tripFormId:dataTableId" />
</code>```

I realized after seeing this in the Chrome console debugger

jquery.js.xhtml?ln=primefaces&v=7.0:2 [Deprecation] Synchronous
  XMLHttpRequest on the main thread is deprecated because of its
  detrimental effects to the end user's experience. For more help, check
  https://xhr.spec.whatwg.org/.

Body:
I upgraded my server in Eclipse from WildFly v10.x to WildFly 18.0.0 Final and now one of my JSF/Primefaces applications doesn't render properly after updating the view.  On initial page load the view looks fine but if I select some filters (Primeface dropdowns, checkboxes, etc..) and click a command button to refresh the view (AJAX), it renders as if Primefaces is no longer available. See screenshots

Initial View Renders Fine:

After View Is Updated:

The error while debugging in Chrome:

SCRIPT5007: Unable to get property 'cw' of undefined or null reference

.

$(function(){PrimeFaces.cw('Growl','widget_growl',{id:'growl',sticky:false,life:5000,escape:true,msgs:[]});});

Not sure why the application is now not working after just upgrading WildFly.

Body:
I fixed by replacing @all on the p:commandButton with a more specific target

<p:commandButton action="#{...}" update="@all" />
<p:commandButton action="#{...}" update=":tripFormId:dataTableId" />

I realized after seeing this in the Chrome console debugger

jquery.js.xhtml?ln=primefaces&v=7.0:2 [Deprecation] Synchronous
  XMLHttpRequest on the main thread is deprecated because of its
  detrimental effects to the end user's experience. For more help, check
  https://xhr.spec.whatwg.org/.


问:
Incrementing Timestamps
I have a Python script converting multiple csv lists into one xml document with time stamps for each row
I already have the format set as:

```<code>TS = datetime.now().isoformat(timespec='milliseconds')+ "Z"
</code>```

calling TS will give me this time stamp = 2020-02-14T14:30:59.237Z

I need to reuse this variable possibly 100k times or more in my XML document and this creates the exact same time, every time I call the variable. How can I increment the time stamp by 1 millisecond every time it is called in the script??

答:
You seem to be confused about the difference between a variable and a function.
You do not "call" a variable, unless you have specifically assigned it a value as a function.

You did not do this.  Your given code calls now and isoformat, returning a string value.  You put this value into TS for safekeeping.  Referring multiple times to TS does not change its value: it refers to the "once and future" string value, not to any process that would update that value.

If you want to update the time stamp, do so explicitly: add a timedelta of one millisecond to it on each loop iteration.

Title: Incrementing Timestamps

Body:
I have a Python script converting multiple csv lists into one xml document with time stamps for each row
I already have the format set as:

TS = datetime.now().isoformat(timespec='milliseconds')+ "Z"

calling TS will give me this time stamp = 2020-02-14T14:30:59.237Z

I need to reuse this variable possibly 100k times or more in my XML document and this creates the exact same time, every time I call the variable. How can I increment the time stamp by 1 millisecond every time it is called in the script??


问:
Can you join three tables on the same key if that key could be missing from one or more of the tables?
I'm taking three tables and joining them all together using the same primary key, but with no guarantee that all values exist across all three tables, and I want every value to end up in the final join.

For example, there's a TableA, TableB, and TableC, each with only one column (we'll just call the columns colA, colB, and colC). Value 10 is present in TableA and TableC, but not TableB.

```<code>SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     FULL OUTER JOIN TableC ON TableB.colB = TableC.colC;

+--------+  +--------+  +--------+
|  colA  |  |  colB  |  |  colC  |
+--------+  +--------+  +--------+
|      5 |  |      5 |  |      5 |
|     10 |  |     15 |  |     10 |
|     15 |  +--------+  |     15 |
+--------+              +--------+
</code>```

In the above example, I end up with something like this after the joins:

```<code>+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
| 5      | 5      | 5      |
| null   | null   | 10     |
| 15     | 15     | 15     |
| 10     | null   | null   |
+--------+--------+--------+
</code>```

My expected result is this:

```<code>+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
|      5 | 5      |      5 |
|     10 | null   |     10 |
|     15 | 15     |     15 |
+--------+--------+--------+
</code>```

The logic for my join is to first join TableA and TableB, then join the result with TableC. In this specific scenario, the join does not work. The join can try to match on the column passed through from TableA or the column from TableB, but I'm not sure how to make it check both.

Because I first joined TableA and TableB, there was no matching value in TableB. When I try to join TableC on TableB, it also finds no match, even though the key exists in TableA.

The closest I've gotten to my desired result is by using this query:

```<code>SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     RIGHT OUTER JOIN TableC ON TableC.colC IN (TableA.colA, TableB.colB);

+------+  +------+  +------+     +------+------+------+
| colA |  | colB |  | colC |     | colA | colB | colC |
+------+  +------+  +------+     +------+------+------+
|    5 |  |    5 |  |    5 |     | 5    | 5    |    5 |
|   10 |  |   15 |  |   10 | --> | 10   | null |   10 |
|   15 |  |   25 |  |   15 |     | 15   | 15   |   15 |
+------+  +------+  |   20 |     | null | null |   20 |
                    +------+     +------+------+------+
</code>```

Expected result:

```<code>+------+------+------+
| colA | colB | colC |
+------+------+------+
| 5    | 5    | 5    |
| 10   | null | 10   |
| 15   | 15   | 15   |
| null | null | 20   |
| null | 25   | null |
+------+------+------+
</code>```

This, unfortunately, does not include values that only exist in TableA or TableB in the final joined table, which is why I was using the FULL OUTER JOIN in the first place. With the FULL OUTER JOIN, I can't use the IN clause. Is there a solution that gives me what I want?

DB Fiddle: https://www.db-fiddle.com/f/faMLh4EAAKfBotXbaDofaQ/1

答:
I think you want left joins:

```<code>SELECT *
FROM TableA LEFT OUTER JOIN
     TableB
     ON TableA.colA = TableB.colB LEFT JOIN
     TableC
     ON TableA.colA = TableC.colC;
</code>```

Here is a fiddle.

Body:
I'm taking three tables and joining them all together using the same primary key, but with no guarantee that all values exist across all three tables, and I want every value to end up in the final join.

For example, there's a TableA, TableB, and TableC, each with only one column (we'll just call the columns colA, colB, and colC). Value 10 is present in TableA and TableC, but not TableB.

SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     FULL OUTER JOIN TableC ON TableB.colB = TableC.colC;

+--------+  +--------+  +--------+
|  colA  |  |  colB  |  |  colC  |
+--------+  +--------+  +--------+
|      5 |  |      5 |  |      5 |
|     10 |  |     15 |  |     10 |
|     15 |  +--------+  |     15 |
+--------+              +--------+

In the above example, I end up with something like this after the joins:

+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
| 5      | 5      | 5      |
| null   | null   | 10     |
| 15     | 15     | 15     |
| 10     | null   | null   |
+--------+--------+--------+

My expected result is this:

+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
|      5 | 5      |      5 |
|     10 | null   |     10 |
|     15 | 15     |     15 |
+--------+--------+--------+

The logic for my join is to first join TableA and TableB, then join the result with TableC. In this specific scenario, the join does not work. The join can try to match on the column passed through from TableA or the column from TableB, but I'm not sure how to make it check both.

Because I first joined TableA and TableB, there was no matching value in TableB. When I try to join TableC on TableB, it also finds no match, even though the key exists in TableA.

The closest I've gotten to my desired result is by using this query:

SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     RIGHT OUTER JOIN TableC ON TableC.colC IN (TableA.colA, TableB.colB);

+------+  +------+  +------+     +------+------+------+
| colA |  | colB |  | colC |     | colA | colB | colC |
+------+  +------+  +------+     +------+------+------+
|    5 |  |    5 |  |    5 |     | 5    | 5    |    5 |
|   10 |  |   15 |  |   10 | --> | 10   | null |   10 |
|   15 |  |   25 |  |   15 |     | 15   | 15   |   15 |
+------+  +------+  |   20 |     | null | null |   20 |
                    +------+     +------+------+------+

Expected result:

+------+------+------+
| colA | colB | colC |
+------+------+------+
| 5    | 5    | 5    |
| 10   | null | 10   |
| 15   | 15   | 15   |
| null | null | 20   |
| null | 25   | null |
+------+------+------+

This, unfortunately, does not include values that only exist in TableA or TableB in the final joined table, which is why I was using the FULL OUTER JOIN in the first place. With the FULL OUTER JOIN, I can't use the IN clause. Is there a solution that gives me what I want?

DB Fiddle: https://www.db-fiddle.com/f/faMLh4EAAKfBotXbaDofaQ/1

Body:
I think you want left joins:

SELECT *
FROM TableA LEFT OUTER JOIN
     TableB
     ON TableA.colA = TableB.colB LEFT JOIN
     TableC
     ON TableA.colA = TableC.colC;

Here is a fiddle.


问:
Accessing Ant properties in Gradle Task / Groovy function?
I am trying to use the ant.uptodate function in a gradle function, to check if some files have changed.

```<code>task generateXMLBeans {
    ant.uptodate(property: "xsdFileChanges", targetfile: "lib/xmlBeans.jar") {
            srcfiles(dir: 'protocol') {
                include(name: '*.xsd')
            }
    }
    if(ant.properties.xsdFileChanges == "false") {
        ant.taskdef(name: 'xmlbean', classname: 'org.apache.xmlbeans.impl.tool.XMLBean',
            classpath: configurations.xmlbeans.asPath)
            ant.xmlbean(
                javasource: "1.5",
                failonerror: "true",
                fork: "yes",
                memoryMaximumSize: "512M",
                memoryInitialSize: "64M",
                destfile: "lib/xmlBeans.jar",
                classpath: configurations.xmlbeans.asPath){
                    fileset(dir: 'protocol') {
                        include(name: '*.xsdconfig')
                        include(name: 'hmiprotocol.xsd')
                    }
                }
    }
}
</code>```

But the variable ant.properties.xsdFileChanges is null.

I tried to put the ant.uptodate function in a separate function, with the same result.

When I call the task with --debug function, I can see that the ant.uptodate function works generally.

```<code>14:40:50.947 [DEBUG] [org.gradle.api.internal.project.ant.AntLoggingAdapter] [ant:uptodate] hmiprotocol_systemlog.xsd omitted as D:\workspace_201912\ProjectX\lib\xmlBeans.jar is up to date.
14:40:50.948 [DEBUG] [org.gradle.api.internal.project.ant.AntLoggingAdapter] [ant:uptodate] hmiprotocol_testdetails.xsd omitted as D:\workspace_201912\ProjectX\lib\xmlBeans.jar is up to date.
</code>```

Has anyone any idea, how I can access the ant property correctly?

答:
This isn't related to using Ant from within Gradle; it's just how Ant's uptodate property works. The specified property isn't set to false if the file isn't up to date. It's simply not set at all. A few other Ant tasks, such as condition use this same convention.

A quick example you can try with Ant itself, given that you have both a build.xml and build.gradle file in the same directory:

```<code><target name="default">
    <uptodate property="uptodate1" targetfile="build.xml" srcfile="build.gradle" />

    <echo>${uptodate1}</echo>

    <uptodate property="uptodate2" targetfile="build.gradle" srcfile="build.xml" />

    <echo>${uptodate2}</echo>
</target>
</code>```

Output (may be reversed depending on modified times):

```<code>default:
     [echo] true
     [echo] ${uptodate2}
</code>```

Body:
I am trying to use the ant.uptodate function in a gradle function, to check if some files have changed.

task generateXMLBeans {
    ant.uptodate(property: "xsdFileChanges", targetfile: "lib/xmlBeans.jar") {
            srcfiles(dir: 'protocol') {
                include(name: '*.xsd')
            }
    }
    if(ant.properties.xsdFileChanges == "false") {
        ant.taskdef(name: 'xmlbean', classname: 'org.apache.xmlbeans.impl.tool.XMLBean',
            classpath: configurations.xmlbeans.asPath)
            ant.xmlbean(
                javasource: "1.5",
                failonerror: "true",
                fork: "yes",
                memoryMaximumSize: "512M",
                memoryInitialSize: "64M",
                destfile: "lib/xmlBeans.jar",
                classpath: configurations.xmlbeans.asPath){
                    fileset(dir: 'protocol') {
                        include(name: '*.xsdconfig')
                        include(name: 'hmiprotocol.xsd')
                    }
                }
    }
}

But the variable ant.properties.xsdFileChanges is null.

I tried to put the ant.uptodate function in a separate function, with the same result.

When I call the task with --debug function, I can see that the ant.uptodate function works generally.

14:40:50.947 [DEBUG] [org.gradle.api.internal.project.ant.AntLoggingAdapter] [ant:uptodate] hmiprotocol_systemlog.xsd omitted as D:\workspace_201912\ProjectX\lib\xmlBeans.jar is up to date.
14:40:50.948 [DEBUG] [org.gradle.api.internal.project.ant.AntLoggingAdapter] [ant:uptodate] hmiprotocol_testdetails.xsd omitted as D:\workspace_201912\ProjectX\lib\xmlBeans.jar is up to date.

Has anyone any idea, how I can access the ant property correctly?

Body:
This isn't related to using Ant from within Gradle; it's just how Ant's uptodate property works. The specified property isn't set to false if the file isn't up to date. It's simply not set at all. A few other Ant tasks, such as condition use this same convention.

A quick example you can try with Ant itself, given that you have both a build.xml and build.gradle file in the same directory:

<target name="default">
    <uptodate property="uptodate1" targetfile="build.xml" srcfile="build.gradle" />

    <echo>${uptodate1}</echo>

    <uptodate property="uptodate2" targetfile="build.gradle" srcfile="build.xml" />

    <echo>${uptodate2}</echo>
</target>

Output (may be reversed depending on modified times):

default:
     [echo] true
     [echo] ${uptodate2}


问:
Kafka batch listener, polling fixed numbers of records ( as much as possible)
I'm using Spring boot version 1.5.4.RELEASE & spring Kafka version  1.3.8.RELEASE.

My Kafka consumer is doing batch processing in chunks of 100. Topic I'm trying to consume has 10 partitions & I do have 10 instances of Kafka consumer.

Is there a I can enforce to get 100 fixed number of records ( as much as possible), apart from last chunk in particular partition.

答:
Kafka has no property fetch.min.records.

The best you can do is simulate it with:

fetch.min.bytes: The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. The default setting of 1 byte means that fetch requests are answered as soon as a single byte of data is available or the fetch request times out waiting for data to arrive. Setting this to something greater than 1 will cause the server to wait for larger amounts of data to accumulate which can improve server throughput a bit at the cost of some additional latency.

and

fetch.max.wait.ms: The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by fetch.min.bytes.

Which will work if your records have similar lengths.

By the way Spring Boot 1.5.x is end of life and no longer supported. The current Boot version is 2.2.3.


问:
How can i do event listener for a custom select in the table?
I have table it contains columns from database and  I have custom select on the column and also have button update. Now I need when I click on the button make event listener in custom select and get what the user selected and print the value  selected on  console using JavaScript ….How can I do this please any one help me...   </p>

```<code>@foreach ($bookinghalls as $item)

    <tr>
        <td>{{$item->id}}</td>
    <td>{{$item->name}}</td>
   <td >{{$item->hall_name}}</td>
    <td>{{$item->from_date}}</td>
    <td>{{$item->to_date}}</td>
    <td>{{$item->type_booking}}</td>
    <td  ><select class="custom-select mr-sm-2" name="intervel"   >
@if ($item->pay==0)
<option value="0" >Not paid</option>
<option value="1" >paid </option>

@else ($item->pay==1)
<option value="1" >paid </option>
<option value="0" >Not paid</option>
@endif
</td>
     <td id="stauts">  <?php
        if($item->stauts==0)
         print_r("available");
     elseif($item->stauts==1)
     print_r("it's Processing ");
     elseif($item->stauts==2)
     print_r("booking done");
       ?></td>
     <td><button type="submit"  class="btn btn-primary but_update"  name="imagaid"   >update</button>
     </td>
</code>```

答:
for set event listener for a <select> tag and get value of <option value="any-value" selected>text</option>, do as following:

```<code>document.querySelector('.custom-select').addEventListener('change', function () {
    let selectedValue = this.value;
    console.log(selectedValue);
});
</code>```

Body:
I have table it contains columns from database and  I have custom select on the column and also have button update. Now I need when I click on the button make event listener in custom select and get what the user selected and print the value  selected on  console using JavaScript ….How can I do this please any one help me...

@foreach ($bookinghalls as $item)

        {{$item->id}}
    {{$item->name}}
   {{$item->hall_name}}
    {{$item->from_date}}
    {{$item->to_date}}
    {{$item->type_booking}}
    <select class="custom-select mr-sm-2" name="intervel"   >
@if ($item->pay==0)
<option value="0" >Not paid</option>
<option value="1" >paid </option>

@else ($item->pay==1)
<option value="1" >paid </option>
<option value="0" >Not paid</option>
@endif

       <?php
        if($item->stauts==0)
         print_r("available");
     elseif($item->stauts==1)
     print_r("it's Processing ");
     elseif($item->stauts==2)
     print_r("booking done");
       ?>
     <button type="submit"  class="btn btn-primary but_update"  name="imagaid"   >update</button>

Body:
for set event listener for a <select> tag and get value of <option value="any-value" selected>text</option>, do as following:

document.querySelector('.custom-select').addEventListener('change', function () {
    let selectedValue = this.value;
    console.log(selectedValue);
});


问:
Rendering several components in a grid
Imagen we have a little stock application. Here we make a list off all available stocks.We have a stocks.vue component, the code below, and a stock.vue component. We have 4 stocks here. We want to render them in a 2x2 grid. The code below renders them in a 1x4 grid.
A div.columns holds up to 12 div.column (Bulma), so for our 2x2 grid we'd need two div.columns each holding two div.column and each div.column would hold a stock.

```<code><template>
    <div>
        <p>Current stocks:</p>
        <div class="columns">
            <div class="column" v-for="stock in stocks">
                <app-stock :stock="stock"></app-stock>
            </div>
        </div>
    </div>
</template>

<script>
    import Stock from './stock.vue';

    export default {
        data() {
            return {
                stocks: [
                    { name: 'BMW', value: '23' },
                    { name: 'Apple', value: '223' },
                    { name: 'Sony', value: '43' },
                    { name: 'EDA', value: '235' }
                ]
            }
        },
        components: {
            appStock: Stock
        }
    }
</script>
</code>```

Now, what's a good way to rewrite the above code such that it renders our stocks in a 2x2 grid? Would it maybe be better to first rearrange our data in a computed such that it represents or view more appropriately i.e. in this case into a 2 dimensional array of objects?

答:
You are missing is-multiline and is-half :

```<code>    <div class="columns is-multiline">
        <div class="column is-half" v-for="stock in stocks">
            <app-stock :stock="stock"></app-stock>
        </div>
    </div>
</code>```

Docs about it can be find here.

Title: Rendering several components in a grid

Body:
Imagen we have a little stock application. Here we make a list off all available stocks.We have a stocks.vue component, the code below, and a stock.vue component. We have 4 stocks here. We want to render them in a 2x2 grid. The code below renders them in a 1x4 grid.
A div.columns holds up to 12 div.column (Bulma), so for our 2x2 grid we'd need two div.columns each holding two div.column and each div.column would hold a stock.

<template>

Current stocks:

                <app-stock :stock="stock"></app-stock>

</template>

Now, what's a good way to rewrite the above code such that it renders our stocks in a 2x2 grid? Would it maybe be better to first rearrange our data in a computed such that it represents or view more appropriately i.e. in this case into a 2 dimensional array of objects?

Body:
You are missing is-multiline and is-half :

    <div class="columns is-multiline">
        <div class="column is-half" v-for="stock in stocks">
            <app-stock :stock="stock"></app-stock>
        </div>
    </div>

Docs about it can be find here.


问:
SQL Server 2008 - MERGE statement - Perform multiple actions in WHEN MATCHED block
I am trying to use MERGE statement to accomplish the following. I have a SP and i am passing TableValue Parameter to it. This is how my SP looks like:

```<code>CREATE PROC sp_AddInformation
@IntoTbl dbo.Information  READONLY ,
@baseEventType dbo.EventType READONLY

AS

BEGIN

MERGE Information
USING (SELECT InfoID, NewsID, NewsType FROM @IntoTbl ) AS baseInfo (InfoID, NewsID, NewsType)
ON (info.infoID = baseInfo.InfoID)
WHEN MATCHED
        THEN
        --EXEC dbo.sp_insertEventInfo(@baseEventType) (This is not working)

        UPDATE set Info.Reporter = baseInfo.Reporter
WHEN NOT MATCHED BY SOURCE
        THEN

        DELETE
WHEN NOT MATCHED BY TARGET
    THEN INSERT VALUES (InfoID, NewsID,NewsType);
END
</code>```

Does anyone know how can i call another SP or perform another MERGE on other tables in WHEN MATCHED block?

答:
The syntax shows that UPDATE SET or DELETE are the only options for merge_matched

as shown here

Body:
I am trying to use MERGE statement to accomplish the following. I have a SP and i am passing TableValue Parameter to it. This is how my SP looks like:

CREATE PROC sp_AddInformation
@IntoTbl dbo.Information  READONLY ,
@baseEventType dbo.EventType READONLY

AS

BEGIN

MERGE Information
USING (SELECT InfoID, NewsID, NewsType FROM @IntoTbl ) AS baseInfo (InfoID, NewsID, NewsType)
ON (info.infoID = baseInfo.InfoID)
WHEN MATCHED
        THEN
        --EXEC dbo.sp_insertEventInfo(@baseEventType) (This is not working)

        UPDATE set Info.Reporter = baseInfo.Reporter
WHEN NOT MATCHED BY SOURCE
        THEN

        DELETE
WHEN NOT MATCHED BY TARGET
    THEN INSERT VALUES (InfoID, NewsID,NewsType);
END

Does anyone know how can i call another SP or perform another MERGE on other tables in WHEN MATCHED block?