问:
Skip JPA life cycle methods while running tests
I have an entity Post and an event listener is registered with it as shown here.

```<code>@EntityListeners({EntityAuditor.class})
@Entity
class Post {
  ...
}
</code>```

Here is how my EntityAuditor listener class looks like:

```<code>public class EntityAuditor {
  @PostPersist
  void publishToKafka(Object object) {
      // publish new object to Kafka
  }
}
</code>```

I don't want this to be called when my unit/integration test try to create a new post. Is there a way I can skip the JPA lifecycle hooks or the event listener only for tests?

答:
According to the JPA spec The EntityListeners annotation can be overridden with the <entity-listeners> subelement of the <entity> element in the persistence object/relational
mapping file.

So, you should include a META-INF/orm.xml file, only on your test environment, and set an empty <entity-listeners> for your entity. Something like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_2.xsd"
                 version="2.2">
    <entity class="yourpackage.Post">
        <entity-listeners />
    </entity>
</entity-mappings>
</code>```

Body:
I have an entity Post and an event listener is registered with it as shown here.

@EntityListeners({EntityAuditor.class})
@Entity
class Post {
  ...
}

Here is how my EntityAuditor listener class looks like:

public class EntityAuditor {
  @PostPersist
  void publishToKafka(Object object) {
      // publish new object to Kafka
  }
}

I don't want this to be called when my unit/integration test try to create a new post. Is there a way I can skip the JPA lifecycle hooks or the event listener only for tests?

Body:
According to the JPA spec The EntityListeners annotation can be overridden with the <entity-listeners> subelement of the <entity> element in the persistence object/relational
mapping file.

So, you should include a META-INF/orm.xml file, only on your test environment, and set an empty <entity-listeners> for your entity. Something like this

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_2.xsd"
                 version="2.2">
    <entity class="yourpackage.Post">
        <entity-listeners />
    </entity>
</entity-mappings>


来源: stackexchange

问:
mybatis not returning all the rows on lazy fetch
My java application when using mybatis (3.4.4) to query oracle back end is not returning all the rows when using lazy load.

Essentially,

when I query my database using some SQL tool (like oracle Sql Developer) I get 4000 results

when I query using selectCursor which leads to lazy load conn.selectCusror(query) I only get 560 result!

when I query using selectList which will fetch all result at once conn.selectList(query) I am getting 4000 results (matches with database)

Note: A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. Documentation

This is how I am counting the number of records

```<code>Cursor<Object> cur = conn.selectCursor(query) ; // query definition is written below
int count =0;
for(Object ob : cur){
    count++;
}
System.out.println(count);
</code>```

QUERY

```<code><select id="query" fetchSize="20000" resultType="java.util.Map" >
    select distinct code from my CODES_VIEW
</select>
</code>```

Can someone please advise why selectCursor is not giving all the 4000 results

答:
After spending days I found this solution:

My result set from the query contains a row (561) which have null values in its column. This shouldn't be a problem as I can have null values in the columns I fetched . In this case code column has value null at row 561.
When fetching records via selectCursor (lazy method of fetching data) mybatis believes it is end of record when all the columns are null in the fetched row.

MyBatis, by default, returns null when all the columns of a returned
  row are NULL. When this setting is enabled, MyBatis returns an empty
  instance instead. Note that it is also applied to nested results (i.e.
  collectioin and association). Since: 3.4.2
  https://mybatis.org/mybatis-3/configuration.html

However, you won't face this problem when you use selectList as all the records are fetched at once and cursor doesn't keep on checking on how does the next fetched records look like .

Hence the solution is to put the below setting in the mybatis config.xml

```<code><setting name="returnInstanceForEmptyRow" value="true" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My java application when using mybatis (3.4.4) to query oracle back end is not returning all the rows when using lazy load.

Essentially,

when I query my database using some SQL tool (like oracle Sql Developer) I get 4000 results

when I query using selectCursor which leads to lazy load conn.selectCusror(query) I only get 560 result!

when I query using selectList which will fetch all result at once conn.selectList(query) I am getting 4000 results (matches with database)

Note: A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. Documentation

This is how I am counting the number of records

Cursor<Object> cur = conn.selectCursor(query) ; // query definition is written below
int count =0;
for(Object ob : cur){
    count++;
}
System.out.println(count);

QUERY

<select id="query" fetchSize="20000" resultType="java.util.Map" >
    select distinct code from my CODES_VIEW
</select>

Can someone please advise why selectCursor is not giving all the 4000 results

Body:
After spending days I found this solution:

My result set from the query contains a row (561) which have null values in its column. This shouldn't be a problem as I can have null values in the columns I fetched . In this case code column has value null at row 561.
When fetching records via selectCursor (lazy method of fetching data) mybatis believes it is end of record when all the columns are null in the fetched row.

MyBatis, by default, returns null when all the columns of a returned
  row are NULL. When this setting is enabled, MyBatis returns an empty
  instance instead. Note that it is also applied to nested results (i.e.
  collectioin and association). Since: 3.4.2
  https://mybatis.org/mybatis-3/configuration.html

However, you won't face this problem when you use selectList as all the records are fetched at once and cursor doesn't keep on checking on how does the next fetched records look like .

Hence the solution is to put the below setting in the mybatis config.xml

<setting name="returnInstanceForEmptyRow" value="true" />


问:
redirect user on previous page after successfull task
What should be good way to redirect user after successful action like edit or delete any item, in delete condition we could use $_SERVER['HTTP_REFERER'] but in case of edit, we show first of all edit form and then user clicks update, so if we use same approach user would be redirected to edit page not main page. I hope you got idea about my confusion. thanks.

答:
Save the url in session when you are coming to Edit page and when you submit just use the below snippet after executing the update query:</p>

```<code>header('Location: '.$_SESSION['redirect_url']);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Save the url in session when you are coming to Edit page and when you submit just use the below snippet after executing the update query:

header('Location: '.$_SESSION['redirect_url']);


问:
Randomly show image + link in html newsletter template
Let's say i have a list of 4 images and i'm trying to randomly show 2 of them each time the newsletter is loaded.

I have a file show_image.php with the following code:

```<code>
$images = array(
  0 => array(
    'image' => 'http://example.com/img/partner1.jpg',
    'link' => 'http://www.example1.com'
  ),
  1 => array(
    'image' => 'http://example.com/img/partner2.jpg',
    'link' => 'http://www.example2.com'
  ),
  2 => array(
    'image' => 'http://example.com/img/partner3.jpg',
    'link' => 'http://www.example3.com'
  ),
  3 => array(
    'image' => 'http://example.com/img/partner4.jpg',
    'link' => 'http://www.example4.com'
  )
);

$i = 0
foreach($images as $image)
{
  $i++;
  $zones[$i][] = $image;
  if($i == 2)
    $i = 0;
}

if(!empty($zones[$_GET['zone']]))
{
    $zone = $zones[$_GET['zone']];
    $random_index = array_rand($zone);
    $partner = $zone[$random_index];

    if($_GET['field'] == 'image')
    {
        $file = getFullPath($partner['image']);

        $type = 'image/jpeg';
        header('Content-Type:'.$type);
        header('Content-Length: ' . filesize($file));
        readfile($file);
    }
    elseif($_GET['field'] == 'link')
    {
        wp_redirect( $partner['link'], 301);
        exit();
    }
}

</code>```

In my current situation, the images in the (html) newsletter template look like this:

```<code><a href="http://example.com/show_image.php?zone=1&field=link">
  <img src="http://example.com/show_image.php?zone=1&field=image">
</a>
<a href="http://example.com/show_image.php?zone=2&field=link">
  <img src="http://example.com/show_image.php?zone=2&field=image">
</a>
</code>```

As you can see, the call for a random image and link are separate, causing the php script to respond with a random link that doesn't match the random image.

Can anyone point me in the right direction how to randomly show an image with the right corresponding link?

答:
there are could be multiple solutions, all of them have positive and negative sides:

Instead of static html file with hard-coded links, you can generate page on fly with php, so in this way you will generate random number for each zone and output html with proper links/images

1.1. You can use iframe to load image and link form php server

If you have to use static html and javascript, you can perform ajax call to php with javascript, which again will fetch image and link and use them to generate html code (document.write or innerHTML)

You can try to use cookies or session mechanism, in this case in php code you will have branch like if number for zone is not generated yet - generate and store in cookie/session; return link or image for number from cookies/session

To modify your code for #3 you need to replace

```<code> $random_index = array_rand($zone);
</code>```

with something like (writing without actual php, so syntax errors are possible):

```<code>$cook = 'zone' . $_GET['zone'];
$random_index = isset($_COOKIE[$cook]) ? $_COOKIE[$cook] : array_rand($zone);
setcookie($cook, $random_index);
</code>```

note - it is up to you to put proper validation for any variables from GET or COOKIE

In case of e-mail clients - majority of them restrict execution of javascript code and don't store cookies (and from user's perspective is it very good that they do that), anyway you can try something like that:

during e-mail sending generate unique id for each e-mail sent (you can use UUID for that)

include this id into links in your template, like

in image and click handler - you need to get id from url and check in database - whether you assigned value to it and if no - generate and store in db

if value in db present - you can now serve appropriate image or redirect to appropriate url

but in this scheme - users always will be presented with the same image (though different users will see different ones), to fix that you can introduce some kind of expiration, ie put timestamp in db and invalidate (regenerate) value

note - some e-mail clients can force cache of images, ignoring http headers, thus such scheme will fail

other notes:

don't forget about no-cache http headers for serving image

don't use permanent redirects, only temporary ones for your use case

some e-mail clients will not load images which are not embedded into message, for such ones you can play with  and embedded images of some single randomly picked ad

Body:
Let's say i have a list of 4 images and i'm trying to randomly show 2 of them each time the newsletter is loaded.

I have a file show_image.php with the following code:

$images = array(
  0 => array(
    'image' => 'http://example.com/img/partner1.jpg',
    'link' => 'http://www.example1.com'
  ),
  1 => array(
    'image' => 'http://example.com/img/partner2.jpg',
    'link' => 'http://www.example2.com'
  ),
  2 => array(
    'image' => 'http://example.com/img/partner3.jpg',
    'link' => 'http://www.example3.com'
  ),
  3 => array(
    'image' => 'http://example.com/img/partner4.jpg',
    'link' => 'http://www.example4.com'
  )
);

$i = 0
foreach($images as $image)
{
  $i++;
  $zones[$i][] = $image;
  if($i == 2)
    $i = 0;
}

if(!empty($zones[$_GET['zone']]))
{
    $zone = $zones[$_GET['zone']];
    $random_index = array_rand($zone);
    $partner = $zone[$random_index];

    if($_GET['field'] == 'image')
    {
        $file = getFullPath($partner['image']);

        $type = 'image/jpeg';
        header('Content-Type:'.$type);
        header('Content-Length: ' . filesize($file));
        readfile($file);
    }
    elseif($_GET['field'] == 'link')
    {
        wp_redirect( $partner['link'], 301);
        exit();
    }
}

In my current situation, the images in the (html) newsletter template look like this:

As you can see, the call for a random image and link are separate, causing the php script to respond with a random link that doesn't match the random image.

Can anyone point me in the right direction how to randomly show an image with the right corresponding link?

Body:
there are could be multiple solutions, all of them have positive and negative sides:

Instead of static html file with hard-coded links, you can generate page on fly with php, so in this way you will generate random number for each zone and output html with proper links/images

1.1. You can use iframe to load image and link form php server

If you have to use static html and javascript, you can perform ajax call to php with javascript, which again will fetch image and link and use them to generate html code (document.write or innerHTML)

You can try to use cookies or session mechanism, in this case in php code you will have branch like if number for zone is not generated yet - generate and store in cookie/session; return link or image for number from cookies/session

To modify your code for #3 you need to replace

 $random_index = array_rand($zone);

with something like (writing without actual php, so syntax errors are possible):

$cook = 'zone' . $_GET['zone'];
$random_index = isset($_COOKIE[$cook]) ? $_COOKIE[$cook] : array_rand($zone);
setcookie($cook, $random_index);

note - it is up to you to put proper validation for any variables from GET or COOKIE

In case of e-mail clients - majority of them restrict execution of javascript code and don't store cookies (and from user's perspective is it very good that they do that), anyway you can try something like that:

during e-mail sending generate unique id for each e-mail sent (you can use UUID for that)

include this id into links in your template, like <a href="http://..../?...&id=UUID"><img src="http://.../?..&id=UUID"></a>

in image and click handler - you need to get id from url and check in database - whether you assigned value to it and if no - generate and store in db

if value in db present - you can now serve appropriate image or redirect to appropriate url

but in this scheme - users always will be presented with the same image (though different users will see different ones), to fix that you can introduce some kind of expiration, ie put timestamp in db and invalidate (regenerate) value

note - some e-mail clients can force cache of images, ignoring http headers, thus such scheme will fail

other notes:

don't forget about no-cache http headers for serving image

don't use permanent redirects, only temporary ones for your use case

some e-mail clients will not load images which are not embedded into message, for such ones you can play with <noscript> and embedded images of some single randomly picked ad


问:
Javascript insert array in array
Source from wi2l.de/sof.html

var x = -1;
var a = new Array(9);
var i = new Array(2);

x = x + 1;
a[x] = ["a", "b"];
x = x + 1;
a[x] = ["c", "d"];
i[0] = "e";
i[1] = "f";
x = x + 1;
a[x] = i;
i[0] = "g";
i[1] = "h";
x = x + 1;
a[x] = i;

console.log(a[1] + " " + a[2] + " " + a[3]);```

result is c,d g,h g,h but should be c,d e,f g,h.

答:
a[2] seems to point to the memory address of i and not recover its value.

To counter this, you need to recover the value of i. You can do it this way:

a[x] = Object.values(i)

Title: Javascript insert array in array

Body:
Source from wi2l.de/sof.html

var x = -1;
var a = new Array(9);
var i = new Array(2);

x = x + 1;
a[x] = ["a", "b"];
x = x + 1;
a[x] = ["c", "d"];
i[0] = "e";
i[1] = "f";
x = x + 1;
a[x] = i;
i[0] = "g";
i[1] = "h";
x = x + 1;
a[x] = i;

console.log(a[1] + " " + a[2] + " " + a[3]);

result is c,d g,h g,h but should be c,d e,f g,h.


问:
Serialize a map using a specific order
I have a map that uses string for both key and value. I have an array of keys that specifies the order of the values of the map.

I want to serialize that map to a JSON, but keeping the order defined on the array.

There is a sample code here: http://play.golang.org/p/A52GTDY6Wx

I want to serialize it as:

```<code>{
  "name": "John",
  "age": "20"
}
</code>```

But if I serialize the map directly, the keys are ordered alphabetically:

```<code>{
  "age": "20",
  "name": "John"
}
</code>```

I can serialize it as an array of maps, thus keeping the order, however that generates a lot of undesired characters:

```<code>[
  {
    "name": "John"
  },
  {
    "age": "20"
  }
]
</code>```

In my real code I need to serialize the results of a database query which is specified in a text file, and I need to maintain the column order. I cannot use structs because the columns are not known at compile time.

EDIT: I don't need to read the JSON later in the specified order. The generated JSON is meant to be read by people, so I just want it to be as humanly readable as possible.

I could use a custom format but JSON suits me perfectly for this.

Thanks!

答:
Here is a MapSlice implementation similar to what YAML v2 offers. It can do both Marshal and Unmarshal.

https://github.com/mickep76/mapslice-json

Title: Serialize a map using a specific order

Body:
I have a map that uses string for both key and value. I have an array of keys that specifies the order of the values of the map.

I want to serialize that map to a JSON, but keeping the order defined on the array.

There is a sample code here: http://play.golang.org/p/A52GTDY6Wx

I want to serialize it as:

{
  "name": "John",
  "age": "20"
}

But if I serialize the map directly, the keys are ordered alphabetically:

{
  "age": "20",
  "name": "John"
}

I can serialize it as an array of maps, thus keeping the order, however that generates a lot of undesired characters:

[
  {
    "name": "John"
  },
  {
    "age": "20"
  }
]

In my real code I need to serialize the results of a database query which is specified in a text file, and I need to maintain the column order. I cannot use structs because the columns are not known at compile time.

EDIT: I don't need to read the JSON later in the specified order. The generated JSON is meant to be read by people, so I just want it to be as humanly readable as possible.

I could use a custom format but JSON suits me perfectly for this.

Thanks!


问:
Why is perl regex hanging?
I have the following code (which uses a recursive regex).   Things seem to work fine, except at one particular place, where I have an unmatched brace.   I'm trying to understand what exactly is causing the hang.   I have:

```<code>use strict;
use warnings;
use Carp;
use Data::Dumper;

my $matchBracePtrn =    qr/(?<brace>\((?:[^()]+|(?&brace))+\))/;
my $mkVarPtrn =         qr/\$(?:\w|${matchBracePtrn})/;

# my $testString='$(a) $(a $(c)';   # OK: reports $(a) and $(c)...
# my $testString='$(foreach i,$(LIST),$(eval $(call foo,$i)))'; # OK
my $testString='$(a) $(foreach i,$(LIST),$(eval $(call foo,$i))'; #not OK!

while ($testString =~ /($mkVarPtrn)/g) {
    print "$1\n"
}
</code>```

This outputs:

```<code>$(a)
</code>```

and then hangs.   This is perl 5.22.0, in case that matters.

答:
The (?<brace>\((?:[^()]+|(?&brace))+\)) pattern causes catastrophic backtracking.

In order to fix the recursive pattern, either use a ++ possessive quantifier with [^()], [^()]++, or use an atomic group instead of the non-capturing group, (?>[^()]+|(?&brace))+.

So, use either of

```<code>my $matchBracePtrn =    qr/(?<brace>\((?:[^()]++|(?&brace))+\))/;
my $matchBracePtrn =    qr/(?<brace>\((?>[^()]+|(?&brace))+\))/;
</code>```

See the online demo.

Title: Why is perl regex hanging?

Body:
I have the following code (which uses a recursive regex).   Things seem to work fine, except at one particular place, where I have an unmatched brace.   I'm trying to understand what exactly is causing the hang.   I have:

use strict;
use warnings;
use Carp;
use Data::Dumper;

my $matchBracePtrn =    qr/(?<brace>\((?:[^()]+|(?&brace))+\))/;
my $mkVarPtrn =         qr/\$(?:\w|${matchBracePtrn})/;

# my $testString='$(a) $(a $(c)';   # OK: reports $(a) and $(c)...
# my $testString='$(foreach i,$(LIST),$(eval $(call foo,$i)))'; # OK
my $testString='$(a) $(foreach i,$(LIST),$(eval $(call foo,$i))'; #not OK!

while ($testString =~ /($mkVarPtrn)/g) {
    print "$1\n"
}

This outputs:

$(a)

and then hangs.   This is perl 5.22.0, in case that matters.

Body:
The (?<brace>\((?:[^()]+|(?&brace))+\)) pattern causes catastrophic backtracking.

In order to fix the recursive pattern, either use a ++ possessive quantifier with [^()], [^()]++, or use an atomic group instead of the non-capturing group, (?>[^()]+|(?&brace))+.

So, use either of

my $matchBracePtrn =    qr/(?<brace>\((?:[^()]++|(?&brace))+\))/;
my $matchBracePtrn =    qr/(?<brace>\((?>[^()]+|(?&brace))+\))/;

See the online demo.


问:
What will be the logic to show top rated item?
I want to show items in my website sorted by its rating.
I don't want to show highest rated items by the average of rating. Could anyone suggest some formula to define highest rated item.</p>

答:
Your definition of the score for an item is likely to be a function of:

Average rating

Highest rating, lowest rating

Number of rates

A time weighting


问:
Getting Read/Write access error when trying to use method from external library
I am trying to use the following implementation from a library

C++

```<code>int CALLBACK xCallback(long xmitlen, int buflen, char *buf, long flen)
{
    return 0;
}

extern "C"  __declspec(dllexport) int __stdcall TXFIlestransfer(int port, string fileName);

__declspec(dllexport) int __stdcall TXFIlestransfer(int port, string fileName)
{
     int ret;

     char *test = &fileName[0];

     ret = sio_FtKermitTx(port, test, xCallback, 27);

     return ret;
}
</code>```

I am importing this to use with C# and am getting System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

Any help with resolving this error would be greatly appreciated.

答:
I tested your program by simulating the sio_FtKermitTx function in my C++ dll (Mydll.dll):

```<code>int sio_FtKermitTx (int port, char *fname, int (CALLBACK *func) (long xmitlen, int buflen, char *buf, long flen), int key)
{
    return 5;
}
</code>```

And even with an empty body, I have the same problem as you.

After several investigations, I noticed that the problem came from the fact that we are using a string object between C# and C++ code which for one reason or another (unicode / multibyte configuration for example, or simply because sharing complex objects is difficult to implement) causes problem.

Solution:

By replacing the string object with a primitive char type, everything works correctly:

C# Code:

```<code>using System.Runtime.InteropServices;
namespace MyProgramme
{
    class Test
    {
        // Import C++ DLL
        [DllImport("Mydll.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int TXFIlestransfer(int i, char[] filename);
        //public static extern int TXFIlestransfer(int i, string filename); // this crash

        static void RunTest(/*LoadFilterEVENTMessage msg*/)
        {
            string c = "ABC";
            char[] char_arr = c.ToCharArray();
            int i = TXFIlestransfer(3, char_arr);
            // int i = TXFIlestransfer(3, c); string version crash

            string s = i.ToString();
            MessageBox.Show(s);
        }

        /* Methods in DLL being used below  */
        public static void Main()
        {
            RunTest();
        }
    };
}
</code>```

C++ DLL code (Mydll.dll) :

```<code>extern "C" __declspec(dllexport) int TXFIlestransfer(int port, char fileName[])
{
    int ret;
    char *test = &fileName[0];
    ret = sio_FtKermitTx(port, test, xCallback, 27);
    return ret;
}
</code>```

anyway, your sio_FtKermitTx function accepts a char* in parameter, so changing your TXFIlestransfer parameters from string to char[] is not problematic.

Result:

After running C# program you will get this:

Body:
I am trying to use the following implementation from a library

C++

int CALLBACK xCallback(long xmitlen, int buflen, char *buf, long flen)
{
    return 0;
}

extern "C"  __declspec(dllexport) int __stdcall TXFIlestransfer(int port, string fileName);

__declspec(dllexport) int __stdcall TXFIlestransfer(int port, string fileName)
{
     int ret;

     char *test = &fileName[0];

     ret = sio_FtKermitTx(port, test, xCallback, 27);

     return ret;
}

I am importing this to use with C# and am getting System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

Any help with resolving this error would be greatly appreciated.

Body:
I tested your program by simulating the sio_FtKermitTx function in my C++ dll (Mydll.dll):

int sio_FtKermitTx (int port, char *fname, int (CALLBACK *func) (long xmitlen, int buflen, char *buf, long flen), int key)
{
    return 5;
}

And even with an empty body, I have the same problem as you.

After several investigations, I noticed that the problem came from the fact that we are using a string object between C# and C++ code which for one reason or another (unicode / multibyte configuration for example, or simply because sharing complex objects is difficult to implement) causes problem.

Solution:

By replacing the string object with a primitive char type, everything works correctly:

C# Code:

using System.Runtime.InteropServices;
namespace MyProgramme
{
    class Test
    {
        // Import C++ DLL
        [DllImport("Mydll.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int TXFIlestransfer(int i, char[] filename);
        //public static extern int TXFIlestransfer(int i, string filename); // this crash

        static void RunTest(/*LoadFilterEVENTMessage msg*/)
        {
            string c = "ABC";
            char[] char_arr = c.ToCharArray();
            int i = TXFIlestransfer(3, char_arr);
            // int i = TXFIlestransfer(3, c); string version crash

            string s = i.ToString();
            MessageBox.Show(s);
        }

        /* Methods in DLL being used below  */
        public static void Main()
        {
            RunTest();
        }
    };
}

C++ DLL code (Mydll.dll) :

extern "C" __declspec(dllexport) int TXFIlestransfer(int port, char fileName[])
{
    int ret;
    char *test = &fileName[0];
    ret = sio_FtKermitTx(port, test, xCallback, 27);
    return ret;
}

anyway, your sio_FtKermitTx function accepts a char* in parameter, so changing your TXFIlestransfer parameters from string to char[] is not problematic.

Result:

After running C# program you will get this:


问:
Why is this C++ deque code 'less efficient' when I demodularize it?
This is a problem I faced when studying solutions to this problem on HackerRank.
It basically boils down to the following: given an array A and an integer K, the problem asks you to find the maximum of each contiguous subarray of A with size K.
There is some additional stuff (for each test case, this problem occurs T times, and one must read from input to obtain A), but that's the gist of it.

The site checks whether your answer is sufficiently efficient, and even if your code produces the correct output in the end, the submission may fail due to timeout.
Now, when your first get to the code area, there is some predefined code for you:

```<code>#include <iostream>
#include <deque>
using namespace std;

void printKMax(int arr[], int n, int k){
    //Write your code here.
}

int main(){

    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
}
</code>```

All fine and dandy, the site already handles input for your benefit, and points you towards a modular approach.
All you have to do is actually solve the contiguous subarray problem;
I did it with the following function, which passes all test cases:

```<code>void printKMax(int arr[], int n, int k){
    // Queue will store up to k elements (moving window)
    // Elements stored will be indices of the array. Indices allow to compare with loop iterator for removal of oldest element as window moves
    // Most recent elements are pushed to the back (so they take longer to be popped)
    std::deque<int> Q(k);

    // Iterate over the first window
    int i;
    for (i = 0; i < k; ++i) {
        // A new element (arr[i]) to be added at the back invalidates all elements added before it that are no greater (if they are smaller, they cannot be a maximum; if they are equal, the new element is more recent). Those elements are popped
        // This guarantees that the values corresponding to Q's indices will be increasing (strictly) from back to front. In particular, the front will be the maximum
        while ((!Q.empty()) && arr[i] >= arr[Q.back()])
            Q.pop_back();
        Q.push_back(i);
    }

    // Iterate, letting the window move
    for (; i < n; ++i) {
        // Print the largest element (window has not moved yet), followed by a space
        cout << arr[Q.front()] << " ";

        // Use indices to determine if oldest element has gone out of the window
        if (Q.front() <= i - k) Q.pop_front();

        // Add new element, like before
        while ((!Q.empty()) && arr[i] >= arr[Q.back()])
            Q.pop_back();
        Q.push_back(i);
    }

    // Print the maximum element of last window, and end the line
    cout << arr[Q.front()] << endl;
}
</code>```

However, looking back on it, I thought I could do (slightly?) better.
For each test case, the input handling in main loops n times to fill the array arr, and then printKMax in turn also loops n times to create and slide the moving window.
I thought I could combine these into a single loop, which I guess should be more efficient.
I did it with the following code, which is basically the same as before but with printKMax incorporated into the main.
I'll omit comments this time.

```<code>int main(){

    int t;
    cin >> t;
    while(t>0) {
        int i = 0, n, k;
        cin >> n >> k;
        int arr[n];

        std::deque<int> Q(k);

        for (; i < k; ++i) {
            cin >> arr[i];
            while ((!Q.empty()) && arr[i] >= arr[Q.back()])
                Q.pop_back();
            Q.push_back(i);
        }

        for (; i < n; ++i) {
            cout << arr[Q.front()] << " ";

            if (Q.front() <= i - k) Q.pop_front();

            cin >> arr[i];
            while ((!Q.empty()) && arr[i] >= arr[Q.back()])
                Q.pop_back();
            Q.push_back(i);
        }

        cout << arr[Q.front()] << endl;

        t--;
        }
    return 0;
}
</code>```

This time, however, the code fails all but the simplest of test cases, in each case due to time limit constraints.

I understand that in practice modularization is good, but at this point my interest is more 'academic' than anything else.
Is there something I'm missing about the actual program, or is this something related to how things are run behind the scenes that I'm unaware of?

EDIT: As suggested by PaulMcKenzie, I've used g++ to run both versions of the program, using one of the failed test cases as input.
Both ran fine and produced the same output, but the one with printKMax ran in 3.97s while the one without ran in 5.44s. It takes about 37% longe.

答:
You second version is slower, because you're interleaving your input and output.

Reading from cin causes any output buffered for cout to be flushed first.  The idea is that there is a user that needs to see your prompt.

Since you switch between reading and writing many times for each test, it results in many I/O operations to write to the console, which is not so fast.

See: https://www.geeksforgeeks.org/fast-io-for-competitive-programming/ and https://en.cppreference.com/w/cpp/io/basic_ios/tie

you can fix it with cin.tie(NULL);

Body:
This is a problem I faced when studying solutions to this problem on HackerRank.
It basically boils down to the following: given an array A and an integer K, the problem asks you to find the maximum of each contiguous subarray of A with size K.
There is some additional stuff (for each test case, this problem occurs T times, and one must read from input to obtain A), but that's the gist of it.

The site checks whether your answer is sufficiently efficient, and even if your code produces the correct output in the end, the submission may fail due to timeout.
Now, when your first get to the code area, there is some predefined code for you:

#include <iostream>
#include <deque>
using namespace std;

void printKMax(int arr[], int n, int k){
    //Write your code here.
}

int main(){

    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
}

All fine and dandy, the site already handles input for your benefit, and points you towards a modular approach.
All you have to do is actually solve the contiguous subarray problem;
I did it with the following function, which passes all test cases:

void printKMax(int arr[], int n, int k){
    // Queue will store up to k elements (moving window)
    // Elements stored will be indices of the array. Indices allow to compare with loop iterator for removal of oldest element as window moves
    // Most recent elements are pushed to the back (so they take longer to be popped)
    std::deque<int> Q(k);

    // Iterate over the first window
    int i;
    for (i = 0; i < k; ++i) {
        // A new element (arr[i]) to be added at the back invalidates all elements added before it that are no greater (if they are smaller, they cannot be a maximum; if they are equal, the new element is more recent). Those elements are popped
        // This guarantees that the values corresponding to Q's indices will be increasing (strictly) from back to front. In particular, the front will be the maximum
        while ((!Q.empty()) && arr[i] >= arr[Q.back()])
            Q.pop_back();
        Q.push_back(i);
    }

    // Iterate, letting the window move
    for (; i < n; ++i) {
        // Print the largest element (window has not moved yet), followed by a space
        cout << arr[Q.front()] << " ";

        // Use indices to determine if oldest element has gone out of the window
        if (Q.front() <= i - k) Q.pop_front();

        // Add new element, like before
        while ((!Q.empty()) && arr[i] >= arr[Q.back()])
            Q.pop_back();
        Q.push_back(i);
    }

    // Print the maximum element of last window, and end the line
    cout << arr[Q.front()] << endl;
}

However, looking back on it, I thought I could do (slightly?) better.
For each test case, the input handling in main loops n times to fill the array arr, and then printKMax in turn also loops n times to create and slide the moving window.
I thought I could combine these into a single loop, which I guess should be more efficient.
I did it with the following code, which is basically the same as before but with printKMax incorporated into the main.
I'll omit comments this time.

int main(){

    int t;
    cin >> t;
    while(t>0) {
        int i = 0, n, k;
        cin >> n >> k;
        int arr[n];

        std::deque<int> Q(k);

        for (; i < k; ++i) {
            cin >> arr[i];
            while ((!Q.empty()) && arr[i] >= arr[Q.back()])
                Q.pop_back();
            Q.push_back(i);
        }

        for (; i < n; ++i) {
            cout << arr[Q.front()] << " ";

            if (Q.front() <= i - k) Q.pop_front();

            cin >> arr[i];
            while ((!Q.empty()) && arr[i] >= arr[Q.back()])
                Q.pop_back();
            Q.push_back(i);
        }

        cout << arr[Q.front()] << endl;

        t--;
        }
    return 0;
}

This time, however, the code fails all but the simplest of test cases, in each case due to time limit constraints.

I understand that in practice modularization is good, but at this point my interest is more 'academic' than anything else.
Is there something I'm missing about the actual program, or is this something related to how things are run behind the scenes that I'm unaware of?

EDIT: As suggested by PaulMcKenzie, I've used g++ to run both versions of the program, using one of the failed test cases as input.
Both ran fine and produced the same output, but the one with printKMax ran in 3.97s while the one without ran in 5.44s. It takes about 37% longe.


问:
R lubridate: Apply helper to dataframe
I have a dataframe of times looking like this:

```<code>library(lubridate)

times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"),
                        exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")),
                        row.names = c(NA, 3L), class = "data.frame")
</code>```

I want to convert the times in more convenient date-time objects, which I will do with the hms() helper function from the lubridate package.

Running hms() on one column of my dataframe works like a charm:

```<code>hms(times[,1])
</code>```

[1] "17H 19M 4S"  "17H 28M 53S" "17H 38M 44S"

Great, surely I can just apply() on my whole dataframe then.

```<code>apply(times, 2, hms)
</code>```

Which gives a weird dataframe with some integers, definitely not what I am expecting.

What is the right way to convert all of my times dataframe with the hms() function?

答:
```<code>library(dplyr)
library(lubridate)

times %>% mutate_all(hms)
#OR
mutate_all(times, hms)
#         exp1        exp2
#1  17H 19M 4S  17H 22M 4S
#2 17H 28M 53S 17H 31M 53S
#3 17H 38M 44S 17H 41M 45S
</code>```

Title: R lubridate: Apply helper to dataframe

Body:
I have a dataframe of times looking like this:

library(lubridate)

times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"),
                        exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")),
                        row.names = c(NA, 3L), class = "data.frame")

I want to convert the times in more convenient date-time objects, which I will do with the hms() helper function from the lubridate package.

Running hms() on one column of my dataframe works like a charm:

hms(times[,1])

[1] "17H 19M 4S"  "17H 28M 53S" "17H 38M 44S"

Great, surely I can just apply() on my whole dataframe then.

apply(times, 2, hms)

Which gives a weird dataframe with some integers, definitely not what I am expecting.

What is the right way to convert all of my times dataframe with the hms() function?


问:
Scheme/"The Seasoned Schemer": Question about the syntax of the definition of "try" function
In their book "The Seasoned Schemer", Felleisen and Friedman introduce the try function. According to http://community.schemewiki.org/?seasoned-schemer, this function can be defined as

```<code>(define-syntax try
  (syntax-rules ()
    ((try var a . b)
     (letcc success
       (letcc var (success a)) . b))))
</code>```

where letcc is defined as

```<code>(define-syntax letcc
  (syntax-rules ()
    ((letcc var body ...)
     (call-with-current-continuation
       (lambda (var)  body ... )))))
</code>```

Now, while I understand what try does and how it can be used, I am having trouble to follow the formal definition of it. What exactly is the meaning of the dot in the application of letcc to success and (letcc var (success a)) . b in the lines

```<code>(letcc success
       (letcc var (success a)) . b)
</code>```

of try? Or maybe asked differently: Which part of the definition of try establishes that try is evaluated to b if var is called in a?

Edit 1: Sorry, the definition of letcc was incomplete. Added the missing first line.

Edit 2: The following code can be run in Racket.

```<code>(define-syntax letcc
   (syntax-rules ()
                 ((letcc var body ...)
                  (call-with-current-continuation
                    (lambda (var)  body ... )))))

 (define-syntax try
   (syntax-rules ()
                 ((try var a . b)
                  (letcc success
                         (letcc var (success a)) . b))))

(try var (+ 1 1) 4)
; output: 2

(try var (var '(2)) 4)
; output: 4
</code>```

答:
I'm not an expert on the intricacies of Scheme macro syntax, but I think an equivalent definition of try is:

```<code>(define-syntax try
  (syntax-rules ()
    ((try var a b ...)
     (letcc success
       (letcc var (success a)) b ...))))
</code>```

I find this much easier to read for sure.

(try e   <c>) (either version, at least in Racket) then expands to

```<code>(letcc success
  (letcc e
    (success <a>))
  <b> <c>)))
</code>```

So, then, when  is being evaluated, e is a continuation which returns its arguments from the inner letcc form, where they're ignored.  If e is invoked that's where you end up and then  and <c> get evaluated in the normal way (I've only put more than one thing there because I can, and it deals with the whole . ... thing).  if e isn't invoked during the evaluation of , then success is invoked, and it's also a continuation which then returns the result of evaluating  from the whole form.

At least I think that's what happens.

Below is a chunk of Racket which I used to test I understood things.

```<code>(module+ test
  (require rackunit))

(define-syntax let/cc
  (syntax-rules ()
    ((let/cc var body ...)
     (call-with-current-continuation
       (lambda (var) body ... )))))

(define-syntax try
  (syntax-rules ()
    ((try var a b ...)
     (let/cc success
       (let/cc var (success a)) b ...))))

(module+ test
  (check-eqv?
   (try fail (+ 1 1) 4)
   2)

  (check-eqv?
   (try fail (fail '(2)) 4)
   4)

  (check-eqv?
   (try fail
        (begin 1 (fail) (error "failed to fail"))
        4 5 6)
   6))
</code>```

Body:
In their book "The Seasoned Schemer", Felleisen and Friedman introduce the try function. According to http://community.schemewiki.org/?seasoned-schemer, this function can be defined as

(define-syntax try
  (syntax-rules ()
    ((try var a . b)
     (letcc success
       (letcc var (success a)) . b))))

where letcc is defined as

(define-syntax letcc
  (syntax-rules ()
    ((letcc var body ...)
     (call-with-current-continuation
       (lambda (var)  body ... )))))

Now, while I understand what try does and how it can be used, I am having trouble to follow the formal definition of it. What exactly is the meaning of the dot in the application of letcc to success and (letcc var (success a)) . b in the lines

(letcc success
       (letcc var (success a)) . b)

of try? Or maybe asked differently: Which part of the definition of try establishes that try is evaluated to b if var is called in a?

Edit 1: Sorry, the definition of letcc was incomplete. Added the missing first line.

Edit 2: The following code can be run in Racket.

(define-syntax letcc
   (syntax-rules ()
                 ((letcc var body ...)
                  (call-with-current-continuation
                    (lambda (var)  body ... )))))

 (define-syntax try
   (syntax-rules ()
                 ((try var a . b)
                  (letcc success
                         (letcc var (success a)) . b))))

(try var (+ 1 1) 4)
; output: 2

(try var (var '(2)) 4)
; output: 4

Body:
I'm not an expert on the intricacies of Scheme macro syntax, but I think an equivalent definition of try is:

(define-syntax try
  (syntax-rules ()
    ((try var a b ...)
     (letcc success
       (letcc var (success a)) b ...))))

I find this much easier to read for sure.

(try e <a> <b> <c>) (either version, at least in Racket) then expands to

(letcc success
  (letcc e
    (success <a>))
  <b> <c>)))

So, then, when <a> is being evaluated, e is a continuation which returns its arguments from the inner letcc form, where they're ignored.  If e is invoked that's where you end up and then <b> and <c> get evaluated in the normal way (I've only put more than one thing there because I can, and it deals with the whole . ... thing).  if e isn't invoked during the evaluation of <a>, then success is invoked, and it's also a continuation which then returns the result of evaluating <a> from the whole form.

At least I think that's what happens.

Below is a chunk of Racket which I used to test I understood things.

(module+ test
  (require rackunit))

(define-syntax let/cc
  (syntax-rules ()
    ((let/cc var body ...)
     (call-with-current-continuation
       (lambda (var) body ... )))))

(define-syntax try
  (syntax-rules ()
    ((try var a b ...)
     (let/cc success
       (let/cc var (success a)) b ...))))

(module+ test
  (check-eqv?
   (try fail (+ 1 1) 4)
   2)

  (check-eqv?
   (try fail (fail '(2)) 4)
   4)

  (check-eqv?
   (try fail
        (begin 1 (fail) (error "failed to fail"))
        4 5 6)
   6))


问:
Return 2 objects using an IIFE
I'm trying to return 2 objects using an IIFE. I cant find whats wrong here.</p>

```<code>var UIController = (function(){

    return{
        getMinput: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        }

        getMinput: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        }
    };

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

答:
Here you have one object. You can't have the same name for methods inside one object. Also, you need to add ',' after each method or prop.
So do it like this: </p>

```<code>(function(){

    return{
        getMinput: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        },

        getMinput1: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        }
    };
    })());

OR if you really need two objects you can use array:

(function(){
    return [
        getMinput: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        },

        getMinput1: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        }
    ];
  })
());
</code>```

Title: Return 2 objects using an IIFE

Body:
I'm trying to return 2 objects using an IIFE. I cant find whats wrong here.

var UIController = (function(){

    return{
        getMinput: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        }

        getMinput: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        }
    };

})();

Body:
Here you have one object. You can't have the same name for methods inside one object. Also, you need to add ',' after each method or prop.
So do it like this:

(function(){

    return{
        getMinput: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        },

        getMinput1: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        }
    };
    })());

OR if you really need two objects you can use array:

(function(){
    return [
        getMinput: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        },

        getMinput1: function(){
            return {
            mstaff1: document.querySelector('#mstaff1').value,
            mstaff2: document.querySelector('#mstaff2').value,
            mpda: document.querySelector('#mpda').value,
            mpos: document.querySelector('#mpos').value,
            mcash: document.querySelector('#mcash').value,
            mtotal: document.querySelector('#mtotal').value
            };
        }
    ];
  })
());


问:
CSS - Fixed button on expanding
I am trying to make the search bar expand on device size < 768px. GIF Image.
How to fixed button when I click expand?

```<code>@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;

    .search-bar {
      max-width: 3em;
      margin-left: auto;

      &:focus-within {
        max-width: 100%;

        .search-bar__input {
          width: auto;
          padding: 0 1em;
        }
      }
    }

    .search-bar__input {
      width: 0;
      padding: 0;
    }
  }
}
</code>```

Here is my codepen:
https://codepen.io/phamtien990819/pen/PoqGwEv

答:
This CSS code I updated. I used position: absolute; to place button on right of the bar. So even after input is opened button stays on right without moving.

```<code>@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;
    position: relative;
    .search-bar__input {
      margin-left: 10px;
      background: transparent;
      overflow: hidden;
    }

    .search-bar__btn {
      width: 40px;
      position: absolute;
      right: 1px;
      height: 29px;
    }
</code>```

body {
  display: flex;
  flex-direction: column;
  margin: 0;
  min-height: 100vh;
  font-size: 14px;
}

ol,
ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

main {
  flex: 1;
}

.material-icons {
  font-size: 24px;
  vertical-align: middle;
}

.material-icons::before {
  content: attr(icon);
}

.site-header {
  position: sticky;
  top: -40px;
  width: 100%;
  z-index: 99;
  background: #fff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.top-nav {
  background: rgba(0, 0, 0, 0.03);
}

.top-nav .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
}

.top-nav ul {
  display: flex;
  font-size: 12px;
  list-style: none;
}

.top-nav ul>li+li {
  margin-left: 1.5em;
}

.top-nav ul a {
  color: currentColor;
}

.main-nav .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 5em;
}

.header-brand {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-brand .logo {
  text-decoration: none;
  color: currentColor;
}

.header-brand .menu-toggle {
  display: none;
  border: 0;
  outline: 0;
  background: transparent;
  margin-left: 1em;
  padding: 6px;
}

/* BEGIN SEARCH BAR */

.header-search {
  flex: auto;
  margin-left: 4em;
}

.header-search .search-bar {
  display: flex;
  align-items: center;
  border: 1px solid rgba(0, 0, 0, 0.1);
  max-width: 25em;
  height: 2.5em;
  transition: all 3s;
}

.header-search .search-bar__input {
  flex: auto;
  height: 100%;
  border: 0;
  padding: 0 1em;
  outline: 0;
}

.header-search .search-bar__btn {
  width: 3em;
  height: 100%;
  border: 0;
  outline: 0;
  text-align: center;
}

@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;
    position: relative;
  }
  .header-search .search-bar__input {
    margin-left: 10px;
    background: transparent;
    overflow: hidden;
  }
  .header-search .search-bar__btn {
    width: 40px;
    position: absolute;
    right: 1px;
    height: 29px;
  }
  .header-search .search-bar {
    max-width: 3em;
    margin-left: auto;
  }
  .header-search .search-bar:focus-within {
    max-width: 100%;
  }
  .header-search .search-bar:focus-within .search-bar__input {
    width: auto;
  }
  .header-search .search-bar__input {
    width: 0;
    padding: 0;
  }
}

/* END SEARCH BAR */

.header-user {
  display: flex;
  align-items: center;
}

.header-user .item {
  position: relative;
  flex-shrink: 0;
  display: inline-flex;
}

.header-user .item .user-link {
  font-weight: 500;
  color: currentColor;
  padding: 6px;
  border-radius: 4px;
  margin-left: 8px;
}

.header-user .item .user-link:hover {
  text-decoration: none;
  background-color: rgba(0, 0, 0, 0.03);
}

@media (max-width: 768px) {
  .s-header {
    top: 0;
  }
  .top-nav {
    display: none;
  }
  .main-nav .container {
    height: 4em;
  }
  .header-brand .menu-toggle {
    display: inline-block;
    margin-left: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/material-design-icons/3.0.1/iconfont/material-icons.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

<body>
  <header class="site-header">
    <div class="top-nav">
      <div class="container">
        <ul>
          <li>Top menu item</li>
          <li>Top menu item</li>
          <li>Top menu item</li>
          <li>Top menu item</li>
          <li>Top menu item</li>
        </ul>
      </div>
    </div>
    <nav class="main-nav">
      <div class="container">
        <div class="header-brand">
          LOGO HERE
          <button class="menu-toggle">
                        <i class="material-icons" icon="menu"></i>
                    </button>
        </div>
        <div class="header-search">
          <form action="#" class="search-bar">
            <input class="search-bar__input" type="search" placeholder="Search..." />
            <button class="search-bar__btn" type="button">
                            <i class="material-icons" icon="search"></i>
                        </button>
          </form>
        </div>
        <ul class="header-user">
          <li class="item">

              <i class="material-icons" icon="person_add"></i>
              <span class="d-none d-md-inline">Login / Register</span>

          </li>
        </ul>
      </div>
    </nav>
  </header>
  <main>
    <div class="container" style="height: 1000px">
      <p class="mt-4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
        dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </main>
  <footer>
    <div class="container">
      <p>Footer content</p>
    </div>
  </footer>
</body></code>```

Title: CSS - Fixed button on expanding

Body:
I am trying to make the search bar expand on device size < 768px. GIF Image.
How to fixed button when I click expand?

@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;

    .search-bar {
      max-width: 3em;
      margin-left: auto;

      &:focus-within {
        max-width: 100%;

        .search-bar__input {
          width: auto;
          padding: 0 1em;
        }
      }
    }

    .search-bar__input {
      width: 0;
      padding: 0;
    }
  }
}

Here is my codepen:
https://codepen.io/phamtien990819/pen/PoqGwEv

Body:
This CSS code I updated. I used position: absolute; to place button on right of the bar. So even after input is opened button stays on right without moving.

@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;
    position: relative;
    .search-bar__input {
      margin-left: 10px;
      background: transparent;
      overflow: hidden;
    }

    .search-bar__btn {
      width: 40px;
      position: absolute;
      right: 1px;
      height: 29px;
    }

body {
  display: flex;
  flex-direction: column;
  margin: 0;
  min-height: 100vh;
  font-size: 14px;
}

ol,
ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

main {
  flex: 1;
}

.material-icons {
  font-size: 24px;
  vertical-align: middle;
}

.material-icons::before {
  content: attr(icon);
}

.site-header {
  position: sticky;
  top: -40px;
  width: 100%;
  z-index: 99;
  background: #fff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.top-nav {
  background: rgba(0, 0, 0, 0.03);
}

.top-nav .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
}

.top-nav ul {
  display: flex;
  font-size: 12px;
  list-style: none;
}

.top-nav ul>li+li {
  margin-left: 1.5em;
}

.top-nav ul a {
  color: currentColor;
}

.main-nav .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 5em;
}

.header-brand {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-brand .logo {
  text-decoration: none;
  color: currentColor;
}

.header-brand .menu-toggle {
  display: none;
  border: 0;
  outline: 0;
  background: transparent;
  margin-left: 1em;
  padding: 6px;
}

/* BEGIN SEARCH BAR */

.header-search {
  flex: auto;
  margin-left: 4em;
}

.header-search .search-bar {
  display: flex;
  align-items: center;
  border: 1px solid rgba(0, 0, 0, 0.1);
  max-width: 25em;
  height: 2.5em;
  transition: all 3s;
}

.header-search .search-bar__input {
  flex: auto;
  height: 100%;
  border: 0;
  padding: 0 1em;
  outline: 0;
}

.header-search .search-bar__btn {
  width: 3em;
  height: 100%;
  border: 0;
  outline: 0;
  text-align: center;
}

@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;
    position: relative;
  }
  .header-search .search-bar__input {
    margin-left: 10px;
    background: transparent;
    overflow: hidden;
  }
  .header-search .search-bar__btn {
    width: 40px;
    position: absolute;
    right: 1px;
    height: 29px;
  }
  .header-search .search-bar {
    max-width: 3em;
    margin-left: auto;
  }
  .header-search .search-bar:focus-within {
    max-width: 100%;
  }
  .header-search .search-bar:focus-within .search-bar__input {
    width: auto;
  }
  .header-search .search-bar__input {
    width: 0;
    padding: 0;
  }
}

/* END SEARCH BAR */

.header-user {
  display: flex;
  align-items: center;
}

.header-user .item {
  position: relative;
  flex-shrink: 0;
  display: inline-flex;
}

.header-user .item .user-link {
  font-weight: 500;
  color: currentColor;
  padding: 6px;
  border-radius: 4px;
  margin-left: 8px;
}

.header-user .item .user-link:hover {
  text-decoration: none;
  background-color: rgba(0, 0, 0, 0.03);
}

@media (max-width: 768px) {
  .s-header {
    top: 0;
  }
  .top-nav {
    display: none;
  }
  .main-nav .container {
    height: 4em;
  }
  .header-brand .menu-toggle {
    display: inline-block;
    margin-left: 0;
  }
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/material-design-icons/3.0.1/iconfont/material-icons.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

<body>
  <header class="site-header">
    <div class="top-nav">
      <div class="container">
        <ul>
          <li><a href="#">Top menu item</a></li>
          <li><a href="#">Top menu item</a></li>
          <li><a href="#">Top menu item</a></li>
          <li><a href="#">Top menu item</a></li>
          <li><a href="#">Top menu item</a></li>
        </ul>
      </div>
    </div>
    <nav class="main-nav">
      <div class="container">
        <div class="header-brand">
          <a class="logo d-none d-md-inline-block" href="#">LOGO HERE</a>
          <button class="menu-toggle">
                        <i class="material-icons" icon="menu"></i>
                    </button>
        </div>
        <div class="header-search">
          <form action="#" class="search-bar">
            <input class="search-bar__input" type="search" placeholder="Search..." />
            <button class="search-bar__btn" type="button">
                            <i class="material-icons" icon="search"></i>
                        </button>
          </form>
        </div>
        <ul class="header-user">
          <li class="item">
            <a class="user-link" href="#">
              <i class="material-icons" icon="person_add"></i>
              <span class="d-none d-md-inline">Login / Register</span>
            </a>
          </li>
        </ul>
      </div>
    </nav>
  </header>
  <main>
    <div class="container" style="height: 1000px">
      <p class="mt-4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
        dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </main>
  <footer>
    <div class="container">
      <p>Footer content</p>
    </div>
  </footer>
</body>


问:
Hiding JupyterLab cell's output by default
I am using JupyterLab to build a bioinformatics pipeline that uses both bash and python scripts.
The first bash script results gives a lot of feedback on every step of the process. However, this feedback is not helpful (unless there was an error) and makes the document less readable.

I would like to be able to hide this cell's output by default, but also to be able to open it when necessary to troubleshoot. I know it's possible to click 3 times on the output to collapse it; I was just wondering whether there is a way to do so by default.

I tried to add the tag specified on here (https://jupyterbook.org/features/hiding.html#Hiding-outputs) to the cell, but it does not seem to work for me.

Thanks for your help.

答:
You may just want to suppress the output using %%capture cell magic as illustrated here. Then you simply remove that magic command from the first line of the cell for times you want to see the output, such as when troubleshooting.

If you want to make it so every time you run the cell, you can later decide to review what was captured you can use the %%capture magic command more as it was meant to be used. By assigning what is captured you can also do something like what the %%bash cell magic allows with handling output streams (see here), too. As described and illustrated here using the utils object you can easily get the stdout and/or stderr as a string, see http://ipython.readthedocs.io/en/stable/api/generated/IPython.utils.capture.html.

So say you put the following at the top of you cell to assign what was captured to out:

%%capture out
```

<p>You can review the stdout stream later with the following:</p>

<pre class="lang-py prettyprint-override"><code>print(out.stdout)
</code>```

Or if you just want part of it, something like print(out.stdout[1:500]). I have some fancier handling illustrated in some blocks of code here.

Body:
You may just want to suppress the output using %%capture cell magic as illustrated here. Then you simply remove that magic command from the first line of the cell for times you want to see the output, such as when troubleshooting.

If you want to make it so every time you run the cell, you can later decide to review what was captured you can use the %%capture magic command more as it was meant to be used. By assigning what is captured you can also do something like what the %%bash cell magic allows with handling output streams (see here), too. As described and illustrated here using the utils object you can easily get the stdout and/or stderr as a string, see http://ipython.readthedocs.io/en/stable/api/generated/IPython.utils.capture.html.

So say you put the following at the top of you cell to assign what was captured to out:

%%capture out

You can review the stdout stream later with the following:

print(out.stdout)

Or if you just want part of it, something like print(out.stdout[1:500]). I have some fancier handling illustrated in some blocks of code here.


问:
WebDriverException: Message: invalid argument: can't kill an exited process with GeckoDriver, Selenium and Python on RaspberryPi3
Server: Raspberry Pi 3

OS: Dietpi - version 159

Geckodriver version: 0.22 for arm

Firefox version: 52.9.0

Python version: 3.5

Selenium version: 3.14.1

Gecko is executable, and is located in /usr/local/bin/

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
import time

options = Options()
options.set_headless(headless=True)
driver = webdriver.Firefox(firefox_options=options)

print('Need your login credential')
username = input('What is your username?:\n')
password = input('What is your password?:\n')
...
...
</code>```

Output:

```<code>root@RPi3:~# python3.5 ITE-bot.py
Traceback (most recent call last):
  File "ITE-bot.py", line 12, in <module>
    driver = webdriver.Firefox(firefox_options=options)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/webdriver.py", line 174, in __init__
    keep_alive=True)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: invalid argument: can't kill an exited process
</code>```

Any idea what is wrong? I've tried google without luck.

答:
I had the same problem, and realized that the real problem was some firefox dependencies not being installed inside the docker container I was testing in.

Try to initiate firefox and check if it returns an error.

Body:
Server: Raspberry Pi 3

OS: Dietpi - version 159

Geckodriver version: 0.22 for arm

Firefox version: 52.9.0

Python version: 3.5

Selenium version: 3.14.1

Gecko is executable, and is located in /usr/local/bin/

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
import time

options = Options()
options.set_headless(headless=True)
driver = webdriver.Firefox(firefox_options=options)

print('Need your login credential')
username = input('What is your username?:\n')
password = input('What is your password?:\n')
...
...

Output:

root@RPi3:~# python3.5 ITE-bot.py
Traceback (most recent call last):
  File "ITE-bot.py", line 12, in <module>
    driver = webdriver.Firefox(firefox_options=options)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/webdriver.py", line 174, in __init__
    keep_alive=True)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: invalid argument: can't kill an exited process

Any idea what is wrong? I've tried google without luck.


问:
Regular expression for remove metadata
I trying to create a application with use some Entity Framework and some old DataSets but I only have a dynamic connection string using entity and need remove metadata at runtime to create a connection string to my database. Anyone know a way to remove all metadata from Entity Framework Connection

I have this

```<code>metadata=res://*/Models.SiteModel.csdl|res://*/Models.SiteModel.ssdl|res://*/Models.SiteModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True"
</code>```

and need only this:

```<code>Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True
</code>```

答:
You can use the EntityConnectionStringBuilder class:

```<code>string connectionString = "metadata=res://*/Models.SiteModel.csdl|res://*/Models.SiteModel.ssdl|res://*/Models.SiteModel.msl;provider=System.Data.SqlClient;provider connection string=\"Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True\"";
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(connectionString);
builder.Metadata = null;
connectionString = builder.ConnectionString;
</code>```

Title: Regular expression for remove metadata

Body:
I trying to create a application with use some Entity Framework and some old DataSets but I only have a dynamic connection string using entity and need remove metadata at runtime to create a connection string to my database. Anyone know a way to remove all metadata from Entity Framework Connection

I have this

metadata=res://*/Models.SiteModel.csdl|res://*/Models.SiteModel.ssdl|res://*/Models.SiteModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True"

and need only this:

Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True

Body:
You can use the EntityConnectionStringBuilder class:

string connectionString = "metadata=res://*/Models.SiteModel.csdl|res://*/Models.SiteModel.ssdl|res://*/Models.SiteModel.msl;provider=System.Data.SqlClient;provider connection string=\"Data Source=(local);Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;MultipleActiveResultSets=True\"";
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(connectionString);
builder.Metadata = null;
connectionString = builder.ConnectionString;


问:
How can I split a previous git commit into separate commits?
I'm trying to track down an error that was introduced somewhere in a certain commit. Unfortunately, that commit consists of a lot of files and I'm not sure where the problem arose. I'd like to do something like "git bisect", but that would only help if I could split the problem commit into a bunch of smaller commits.

I don't have any problem with creating a branch, reverting the problem commit, then re-applying it as a series of commits, but I don't know how to do that. Researching this question here on Stack Overflow results in a lot of answers related to rewriting the history (like this or this), which I don't want to do because the commit in question happened in the past and it's been pushed to a central repository.

How can I split a single commit modifying multiple files into a series of commits, one for each file?

Edit: maybe I haven't explained the question clearly enough.

I have a repository with commits that look like this

```<code>A --- B --- C --- D
</code>```

Commit B is a problem. A bug was introduced and it's been narrowed down to commit B. But commit B consists of a large number of changes to a large number of files, so it's unclear exactly what caused the bug.

What I'd like to do is this:

```<code>A --- B --- C --- D --- revert B --- B1 --- B2  --- ... --- Bn
</code>```

Where B1, B2, ... Bn are commits of the individual files that were changed in commit B.

If I can get the problematic commit broken down, I can then use git bisect to narrow down the problem further.

Is there a way to do this?

答:
Given you already know which commit introduced the error and is just trying to use git to help you understand more about the code:

1.) Create a branch on the commit you want to investigate

e.g. git branch investigation abcdef1 (where abcdef1 is the hash or the problematic commit)

ps: investigation is just a name I chose for the branch... Can be something else...

2.) Go to the new branch you've just created

e.g. git checkout investigation

3.) Undo the problematic commit (only affects this new branch, so no damage to the original history in your main branch)

e.g. git reset HEAD~1

At this point, all the files that were added/changed/deleted will be back to their original state just before the commit was done. You can do a git status to see all the differences.

From here, you can start creating the commits as you wish, either one by file, or grouping some of them... It's up to you.

Of course, this is just for you to track down where the bug is... You would not merge this branch back to master or anything like that... It's just a throwaway branch for the purposes of investigating the bug... Once you know where the bug is, go back to master (or whatever branch is your trunk one) and fix the bug there, and then just delete the investigation branch.

Body:
I'm trying to track down an error that was introduced somewhere in a certain commit. Unfortunately, that commit consists of a lot of files and I'm not sure where the problem arose. I'd like to do something like "git bisect", but that would only help if I could split the problem commit into a bunch of smaller commits.

I don't have any problem with creating a branch, reverting the problem commit, then re-applying it as a series of commits, but I don't know how to do that. Researching this question here on Stack Overflow results in a lot of answers related to rewriting the history (like this or this), which I don't want to do because the commit in question happened in the past and it's been pushed to a central repository.

How can I split a single commit modifying multiple files into a series of commits, one for each file?

Edit: maybe I haven't explained the question clearly enough.

I have a repository with commits that look like this

A --- B --- C --- D

Commit B is a problem. A bug was introduced and it's been narrowed down to commit B. But commit B consists of a large number of changes to a large number of files, so it's unclear exactly what caused the bug.

What I'd like to do is this:

A --- B --- C --- D --- revert B --- B1 --- B2  --- ... --- Bn

Where B1, B2, ... Bn are commits of the individual files that were changed in commit B.

If I can get the problematic commit broken down, I can then use git bisect to narrow down the problem further.

Is there a way to do this?


问:
dyld: Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib
Using electron-builder to build Windows app, When signing up, I got this error :</p>

```<code>dyld: Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib
  Referenced from: /Users/puss/Library/Caches/electron-builder/winCodeSign/winCodeSign-1.7.0/darwin/osslsigncode
  Reason: image not found
</code>```

答:
I had the same problem. In my case, for a legacy Rails 2.4 app. It seems brew had updated /usr/local/opt/openssl to symlink to openssl@1.1/1.1.1d.

After trying several other things, I fixed it by manually updating the symlink /usr/local/opt/openssl to point to the 1.0.2s version that was already on my system:

```<code>MacBook-Pro/usr/local/opt(:|✔) % pwd
/usr/local/opt
MacBook-Pro/usr/local/opt(:|✔) % ll openssl*
lrwxr-xr-x  1 dhempy  admin  24 Feb 19 11:36 openssl -> ../Cellar/openssl/1.0.2s
lrwxr-xr-x  1 dhempy  admin  28 Feb 19 08:55 openssl@1.1 -> ../Cellar/openssl@1.1/1.1.1d
</code>```

Hopefully this is one-and-done for me, and I won't have to reapply that symlink after every update.

Body:
Using electron-builder to build Windows app, When signing up, I got this error :

dyld: Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib
  Referenced from: /Users/puss/Library/Caches/electron-builder/winCodeSign/winCodeSign-1.7.0/darwin/osslsigncode
  Reason: image not found

Body:
I had the same problem. In my case, for a legacy Rails 2.4 app. It seems brew had updated /usr/local/opt/openssl to symlink to openssl@1.1/1.1.1d.

After trying several other things, I fixed it by manually updating the symlink /usr/local/opt/openssl to point to the 1.0.2s version that was already on my system:

MacBook-Pro/usr/local/opt(:|✔) % pwd
/usr/local/opt
MacBook-Pro/usr/local/opt(:|✔) % ll openssl*
lrwxr-xr-x  1 dhempy  admin  24 Feb 19 11:36 openssl -> ../Cellar/openssl/1.0.2s
lrwxr-xr-x  1 dhempy  admin  28 Feb 19 08:55 openssl@1.1 -> ../Cellar/openssl@1.1/1.1.1d

Hopefully this is one-and-done for me, and I won't have to reapply that symlink after every update.


问:
React.js - input losing focus when rerendering
I am just writing to text input and in onChange event I call setState, so React re-renders my UI. The problem is that the text input always loses focus, so I need to focus it again for each letter :D.

```<code>var EditorContainer = React.createClass({

    componentDidMount: function () {
        $(this.getDOMNode()).slimScroll({height: this.props.height, distance: '4px', size: '8px'});
    },

    componentDidUpdate: function () {
        console.log("zde");
        $(this.getDOMNode()).slimScroll({destroy: true}).slimScroll({height: 'auto', distance: '4px', size: '8px'});
    },

    changeSelectedComponentName: function (e) {
        //this.props.editor.selectedComponent.name = $(e.target).val();
        this.props.editor.forceUpdate();
    },

    render: function () {

        var style = {
            height: this.props.height + 'px'
        };
        return (
            <div className="container" style={style}>
                <div className="row">
                    <div className="col-xs-6">
                    {this.props.selected ? <h3>{this.props.selected.name}</h3> : ''}
                    {this.props.selected ? <input type="text" value={this.props.selected.name} onChange={this.changeSelectedComponentName} /> : ''}
                    </div>
                    <div className="col-xs-6">
                        <ComponentTree editor={this.props.editor} components={this.props.components}/>
                    </div>
                </div>
            </div>
        );
    }

});
</code>```

答: I had this issue and the problem turned out to be that I was using a functional component and linking up with a parent component's state. If I switched to using a class component, the problem went away. Hopefully there is a way around this when using functional components as it's a lot more convenient for simple item renderers et al.</p>

Body:
I am just writing to text input and in onChange event I call setState, so React re-renders my UI. The problem is that the text input always loses focus, so I need to focus it again for each letter :D.

var EditorContainer = React.createClass({

    componentDidMount: function () {
        $(this.getDOMNode()).slimScroll({height: this.props.height, distance: '4px', size: '8px'});
    },

    componentDidUpdate: function () {
        console.log("zde");
        $(this.getDOMNode()).slimScroll({destroy: true}).slimScroll({height: 'auto', distance: '4px', size: '8px'});
    },

    changeSelectedComponentName: function (e) {
        //this.props.editor.selectedComponent.name = $(e.target).val();
        this.props.editor.forceUpdate();
    },

    render: function () {

        var style = {
            height: this.props.height + 'px'
        };
        return (

                    {this.props.selected ?
{this.props.selected.name}
 : ''}
                    {this.props.selected ? <input type="text" value={this.props.selected.name} onChange={this.changeSelectedComponentName} /> : ''}

                        <ComponentTree editor={this.props.editor} components={this.props.components}/>

        );
    }

});


问:
"Parallel.For" for Java?
I was wondering if there is a Parallel.For equivalent to the .net version for Java?

If there is could someone please supply an example? thanks!

答:
There is a equivalent for Parallel.For available as a java extension. It is called Ateji PX, they have a free version you can play with. http://www.ateji.com/px/index.html

It is the exact equivalent of parallel.for and looks similar to.

For ||

More examples and explaination on wikipedia:
http://en.wikipedia.org/wiki/Ateji_PX

Closed thing in Java IMO

Title: "Parallel.For" for Java?