问:
How can one use regex to capture the text occurring between lines beginning with a single semicolon?
I want to capture the text between lines which begin with single semicolons:

sample input:

```<code>s = '''
;

the color blue

;

the color green

;

the color red

;
'''
</code>```

this is the desired output:

```<code>['the color blue', 'the color green', 'the color red']
</code>```

this attempted solution doesn't work:

```<code>import re
pat = r'^;(.*)^;'
r = re.findall(pat, s, re.S|re.M)
print(r)
</code>```

this is the wrong output:

```<code>['\n\nthe color blue\n\n;\n\nthe color green\n\n;\n\nthe color red\n\n']
</code>```

答:
Treat it like delimiters.

(?sm)^;\s*\r?\n(.*?)\s*(?=^;\s*\r?\n)

https://regex101.com/r/4tKX0F/1

Explained

```<code> (?sm)                         # Modifiers: dot-all, multi-line
 ^ ; \s* \r? \n                # Begining delimiter
 ( .*? )                       # (1), Text
 \s*                           # Wsp trim
 (?= ^ ; \s* \r? \n )          # End delimiter
</code>```

Body:
I want to capture the text between lines which begin with single semicolons:

sample input:

s = '''
;

the color blue

;

the color green

;

the color red

;
'''

this is the desired output:

['the color blue', 'the color green', 'the color red']

this attempted solution doesn't work:

import re
pat = r'^;(.*)^;'
r = re.findall(pat, s, re.S|re.M)
print(r)

this is the wrong output:

['\n\nthe color blue\n\n;\n\nthe color green\n\n;\n\nthe color red\n\n']

Body:
Treat it like delimiters.

(?sm)^;\s*\r?\n(.*?)\s*(?=^;\s*\r?\n)

https://regex101.com/r/4tKX0F/1

Explained

 (?sm)                         # Modifiers: dot-all, multi-line
 ^ ; \s* \r? \n                # Begining delimiter
 ( .*? )                       # (1), Text
 \s*                           # Wsp trim
 (?= ^ ; \s* \r? \n )          # End delimiter


来源: stackexchange

问:
log4j2 TcpSocketServer does not replace any "{}" in message
I have a spring boot(v1.5.4) web application which use log4j-2.7 for logging.
It works well when write log message to file or console, but when send message to TcpSocketServer, the log server just output the message without the "{}" formatting. for example, for this code:

```<code>logger.info("Request from [{}] to [{}]", ipInfo, reqPath);
</code>```

The RollingfileAppender and ConsoleAppender will output:

```<code>INFO  2017-07-06 16:46:07,929 [127.0.0.1][/senten/align] AuthFilter (http-nio-8180-exec-2) Request from [127.0.0.1] to [/senten/align]
</code>```

But the SocketAppender just ouput:

```<code>INFO  2017-07-06 16:46:07,929 [127.0.0.1][/senten/align] AuthFilter (http-nio-8180-exec-2) Request from [{}] to [{}]
</code>```

This is my config with SocketAppenders in log4j.xml

```<code><Appenders>
    <Socket name="socket" host="127.0.0.1" port="9898">
        <SerializedLayout />
    </Socket>
    ........
</Appenders>
</code>```

This is my config file log4j2-socket.xml for TcpSocketServer:

```<code><Configuration status="WARN">
    <Appenders>
        <RollingFile name="default" fileName="Logs/app.log"
            filePattern="Logs/${date:yyyy-MM}/app-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout>
                <Pattern>%-5p %d [%X{ip}][%X{reqPath}] %c{1} (%t) %m %ex%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval = "30" modulate="true"/>
                <SizeBasedTriggeringPolicy size="200 MB" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="default" level="DEBUG" />
        </Root>
    </Loggers>
</Configuration>
</code>```

And, I use this command for start TcpSocketServer:

```<code>java -classpath log4j-core-2.7.jar:log4j-api-2.7.jar:jcommander-1.48.jar org.apache.logging.log4j.core.net.server.TcpSocketServer -p 9898 -c log4j2-socket.xml
</code>```

Does anybody know what's going wrong here, and how to fix it? Thanks!

答:
I file a bug on JIRA of log4j2. A good guy helps me to resolve this problem.

The solution is update to log4j-2.8.2, and adding this arguments for starting TcpSocketServer:

```<code>--classes java.util.Collections$UnmodifiableMap --classes java.util.HashMap
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a spring boot(v1.5.4) web application which use log4j-2.7 for logging.
It works well when write log message to file or console, but when send message to TcpSocketServer, the log server just output the message without the "{}" formatting. for example, for this code:

logger.info("Request from [{}] to [{}]", ipInfo, reqPath);

The RollingfileAppender and ConsoleAppender will output:

INFO  2017-07-06 16:46:07,929 [127.0.0.1][/senten/align] AuthFilter (http-nio-8180-exec-2) Request from [127.0.0.1] to [/senten/align]

But the SocketAppender just ouput:

INFO  2017-07-06 16:46:07,929 [127.0.0.1][/senten/align] AuthFilter (http-nio-8180-exec-2) Request from [{}] to [{}]

This is my config with SocketAppenders in log4j.xml

<Appenders>
    <Socket name="socket" host="127.0.0.1" port="9898">
        <SerializedLayout />
    </Socket>
    ........
</Appenders>

This is my config file log4j2-socket.xml for TcpSocketServer:

<Configuration status="WARN">
    <Appenders>
        <RollingFile name="default" fileName="Logs/app.log"
            filePattern="Logs/${date:yyyy-MM}/app-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout>
                <Pattern>%-5p %d [%X{ip}][%X{reqPath}] %c{1} (%t) %m %ex%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval = "30" modulate="true"/>
                <SizeBasedTriggeringPolicy size="200 MB" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="default" level="DEBUG" />
        </Root>
    </Loggers>
</Configuration>

And, I use this command for start TcpSocketServer:

java -classpath log4j-core-2.7.jar:log4j-api-2.7.jar:jcommander-1.48.jar org.apache.logging.log4j.core.net.server.TcpSocketServer -p 9898 -c log4j2-socket.xml

Does anybody know what's going wrong here, and how to fix it? Thanks!

Body:
I file a bug on JIRA of log4j2. A good guy helps me to resolve this problem.

The solution is update to log4j-2.8.2, and adding this arguments for starting TcpSocketServer:

--classes java.util.Collections$UnmodifiableMap --classes java.util.HashMap


问:
How to change a cell value periodically in libreoffice calc?
The title says it all...

For example, if I want to have a cell which displays the current time and auto updates minute by minute (well, I think we call that a clock), how do I do it?

Is there a simple function implemented already or should I create a macro and assign it to a specific event?

EDIT: Following the provided answer by @Jim K, I want to be more clear about what I want. The "clock" example above was here to make it simple to understand, but what I really want is in the title: a cell value which changes periodically, be it a string, a number, a date...

答:
First enter =NOW() in a cell, and format the number by going to Format -> Cells.

Next, this Basic macro (from here) recalculates every minute.  Go to Tools -> Customize and assign it to the Open Document event.

Sub RecalculatePeriodically
   Const secs = 60
   On Error Goto ErrorHandler
   Do While True
      Wait(1000 * secs)
      ThisComponent.calculateAll()
   Loop
   ErrorHandler:
       'Document was probably closed
End Sub
```

<p>However, this crashes when exiting LibreOffice.  So instead, use the following threaded Python macro (like here).  Assign <code>keep_recalculating_thread</code> to the <code>Open Document</code> event.</p>

<pre class="lang-py prettyprint-override"><code>import time
from threading import Thread
import uno

def keep_recalculating_thread(action_event=None):
    t = Thread(target = keep_recalculating)
    t.start()

def keep_recalculating():
    oDoc = XSCRIPTCONTEXT.getDocument()
    while hasattr(oDoc, 'calculateAll'):
        oDoc.calculateAll()
        time.sleep(60)

g_exportedScripts = keep_recalculating_thread,
</code>```

Another idea is at https://ask.libreoffice.org/en/question/5327/how-can-i-run-a-macro-at-regular-time-interval/, although it requires linking to another file which seems cumbersome.

EDIT:

Maybe you are looking for something like this?  Test it by starting with a blank spreadsheet and entering 1 in cell A1.

def keep_changing_cell(action_event=None):
    t = Thread(target = keep_changing_thread)
    t.start()

def keep_changing_thread():
    oDoc = XSCRIPTCONTEXT.getDocument()
    oSheet = oDoc.CurrentController.ActiveSheet
    COLUMN_A = 0
    FIRST_ROW = 0
    oCell = oSheet.getCellByPosition(COLUMN_A, FIRST_ROW)
    while hasattr(oDoc, 'calculateAll'):
        oCell.setValue(oCell.getValue() + 1)
        time.sleep(2)
```

Body:
First enter =NOW() in a cell, and format the number by going to Format -> Cells.

Next, this Basic macro (from here) recalculates every minute.  Go to Tools -> Customize and assign it to the Open Document event.

Sub RecalculatePeriodically
   Const secs = 60
   On Error Goto ErrorHandler
   Do While True
      Wait(1000 * secs)
      ThisComponent.calculateAll()
   Loop
   ErrorHandler:
       'Document was probably closed
End Sub

However, this crashes when exiting LibreOffice.  So instead, use the following threaded Python macro (like here).  Assign keep_recalculating_thread to the Open Document event.

import time
from threading import Thread
import uno

def keep_recalculating_thread(action_event=None):
    t = Thread(target = keep_recalculating)
    t.start()

def keep_recalculating():
    oDoc = XSCRIPTCONTEXT.getDocument()
    while hasattr(oDoc, 'calculateAll'):
        oDoc.calculateAll()
        time.sleep(60)

g_exportedScripts = keep_recalculating_thread,

Another idea is at https://ask.libreoffice.org/en/question/5327/how-can-i-run-a-macro-at-regular-time-interval/, although it requires linking to another file which seems cumbersome.

EDIT:

Maybe you are looking for something like this?  Test it by starting with a blank spreadsheet and entering 1 in cell A1.

def keep_changing_cell(action_event=None):
    t = Thread(target = keep_changing_thread)
    t.start()

def keep_changing_thread():
    oDoc = XSCRIPTCONTEXT.getDocument()
    oSheet = oDoc.CurrentController.ActiveSheet
    COLUMN_A = 0
    FIRST_ROW = 0
    oCell = oSheet.getCellByPosition(COLUMN_A, FIRST_ROW)
    while hasattr(oDoc, 'calculateAll'):
        oCell.setValue(oCell.getValue() + 1)
        time.sleep(2)


问:
Get modified files in FTP folder

I have a local folder which contains files and directories (>2000
files).

I uploaded this entire folder on my ftp.

Now for example let's say my ftp folder is called FTPFolder and my local folder is called LOCALFolder. These two folders are exactly the same for now.

And let's say the both folders contain a file called text.txt.

Now what I would like to do:

If I change the test.txt on the FTP, how could I detect it in C#?
Getting all local files and all FTPfiles and then comparing them is just too long. Has anyone got another way of doing this ?

Basically the goal is to download all files on the FTP which are different from the same files but locally.

答:
Usual approach to synchronize local folder with FTP folder, is to compare file modification times.

Assuming that you are using FtpWebRequest .NET class, this is actually not trivial to implement. It does not have any standard way to retrieve file modification time.

See Retrieving creation date of file (FTP).

Even better would be to use a file checksum, but that's hardly possible.

See FTP: copy, check integrity and delete.

It would be way easier to use a 3rd party FTP client library that has a better support for retrieving the modification time. And even more easier, if you use FTP client library that supports a synchronization out of the box.

For example with WinSCP .NET assembly you can use Session.SynchronizeDirectories method:

```<code>// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Synchronize files
    session.SynchronizeDirectories(
        SynchronizationMode.Local, @"C:\local\path", "/remote/path", false).Check();
}
</code>```

WinSCP GUI can generate a code template for you.

(I'm the author of WinSCP)

Title: Get modified files in FTP folder

Body:
Usual approach to synchronize local folder with FTP folder, is to compare file modification times.

Assuming that you are using FtpWebRequest .NET class, this is actually not trivial to implement. It does not have any standard way to retrieve file modification time.

See Retrieving creation date of file (FTP).

Even better would be to use a file checksum, but that's hardly possible.

See FTP: copy, check integrity and delete.

It would be way easier to use a 3rd party FTP client library that has a better support for retrieving the modification time. And even more easier, if you use FTP client library that supports a synchronization out of the box.

For example with WinSCP .NET assembly you can use Session.SynchronizeDirectories method:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Synchronize files
    session.SynchronizeDirectories(
        SynchronizationMode.Local, @"C:\local\path", "/remote/path", false).Check();
}

WinSCP GUI can generate a code template for you.

(I'm the author of WinSCP)

ContentLicense: CC BY-SA 4.0


问:
How to keep formula in form field when add new record using form in access
I have a form to entry new data to table in Access 2010.

I want Request ID field to be Max(Req_Number)+1 from current table, whenever user add new record and want it to be filled automatically, also Req_Number is the key. When use Data Mode all fields are blank so I wonder how to lock one filed with a function when entry data to a table using form in access?

答:
The RequestID text box should be Locked and Disabled. Add code to the form's Before Insert event as follows:

```<code>Private Sub Form_BeforeInsert(Cancel As Integer)
On Error GoTo PROC_ERR

    RequestID = Nz(DMax("Req_Number", "myTable"), 0) + 1

PROC_EXIT:
    On Error Resume Next
    Exit Sub

PROC_ERR:
    MsgBox "Error " & Err.Number & " - " & Err.Description
    Resume PROC_EXIT

End Sub
</code>```

Body:
The RequestID text box should be Locked and Disabled. Add code to the form's Before Insert event as follows:

Private Sub Form_BeforeInsert(Cancel As Integer)
On Error GoTo PROC_ERR

    RequestID = Nz(DMax("Req_Number", "myTable"), 0) + 1

PROC_EXIT:
    On Error Resume Next
    Exit Sub

PROC_ERR:
    MsgBox "Error " & Err.Number & " - " & Err.Description
    Resume PROC_EXIT

End Sub


问:
i want to minimize my 1st templatex
I just finished creating my first template by HTML and CSS
but I want to minimize it and make it 75% of like what it is right now.
I don't want to change all the numbers because it will take a lot of time.

this is the 100% template:

and here is the 75% template which is better than the 1st :

答: You could use this css property : transform: scale(0.75) on your  tag, but I don't know if it would have the expected behaviour

Title: i want to minimize my 1st templatex

Body: You could use this css property : transform: scale(0.75) on your <body> tag, but I don't know if it would have the expected behaviour


问:
MYSQL specific search
I'm trying to ORDER BY a MYSQL query correctly. I need the rand() to include the query with the shortest length, the query with the second shortest length, and the query with the third shortest length. Is there a way to do that with just MYSQL?

```<code>SELECT input FROM tableName WHERE input LIKE '%one%' ORDER BY length(input) ASC, rand() limit 1;

one
one one
one one one
one one one one
</code>```

In this case, the query only include the rand() with the lowest length. So basically, I need the rand() to include the:

```<code>one
one one
one one one
</code>```

So that it selects one of these randomly.

答:
```<code> order by length(input) asc limit 3;
</code>```

<p>It will return </p>

```<code>one
one one
one one one
</code>```

Title: MYSQL specific search

Body:
I'm trying to ORDER BY a MYSQL query correctly. I need the rand() to include the query with the shortest length, the query with the second shortest length, and the query with the third shortest length. Is there a way to do that with just MYSQL?

SELECT input FROM tableName WHERE input LIKE '%one%' ORDER BY length(input) ASC, rand() limit 1;

one
one one
one one one
one one one one

In this case, the query only include the rand() with the lowest length. So basically, I need the rand() to include the:

one
one one
one one one

So that it selects one of these randomly.

Body:
 order by length(input) asc limit 3;

It will return

one
one one
one one one


问:
Performance issue with grep -f
I'm using grep to search for several regular expressions in a single file.
In particular, I'm considering a 100 MB file with English subtitles  and running the following regular expressions stored in file patterns.txt:

```<code>Cas.*eharden
acr.*otic
syn.*thesizing
sub.*abbot
iss.*acharite
bot.*onne
dis.*similatory
ove.*rmantel
isa.*tin
ado.*nijah
sol.*ution
zei.*st
fam.*ousness
inq.*uisitress
aor.*tography
via.*duct
ama.*sa
der.*ive
pie.*tas
kit.*chenette
</code>```

While doing so I observed that the time required by grep does not grow linearly with the number of regular expressions. Indeed, it seems to grow exponentially.

Experiments

System: Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz; 4 Cores; 8 GB RAM

Case 1: 20 regexps

Command grep -c -f patterns.txt subtitles.txt counts 2214 occurrences and takes

2,19s user 0,00s system 99% cpu 2,192 total.

Case 2: 30 regexps

If I add the following expressions to patterns.txt

```<code>ort.*hros
ove.*ridentify
mis.*tiest
pay.*ne
int.*erchasing
jej.*uneness
sta.*lactiform
und.*ertrain
cob.*bles
Sub.*category
</code>```

Command grep -c -f patterns.txt subtitles.txt counts 2894 occurrences and takes 71,35s user 0,06s system 99% cpu 1:11,42 total.

Case 3: 35 regexps

Adding five more expressions:

```<code>dis.*embosom
imp.*ortunateness
ema.*thion
rho.*mb
haz.*elwood
</code>```

Command grep -c -f patterns.txt subtitles.txt counts 2904 occurrences and takes 211,18s user 0,22s system 99% cpu 3:31,58 total

Why grep -f exhibit such behavior? What is it doing internally?

The whole set of regexp I've been using can be found here

答:
From reading the grep source code, it appears that the regex's in your file are not executed one at a time. Rather, they're read all at once into one big regex:

```<code>case 'f':
  fp = STREQ (optarg, "-") ? stdin : fopen (optarg, O_TEXT ? "rt" : "r");
  if (!fp)
    error (EXIT_TROUBLE, errno, "%s", optarg);
  for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
    ;
  keys = xrealloc (keys, keyalloc);
  oldcc = keycc;
  while ((cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) != 0)
    {
      keycc += cc;
      if (keycc == keyalloc - 1)
        keys = x2nrealloc (keys, &keyalloc, sizeof *keys);
    }
</code>```

This is confirmed watching an strace of grep run on your command:

```<code>open("testreg", O_RDONLY)               = 3
fstat(3, {st_mode=S_IFREG|0664, st_size=124, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fd8912fe000
read(3, "ort.*hros\nove.*ridentify\nmis.*ti"..., 4096) = 124
</code>```

Backtracking regex implementations (which allow backreferences), do not run in O(n) time, but rather O(2^m), which can lead to catastrophic runtimes.

Your assumption that grep is simply looping over each regex in turn, compiling each into a DFA and then executing it is perfectly reasonable. However, it appears that the grep authors have assumed that by running your regex's all at once, they can probably do so more efficiently in some cases. The result is that by adding regex's to your file, you're falling into the O(2^m) runtime, resulting in an exponential increase in your runtime.

As it turns out, it may be more efficient to simply loop over each regex executing them one at a time, forcing your grep to run linearly. On my laptop, running grep version 2.20, I get the following results using only the last 29 regex's in the file you provided:

```<code>[Downloads]$ wc -l patterns.txt
29 patterns.txt

[Downloads]$ time grep -c -f ~/Downloads/patterns.txt /usr/share/dict/linux.words
117

real    0m3.092s
user    0m3.027s
sys     0m0.047s

[csd@alcazar Downloads]$ time for regex in `cat ~/Downloads/patterns.txt`; do grep -c $regex /usr/share/dict/linux.words > /dev/null; done
real    0m0.474s
user    0m0.312s
sys     0m0.158s
</code>```

Title: Performance issue with grep -f

Body:
I'm using grep to search for several regular expressions in a single file.
In particular, I'm considering a 100 MB file with English subtitles  and running the following regular expressions stored in file patterns.txt:

Cas.*eharden
acr.*otic
syn.*thesizing
sub.*abbot
iss.*acharite
bot.*onne
dis.*similatory
ove.*rmantel
isa.*tin
ado.*nijah
sol.*ution
zei.*st
fam.*ousness
inq.*uisitress
aor.*tography
via.*duct
ama.*sa
der.*ive
pie.*tas
kit.*chenette

While doing so I observed that the time required by grep does not grow linearly with the number of regular expressions. Indeed, it seems to grow exponentially.

Experiments

System: Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz; 4 Cores; 8 GB RAM

Case 1: 20 regexps

Command grep -c -f patterns.txt subtitles.txt counts 2214 occurrences and takes

2,19s user 0,00s system 99% cpu 2,192 total.

Case 2: 30 regexps

If I add the following expressions to patterns.txt

ort.*hros
ove.*ridentify
mis.*tiest
pay.*ne
int.*erchasing
jej.*uneness
sta.*lactiform
und.*ertrain
cob.*bles
Sub.*category

Command grep -c -f patterns.txt subtitles.txt counts 2894 occurrences and takes 71,35s user 0,06s system 99% cpu 1:11,42 total.

Case 3: 35 regexps

Adding five more expressions:

dis.*embosom
imp.*ortunateness
ema.*thion
rho.*mb
haz.*elwood

Command grep -c -f patterns.txt subtitles.txt counts 2904 occurrences and takes 211,18s user 0,22s system 99% cpu 3:31,58 total

Why grep -f exhibit such behavior? What is it doing internally?

The whole set of regexp I've been using can be found here

Body:
From reading the grep source code, it appears that the regex's in your file are not executed one at a time. Rather, they're read all at once into one big regex:

case 'f':
  fp = STREQ (optarg, "-") ? stdin : fopen (optarg, O_TEXT ? "rt" : "r");
  if (!fp)
    error (EXIT_TROUBLE, errno, "%s", optarg);
  for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
    ;
  keys = xrealloc (keys, keyalloc);
  oldcc = keycc;
  while ((cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) != 0)
    {
      keycc += cc;
      if (keycc == keyalloc - 1)
        keys = x2nrealloc (keys, &keyalloc, sizeof *keys);
    }

This is confirmed watching an strace of grep run on your command:

open("testreg", O_RDONLY)               = 3
fstat(3, {st_mode=S_IFREG|0664, st_size=124, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fd8912fe000
read(3, "ort.*hros\nove.*ridentify\nmis.*ti"..., 4096) = 124

Backtracking regex implementations (which allow backreferences), do not run in O(n) time, but rather O(2^m), which can lead to catastrophic runtimes.

Your assumption that grep is simply looping over each regex in turn, compiling each into a DFA and then executing it is perfectly reasonable. However, it appears that the grep authors have assumed that by running your regex's all at once, they can probably do so more efficiently in some cases. The result is that by adding regex's to your file, you're falling into the O(2^m) runtime, resulting in an exponential increase in your runtime.

As it turns out, it may be more efficient to simply loop over each regex executing them one at a time, forcing your grep to run linearly. On my laptop, running grep version 2.20, I get the following results using only the last 29 regex's in the file you provided:

[Downloads]$ wc -l patterns.txt
29 patterns.txt

[Downloads]$ time grep -c -f ~/Downloads/patterns.txt /usr/share/dict/linux.words
117

real    0m3.092s
user    0m3.027s
sys     0m0.047s

[csd@alcazar Downloads]$ time for regex in `cat ~/Downloads/patterns.txt`; do grep -c $regex /usr/share/dict/linux.words > /dev/null; done
real    0m0.474s
user    0m0.312s
sys     0m0.158s


问:
"Do nothing" in the else-part of the ternary operator?
What's the standard line to add to the ternary operator in order to do nothing if the condition is not met?

Example:

```<code>int a = 0;
a > 10 ? a = 5 : /*do nothing*/;
</code>```

Using a seems to do the trick, but I am wondering if there is a more generally accepted way.

答:
That will do it:

```<code>a = a > 10 ? 5 : a;
</code>```

or simply:

```<code>if (a > 10) a = 5;
</code>```

Body:
What's the standard line to add to the ternary operator in order to do nothing if the condition is not met?

Example:

int a = 0;
a > 10 ? a = 5 : /*do nothing*/;

Using a seems to do the trick, but I am wondering if there is a more generally accepted way.

Body:
That will do it:

a = a > 10 ? 5 : a;

or simply:

if (a > 10) a = 5;


问:
Javascript code review - Make element "toggleable"
I wrote a Javascript function that solves a typical problem: Given an HTML element, whenever the user clicks on it another HTML element will be shown, on another click it will be hidden.

As I am not a big Javascript guru and I have just recently started to discover the real power of Javascript, I am sure there is at least a couple of problems with my code.

Any feedback is highly appreciated.

(Note that the I'm using jQuery)

```<code>/**
 * Makes an HTML element with given with ID "targetId" being toggleable
 * controlled by the click event of the HTML element with ID "controlId".
 * The "controlFunction" is a function that should return true/false based
 * on a whether the target should be showed or hidden.
 * If there is no controlFunction "!targetElement.is(":visible")" will be used.
 * The controlFunction is applied in the context of the control element (so
 * the "this" is going to be the controlElement.
 *
 * @param targetId
 * @param controlId
 * @param controlFunction
 * @returns
 */

var makeToggleableOnClick = function (targetId, controlId, controlFunction) {
    var targetElement, controlElement, showHideValue;

    if (!targetId || !controlId) {
        return;
    }
    targetElement = $('#' + targetId);
    controlElement = $('#' + controlId);

    controlElement.css('cursor','pointer');
    controlElement.click(function() {
        if (controlFunction) {
            showHideValue = controlFunction.apply(controlElement,[]);
        } else {
            showHideValue = !targetElement.is(":visible");
        }

        if (showHideValue) {
            targetElement.slideDown();
        } else {
            targetElement.slideUp();
        }
    });
}

/************/
/* EXAMPLE  */
/************/

<input id="controlElement" type="checkbox"/>
<div id="targetElement">
  Bla-bla.
</div>

<script type="text/javascript">
  makeToggleableOnClick('targetElement', 'controlElement', function() {
    return this.is(':checked');
  });
</script>
</code>```

答: You could use http://api.jquery.com/toggle/ instead</p>

Body:
I wrote a Javascript function that solves a typical problem: Given an HTML element, whenever the user clicks on it another HTML element will be shown, on another click it will be hidden.

As I am not a big Javascript guru and I have just recently started to discover the real power of Javascript, I am sure there is at least a couple of problems with my code.

Any feedback is highly appreciated.

(Note that the I'm using jQuery)

/**
 * Makes an HTML element with given with ID "targetId" being toggleable
 * controlled by the click event of the HTML element with ID "controlId".
 * The "controlFunction" is a function that should return true/false based
 * on a whether the target should be showed or hidden.
 * If there is no controlFunction "!targetElement.is(":visible")" will be used.
 * The controlFunction is applied in the context of the control element (so
 * the "this" is going to be the controlElement.
 *
 * @param targetId
 * @param controlId
 * @param controlFunction
 * @returns
 */

var makeToggleableOnClick = function (targetId, controlId, controlFunction) {
    var targetElement, controlElement, showHideValue;

    if (!targetId || !controlId) {
        return;
    }
    targetElement = $('#' + targetId);
    controlElement = $('#' + controlId);

    controlElement.css('cursor','pointer');
    controlElement.click(function() {
        if (controlFunction) {
            showHideValue = controlFunction.apply(controlElement,[]);
        } else {
            showHideValue = !targetElement.is(":visible");
        }

        if (showHideValue) {
            targetElement.slideDown();
        } else {
            targetElement.slideUp();
        }
    });
}

/************/
/* EXAMPLE  */
/************/

<input id="controlElement" type="checkbox"/>

  Bla-bla.

ContentLicense: CC BY-SA 2.5


问:
Filter Json Listview With a EditText Android
Trying to filter my listview with a edittext, everytime i enter some text the listview becomes blank, can anyone tell me what I'm doing wrong and how i can solve this</p>

```<code>search.addTextChangedListener(new TextWatcher (){
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    public void beforeTextChanged(CharSequence arg0, int arg1,
    int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    public void onTextChanged(CharSequence cs, int arg1, int arg2,
    int arg3) {
        // TODO Auto-generated method stub

        String searchString = cs.toString();//wsSearch.getText().toString();
       /* if(searchString.length() != 2) {
            adapter2 = new Adapter(MainActivity.this, array);
            listView.setAdapter(adapter2);
            return;
        }*/
        for (int i = 0; i < array.size(); i++)
        {
            String currentString = array.get(i).getTitulo();
            if (searchString.equalsIgnoreCase(currentString))
            {
                mTemp.add(array.get(i));
            }
        }
        adapter2 = new Adapter(MainActivity.this, mTemp);
        listView.setAdapter(adapter2);

    }

});
}
</code>```

答:
Try this :

```<code>    search.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            String searchString = arg0.toString();//wsSearch.getText().toString();
   /* if(searchString.length() != 2) {
        adapter2 = new Adapter(MainActivity.this, array);
        listView.setAdapter(adapter2);
        return;
    }*/
            mTemp.clear()
            for (int i = 0; i < array.size(); i++)
            {
                String currentString = array.get(i).getTitulo();
                if (currentString.contains(searchString))
                {
                    mTemp.add(array.get(i));
                }
            }
            adapter2 = new Adapter(MainActivity.this, mTemp);
            listView.setAdapter(adapter2);

        }

        public void beforeTextChanged(CharSequence arg0, int arg1,
                                      int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                  int arg3) {
            // TODO Auto-generated method stub
            //BAPTISMAL_SONG.this.adapter2.getFilter().filter(cs);

        }

    });
</code>```

Hope this helps.

Body:
Trying to filter my listview with a edittext, everytime i enter some text the listview becomes blank, can anyone tell me what I'm doing wrong and how i can solve this

search.addTextChangedListener(new TextWatcher (){
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    public void beforeTextChanged(CharSequence arg0, int arg1,
    int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    public void onTextChanged(CharSequence cs, int arg1, int arg2,
    int arg3) {
        // TODO Auto-generated method stub

        String searchString = cs.toString();//wsSearch.getText().toString();
       /* if(searchString.length() != 2) {
            adapter2 = new Adapter(MainActivity.this, array);
            listView.setAdapter(adapter2);
            return;
        }*/
        for (int i = 0; i < array.size(); i++)
        {
            String currentString = array.get(i).getTitulo();
            if (searchString.equalsIgnoreCase(currentString))
            {
                mTemp.add(array.get(i));
            }
        }
        adapter2 = new Adapter(MainActivity.this, mTemp);
        listView.setAdapter(adapter2);

    }

});
}

Body:
Try this :

    search.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            String searchString = arg0.toString();//wsSearch.getText().toString();
   /* if(searchString.length() != 2) {
        adapter2 = new Adapter(MainActivity.this, array);
        listView.setAdapter(adapter2);
        return;
    }*/
            mTemp.clear()
            for (int i = 0; i < array.size(); i++)
            {
                String currentString = array.get(i).getTitulo();
                if (currentString.contains(searchString))
                {
                    mTemp.add(array.get(i));
                }
            }
            adapter2 = new Adapter(MainActivity.this, mTemp);
            listView.setAdapter(adapter2);

        }

        public void beforeTextChanged(CharSequence arg0, int arg1,
                                      int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                  int arg3) {
            // TODO Auto-generated method stub
            //BAPTISMAL_SONG.this.adapter2.getFilter().filter(cs);

        }

    });

Hope this helps.


问:
MVC user TimeSpan properties limitations and dependancy on each other
I ran into problem when creating user booking app. Basically, apart from basic property limitations like min and max value, I need one value to depend on the other. In my app, a user can book a spot at a lake for fishing. And I need it to be in whole hours. For example, if they want to start fishing at 12:40, they can end at 13:40, 14:40, 15:40, etc. How do I do that?
My model looks like this (Rezervaces is an object in which I store user reservations):

```<code>public partial class Rezervaces
{
public int RezId { get; set; }
public int UserId { get; set; }
public string UserPhone { get; set; }

[Required(ErrorMessage = "Time of start is required")]
public System.TimeSpan TimeStart{ get; set; }

[Required(ErrorMessage = "Time of finish is required")]
public System.TimeSpan TimeFinish{ get; set; }

[Required(ErrorMessage = "Date is required")]
[Range(DateTime.Now, DateTime.MaxValue)]
public System.DateTime DateDate{ get; set; }
}
</code>```

and my view editors look like this :

```<code><divclass="form-group">
<bclass="control-labelcol-md-2">Timestart</b>
<divclass="col-md-10">
@Html.EditorFor(model=>model.TimeStart,new{htmlAttributes=
new{@class="form-control",@Value=
(DateTime.Now.AddMinutes(10)).TimeOfDay}})
@Html.ValidationMessageFor(model=>model.CasOd,"",new{
@class="text-danger"})
</div>
</div>

<divclass="form-group">
<bclass="control-labelcol-md-2">Timefinish</b>
<divclass="col-md-10">
@Html.EditorFor(model=>model.TimeFinish,new{htmlAttributes
=new{@class="form-control"},@Value=
(DateTime.Now.AddMinutes(10).AddHours(1)).TimeOfDay})
@Html.ValidationMessageFor(model=>model.CasDo,"",new{
@class="text-danger"})
</div>
</div>

<divclass="form-group">
<bclass="control-labelcol-md-2">Date</b>
<divclass="col-md-10">
@Html.EditorFor(model=>model.DateDate,new{htmlAttributes=
new{@class="form-control",@Value=DateTime.Now}})
@Html.ValidationMessageFor(model=>model.Datum,"",new{
@class="text-danger"})
</div>
</div>

<divclass="form-group">
<divclass="col-md-offset-2col-md-10">
<inputtype="submit"value="Addreservation"class="btnbtn-
default"style="background-color:darkseagreen;color:white"/>
</div>
</div>
</code>```

Any help is really apprecited! Thanks!

答:
I'm not an MVC expert, but your case seems a typical server-side validation, performed in a controller action.

Look at This example for a clear similar situation

Body:
I ran into problem when creating user booking app. Basically, apart from basic property limitations like min and max value, I need one value to depend on the other. In my app, a user can book a spot at a lake for fishing. And I need it to be in whole hours. For example, if they want to start fishing at 12:40, they can end at 13:40, 14:40, 15:40, etc. How do I do that?
My model looks like this (Rezervaces is an object in which I store user reservations):

public partial class Rezervaces
{
public int RezId { get; set; }
public int UserId { get; set; }
public string UserPhone { get; set; }

[Required(ErrorMessage = "Time of start is required")]
public System.TimeSpan TimeStart{ get; set; }

[Required(ErrorMessage = "Time of finish is required")]
public System.TimeSpan TimeFinish{ get; set; }

[Required(ErrorMessage = "Date is required")]
[Range(DateTime.Now, DateTime.MaxValue)]
public System.DateTime DateDate{ get; set; }
}

and my view editors look like this :

<divclass="form-group">
<bclass="control-labelcol-md-2">Timestart
<divclass="col-md-10">
@Html.EditorFor(model=>model.TimeStart,new{htmlAttributes=
new{@class="form-control",@Value=
(DateTime.Now.AddMinutes(10)).TimeOfDay}})
@Html.ValidationMessageFor(model=>model.CasOd,"",new{
@class="text-danger"})

<divclass="form-group">
<bclass="control-labelcol-md-2">Timefinish
<divclass="col-md-10">
@Html.EditorFor(model=>model.TimeFinish,new{htmlAttributes
=new{@class="form-control"},@Value=
(DateTime.Now.AddMinutes(10).AddHours(1)).TimeOfDay})
@Html.ValidationMessageFor(model=>model.CasDo,"",new{
@class="text-danger"})

<divclass="form-group">
<bclass="control-labelcol-md-2">Date
<divclass="col-md-10">
@Html.EditorFor(model=>model.DateDate,new{htmlAttributes=
new{@class="form-control",@Value=DateTime.Now}})
@Html.ValidationMessageFor(model=>model.Datum,"",new{
@class="text-danger"})

<divclass="form-group">
<divclass="col-md-offset-2col-md-10">
<inputtype="submit"value="Addreservation"class="btnbtn-
default"style="background-color:darkseagreen;color:white"/>

Any help is really apprecited! Thanks!


问:
gfortran default width/decimal number descriptors
The following code demonstrates that for gfortran one may have the processor decide the width of the format descriptor for an integer and floating point number:

```<code>program test
    double precision :: x = 5.321568756
    integer ::  i = 53254
    write(*, '(I0)') i
    write(*, '(F0.3)') x
end program test
</code>```

When compiled, this code outputs

```<code>53254
5.322
</code>```

Is it also possible to have the processor decide on the number of decimal points that are output with the write statement? In other words, to have the above program output the following:

```<code>53254
5.321568756
</code>```

without explicitly providing the number of decimal points in the format descriptor like '(F0.9)'. Something like '(F0.(default number of decimal points here))'

答:
You can use the g0 edit descriptor, like:

```<code>
program test
  double precision :: x = 5.321568756
  integer ::  i = 53254
  write(*, '(I0)') i
  write(*, '(F0.3)') x
  write(*, '(G0)') x
end program test
</code>```

(The difference between the G and F edit descriptors is that when the value gets large/small enough, the G edit descriptor switches to exponential notation. Usually that's what you want, though)

Body:
The following code demonstrates that for gfortran one may have the processor decide the width of the format descriptor for an integer and floating point number:

program test
    double precision :: x = 5.321568756
    integer ::  i = 53254
    write(*, '(I0)') i
    write(*, '(F0.3)') x
end program test

When compiled, this code outputs

53254
5.322

Is it also possible to have the processor decide on the number of decimal points that are output with the write statement? In other words, to have the above program output the following:

53254
5.321568756

without explicitly providing the number of decimal points in the format descriptor like '(F0.9)'. Something like '(F0.(default number of decimal points here))'

Body:
You can use the g0 edit descriptor, like:

program test
  double precision :: x = 5.321568756
  integer ::  i = 53254
  write(*, '(I0)') i
  write(*, '(F0.3)') x
  write(*, '(G0)') x
end program test

(The difference between the G and F edit descriptors is that when the value gets large/small enough, the G edit descriptor switches to exponential notation. Usually that's what you want, though)


问:
${user.home} in Ubuntu 14.04 LTS Disk
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

This is one of my config class

```<code>@Configuration
@EnableTransactionManagement
@EnableCaching
@PropertySource("file:///${user.home}/.devices/application-common.properties")
public class DeviceApplicationConfig {
..
}
</code>```

I enter in the linode machine with devuser:

```<code>devuser@localhost:~$ pwd
/home/devuser
</code>```

then I run the SpringBoot app. from the folder /var/devices, But I have this error, while I was expecting the program search the file in: /home/devuser/.devices/application-common.properties

```<code>Caused by: java.io.FileNotFoundException: /root/.devices/application-common.properties (No such file or directory)
</code>```

and checking the processes it seems than the application is run by devuser:

```<code>devuser  12922  1.3 12.3 2478348 252840 ?      Sl   15:16   0:37 java -jar devices-0.0.1-SNAPSHOT.jar
</code>```

答:
you need to configure user.home directory and run application from this user. for configuration of user.home you can refer bellow stackoverflow link :

Command to change the default home directory of a user

Title: ${user.home} in Ubuntu 14.04 LTS Disk

Body:
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

This is one of my config class

@Configuration
@EnableTransactionManagement
@EnableCaching
@PropertySource("file:///${user.home}/.devices/application-common.properties")
public class DeviceApplicationConfig {
..
}

I enter in the linode machine with devuser:

devuser@localhost:~$ pwd
/home/devuser

then I run the SpringBoot app. from the folder /var/devices, But I have this error, while I was expecting the program search the file in: /home/devuser/.devices/application-common.properties

Caused by: java.io.FileNotFoundException: /root/.devices/application-common.properties (No such file or directory)

and checking the processes it seems than the application is run by devuser:

devuser  12922  1.3 12.3 2478348 252840 ?      Sl   15:16   0:37 java -jar devices-0.0.1-SNAPSHOT.jar


问:
Return empty string when placeholder is shown
I have a custom text box with placeholder effect. If the textbox is empty, the placeholder is shown.

When I pass the value of the textbox (when the textbox is empty and the placeholder is shown instead) to a function , it passes the placeholder value, but I want it to just pass an empty string.

I thought about overriding the Text property and do an internal check. Something like

```<code>public string Text
{
    get
    {
        if (this.Text == this.Placeholder)
        {
            return "";
        }
        return this.Text;
    }
    set
    {
        this.Text = value;
    }
}
</code>```

but I don't know if this is possible. This would create an infinite loop, I think. How do I make this work?

I know I can use a custom property (e.g., ActualText instead of Text) to do this, but if it's possible, I'd like to use Text. If not, I'll use a custom property.

```<code>using System;
using System.Drawing;
using System.Windows.Forms;
using CustomExtensions;

namespace CustomControls
{
    public class CustomTextBox : TextBox
    {
        private string _placeholder;

        public string Placeholder
        {
            get
            {
                return this._placeholder;
            }
            set
            {
                this._placeholder = value;
                if (value.IsEmpty(true))
                {
                    this._placeholder = "";
                }
                else
                {
                    this._placeholder = value;
                }
            }
        }

        public CustomTextBox()
        {
            Initialize();
        }

        private void Initialize()
        {
            this.Enter += new EventHandler(this.Placeholder_Hide);
            this.Leave += new EventHandler(this.Placeholder_Show);
        }

        // called from MainForm_Load
        public void InitPH()
        {
            if (!this.Placeholder.IsEmpty(true) && this.Text.IsEmpty())
            {
                this.Text = this.Placeholder;
                this.ForeColor = Color.Gray;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
            }
        }

        private void Placeholder_Hide(object sender, EventArgs e)
        {
            if (this.Text == this._placeholder)
            {
                this.Text = "";
                this.ForeColor = Color.Black;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
            }
        }

        private void Placeholder_Show(object sender, EventArgs e)
        {
            if (this.IsEmpty())
            {
                this.Text = this._placeholder;
                this.ForeColor = Color.Gray;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
            }
        }

        public bool IsEmpty()
        {
            return this.Text.IsEmpty(true, this.Placeholder);
        }
    }
}
</code>```

答:
It would be best not to do if (this.Text == this._placeholder), because what if somebody actually entered the same text as the placeholder? It may be unlikely, but you don't want to leave in the possibility of unintended behavior.

One possible alternative is the following:

Add a field to your class, _valueIsSet, of type bool. Then, modify your event handlers to set it accordingly.

```<code>private void _valueIsSet = false;

private void Placeholder_Hide(object sender, EventArgs e)
{
    if (!this._valueIsSet)
    {
        this.Text = "";
        this.ForeColor = Color.Black;
        this.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
    }
}

private void Placeholder_Show(object sender, EventArgs e)
{
    if (this.IsEmpty())
    {
        this._valueIsSet = false;
        this.Text = this._placeholder;
        this.ForeColor = Color.Gray;
        this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
    }
}
</code>```

Then, add an event handler for your text box's KeyDown event:

```<code>private void customTextBox_KeyDown(object sender, KeyEventArgs e)
{
    this._valueIsSet = true;
}
</code>```

Finally, create a property, myText:

```<code>public string myText
{
    get
    {
        return this._valueIsSet ? this.Text : null;
    }
}
</code>```

Body:
I have a custom text box with placeholder effect. If the textbox is empty, the placeholder is shown.

When I pass the value of the textbox (when the textbox is empty and the placeholder is shown instead) to a function , it passes the placeholder value, but I want it to just pass an empty string.

I thought about overriding the Text property and do an internal check. Something like

public string Text
{
    get
    {
        if (this.Text == this.Placeholder)
        {
            return "";
        }
        return this.Text;
    }
    set
    {
        this.Text = value;
    }
}

but I don't know if this is possible. This would create an infinite loop, I think. How do I make this work?

I know I can use a custom property (e.g., ActualText instead of Text) to do this, but if it's possible, I'd like to use Text. If not, I'll use a custom property.

using System;
using System.Drawing;
using System.Windows.Forms;
using CustomExtensions;

namespace CustomControls
{
    public class CustomTextBox : TextBox
    {
        private string _placeholder;

        public string Placeholder
        {
            get
            {
                return this._placeholder;
            }
            set
            {
                this._placeholder = value;
                if (value.IsEmpty(true))
                {
                    this._placeholder = "";
                }
                else
                {
                    this._placeholder = value;
                }
            }
        }

        public CustomTextBox()
        {
            Initialize();
        }

        private void Initialize()
        {
            this.Enter += new EventHandler(this.Placeholder_Hide);
            this.Leave += new EventHandler(this.Placeholder_Show);
        }

        // called from MainForm_Load
        public void InitPH()
        {
            if (!this.Placeholder.IsEmpty(true) && this.Text.IsEmpty())
            {
                this.Text = this.Placeholder;
                this.ForeColor = Color.Gray;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
            }
        }

        private void Placeholder_Hide(object sender, EventArgs e)
        {
            if (this.Text == this._placeholder)
            {
                this.Text = "";
                this.ForeColor = Color.Black;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
            }
        }

        private void Placeholder_Show(object sender, EventArgs e)
        {
            if (this.IsEmpty())
            {
                this.Text = this._placeholder;
                this.ForeColor = Color.Gray;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
            }
        }

        public bool IsEmpty()
        {
            return this.Text.IsEmpty(true, this.Placeholder);
        }
    }
}

Body:
It would be best not to do if (this.Text == this._placeholder), because what if somebody actually entered the same text as the placeholder? It may be unlikely, but you don't want to leave in the possibility of unintended behavior.

One possible alternative is the following:

Add a field to your class, _valueIsSet, of type bool. Then, modify your event handlers to set it accordingly.

private void _valueIsSet = false;

private void Placeholder_Hide(object sender, EventArgs e)
{
    if (!this._valueIsSet)
    {
        this.Text = "";
        this.ForeColor = Color.Black;
        this.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
    }
}

private void Placeholder_Show(object sender, EventArgs e)
{
    if (this.IsEmpty())
    {
        this._valueIsSet = false;
        this.Text = this._placeholder;
        this.ForeColor = Color.Gray;
        this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
    }
}

Then, add an event handler for your text box's KeyDown event:

private void customTextBox_KeyDown(object sender, KeyEventArgs e)
{
    this._valueIsSet = true;
}

Finally, create a property, myText:

public string myText
{
    get
    {
        return this._valueIsSet ? this.Text : null;
    }
}


问:
problem with conditional switch
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

```<code><?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>
</code>```

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

答:
You don't use conditionals in the case statements like that, not intuitively anyway.  This is what's happening:

```<code>    case ($totaltime < 1):  // Evaluates to 1.  $totaltime is not 1, so no match.
    case ($totaltime > 1):  // Evaluates to 0.  $totaltime is 0, so match.
</code>```

Essentially you're trying to use an else if construct as a switch construct, but the functionality isn't there.  The conditionals don't evaluate in the way you're expecting (the way they would in an if block), they're just looking for the first case block which equals the value being tested in the switch block.

Title: problem with conditional switch

Body:
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

<?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

Body:
You don't use conditionals in the case statements like that, not intuitively anyway.  This is what's happening:

    case ($totaltime < 1):  // Evaluates to 1.  $totaltime is not 1, so no match.
    case ($totaltime > 1):  // Evaluates to 0.  $totaltime is 0, so match.

Essentially you're trying to use an else if construct as a switch construct, but the functionality isn't there.  The conditionals don't evaluate in the way you're expecting (the way they would in an if block), they're just looking for the first case block which equals the value being tested in the switch block.


问:
Navigate in gvim like in most
I'd like to use gvim to view files with long lines. It's a table, so I'm not wrapping the lines.
Is this possible to configure gvim so arrows navigation will be like in "most" tool? Arrow key will move the whole screen 1 character lef/right/top/bottom?
Thanks a lot. </p>

答:
I think this should do what you want.

```<code>set nocompatible
set nowrap
set virtualedit=all

nnoremap <Left> zh
nnoremap <Right> zl
nnoremap <Up> <C-y>
nnoremap <Down> <C-e>
</code>```

If you want the same behavior in insert mode, add the same mappings again as a second set, but use inoremap instead of nnoremap.

The virtualedit setting will allow the cursor to move beyond the end of the line and continue on as if the line had infinite whitespace to the right.

NOTE: virtualedit is only available if Vim was compiled with that feature. You can check with :version. If this feature is available, you should see a + next to it, e.g. +virtualedit.

Title: Navigate in gvim like in most

Body:
I think this should do what you want.

set nocompatible
set nowrap
set virtualedit=all

nnoremap <Left> zh
nnoremap <Right> zl
nnoremap <Up> <C-y>
nnoremap <Down> <C-e>

If you want the same behavior in insert mode, add the same mappings again as a second set, but use inoremap instead of nnoremap.

The virtualedit setting will allow the cursor to move beyond the end of the line and continue on as if the line had infinite whitespace to the right.

NOTE: virtualedit is only available if Vim was compiled with that feature. You can check with :version. If this feature is available, you should see a + next to it, e.g. +virtualedit.


问:
Django Channels message life time
I have some (possibly huge) amount of JSON data I need to push into Django Channel. The data has very small required lifetime (2-3 seconds is enough). I use Redis as backend.

What is default message lifetime?
Is it possible to specify life time of the message?

答:
I found an easy way to resolve my issue without patching asgi_redis code for customer expiry of message.

I created two channel layers in my configuration. Then I set desired short expiry to the second channel layer. All short live time messages now passed and handled by this channel layer consumer.

Title: Django Channels message life time


问:
Where is the umask setting stored? Can this be applied to home directory other than setting it globally?
umask seems to be set in various files (centos) as:

```<code>/etc/profile
/etc/profile.d/umask.sh
/etc/login.defs
...
</code>```

what is the precedence order for this?

Moreover, when you set the umask using "umask xxx" where does this value gets stored?

what is the precedence order for this?

Also how do I go about setting umask for /home/ directory.

By default it is set to 755 which I intend to change to 750.

As I understand umask is a global setting and cannot be applied at directory.
If this is the case what other options do I have?

答: If you want to set the umask for /home you will need to mount this as a separate filesystem using the umask option to set the required umask. These options will need to be set in /etc/fstab to take effect when the system starts. Question really is whether you have /home on a separate /disk/partition/logical volume at the moment.</p>

Body:
umask seems to be set in various files (centos) as:

/etc/profile
/etc/profile.d/umask.sh
/etc/login.defs
...

what is the precedence order for this?

Moreover, when you set the umask using "umask xxx" where does this value gets stored?

what is the precedence order for this?

Also how do I go about setting umask for /home/ directory.

By default it is set to 755 which I intend to change to 750.

As I understand umask is a global setting and cannot be applied at directory.
If this is the case what other options do I have?


问:
How to embed file into template using Scons and Substfile?
I'm trying to create a Substfile rule that will expand a key to the transformed contents of another file. I'm not clear on the setup here to ensure the source file is registered as a dependency.

Logically I want something like:

```<code>out = env.Substfile( 'file.in', SUBST_DICT = {
     '%SOME_CONTENT%': transform( readfile('depends.txt') ),
}
</code>```

答:
I'm using a combination of Action and Command to do what I want. I ended up not using Substfile, though it could probably be chained to the command.

This RawStringIt action loads a text file and emits a C++ encoded raw string for the content.

def RawStringIt(varName):
    def Impl(target, source, env):
        content = source[0].get_text_contents()
        with open(target[0].get_path(), 'w') as target_file:
            target_file.write( "std::string {} = R\"~~~~({})~~~~\";".format(varName,content))
        return 0

    return Action(Impl, "creating C++ Raw String $TARGET from $SOURCE" )

base_leaf = env.Command( 'include/runner/base.leaf.hpp', '../share/base.leaf', RawStringIt("dataBaseLeaf") )
```

Body:
I'm trying to create a Substfile rule that will expand a key to the transformed contents of another file. I'm not clear on the setup here to ensure the source file is registered as a dependency.

Logically I want something like:

out = env.Substfile( 'file.in', SUBST_DICT = {
     '%SOME_CONTENT%': transform( readfile('depends.txt') ),
}


问:
Category Page in Jekyll
I have a category.html page that will loop through a certain category of posts.

```<code>{% for post in site.categories.tech %}
</code>```

What I want to display is from the index.html page, when the user clicks

```<code>{{ post.categories }}
</code>```

Which is generated from a loop that displays all of the posts.

```<code>{% for post in site.posts %}
</code>```

I need that {{ post.categories }} variable to replace the .tech in the categories.html like this

```<code>{% for category in site.categories.{{ post.categories }} %}
</code>```

I don't know how to pass the variable from index.html to categories.html

答:
Site categories is an object where each key is the category name. So

```<code>{{ site.categories }}
</code>```

Outputs something like this:

```<code>{
  "Category name" => [#, #, #, #, #, #, #],
  "Another category name" => [#, #, #, #, #, #, #],
  ...
}
</code>```

Therefore, square brackets should do it. So if in the front matter of your index.html you have

```<code>---
categories: tech
---
</code>```

The code below will render all your posts under tech category.

```<code>{% for post in site.categories[post.categories] %}
  {{ post }}
{% endfor %}
</code>```

Of course this won't work if you have multiple categories in the front matter, but I don't know your use case.

Title: Category Page in Jekyll

Body:
I have a category.html page that will loop through a certain category of posts.

{% for post in site.categories.tech %}

What I want to display is from the index.html page, when the user clicks

{{ post.categories }}

Which is generated from a loop that displays all of the posts.

{% for post in site.posts %}

I need that {{ post.categories }} variable to replace the .tech in the categories.html like this

{% for category in site.categories.{{ post.categories }} %}

I don't know how to pass the variable from index.html to categories.html

Body:
Site categories is an object where each key is the category name. So

{{ site.categories }}

Outputs something like this:

{
  "Category name" => [#, #, #, #, #, #, #],
  "Another category name" => [#, #, #, #, #, #, #],
  ...
}

Therefore, square brackets should do it. So if in the front matter of your index.html you have

---
categories: tech
---

The code below will render all your posts under tech category.

{% for post in site.categories[post.categories] %}
  {{ post }}
{% endfor %}

Of course this won't work if you have multiple categories in the front matter, but I don't know your use case.


问:
How do I force a 404 from the symfony routing in YML without specifying a custom controller?

Problem to solve

I want to force to trigger a 404 for a certain specific route in symfony, without having to specify a custom controller that just throws the exception, and before the router continues to explore the rest of the routing file.

Can I say that in the routing.yml file for a specific route?

Context

I have this routing for form submitting in my travel agency:

```<code>POST /submit/{submitterForm}
</code>```

where submitterForm can only take 2 values: purchase-trip and contact depending on if the visitor submits a form in a page where he is visiting a trip or from the contact page. For example POST /submit/contact would be valid.

I have this other route:

```<code>GET /{destinationSeoUri}/{tripSeoUri}
</code>```

to display a specific trip for a destination. For example GET /thailand/trip-bangkok-beaches would be valid.

Limiting values from the router

This is the relevant extract of my routing.yml:

```<code>submit:
    path: /submit/{submitterForm}
    methods: [ POST ]
    defaults: { _controller: AppBundle:DataSubmission:submit }
    requirements:
        submitterForm: purchase-trip|contact

trip:
    path: /{destinationSeoUri}/{tripSeoUri}
    methods: [ GET ]
    defaults: { _controller: AppBundle:Trip:trip }
</code>```

What I want

For any POST request with an invalid value of {submitterForm} in the route /submit/{submitterForm} I want that the system returns a 404 Not Found

It does not happen now because when the router does not match the submit route pattern, it still falls down to the next ones and then matches the trip pattern.

Then, the system says "okey, I have a route that matches, instead, this is only allowed for GET, so I'll respond a 405 Method not allowed".

This would hold true for something like POST /thailand/trip-bangkok-beaches but I want to specifically signal the client that if the POST matches the /submit/any-invalid-form-submitter-name it is then a Not Found.

Initial solution

To do so, I've inserted, in order, in the middle of the previous two, a catch-all for /submit/* like in this routing excerpt:

```<code>submit:
    path: /submit/{submitterForm}
    methods: [ POST ]
    defaults: { _controller: AppBundle:DataSubmission:submit }
    requirements:
        submitterForm: purchase-trip|contact

submit_fallback:
    path: /submit/{submitterForm}
    methods: [ POST ]
    defaults: { _controller: AppBundle:DataSubmission:notFound }

trip:
    path: /{destinationSeoUri}/{tripSeoUri}
    methods: [ GET ]
    defaults: { _controller: AppBundle:Trip:trip }
</code>```

This way, requesting to POST /submit/any-invalid-form-submitter-name is matched by the submit_fallback route.

The controller

The controller is a pretty simple "on-liner":

```<code>{
    throw new NotFoundHttpException();
}
</code>```

Preferred solution

I think I'm looking for something similar to this:

```<code>submit_fallback:
    path: /submit/{submitterForm}
    methods: [ POST ]
    status: 404
</code>```

So, questions

Is it possible for me to tell the submit_fallback something like: hey guy you don't need a _controller just because you have to send a 404 Not found (or any other status I would want) and nothing else.

If so, how?

答:
Just add requirements onto your other route so that destinationSeoUri cannot equal submit. This should force that route to not match, and throw the 404 instead of the 405 error.

```<code>trip:
    path: /{destinationSeoUri}/{tripSeoUri}
    methods: [ GET ]
    defaults: { _controller: AppBundle:Trip:trip }
    requirements:
        destinationSeoUri: "^(?!submit$)"
</code>```

Body:
Problem to solve

I want to force to trigger a 404 for a certain specific route in symfony, without having to specify a custom controller that just throws the exception, and before the router continues to explore the rest of the routing file.

Can I say that in the routing.yml file for a specific route?

Context

I have this routing for form submitting in my travel agency:

POST /submit/{submitterForm}

where submitterForm can only take 2 values: purchase-trip and contact depending on if the visitor submits a form in a page where he is visiting a trip or from the contact page. For example POST /submit/contact would be valid.

I have this other route:

GET /{destinationSeoUri}/{tripSeoUri}

to display a specific trip for a destination. For example GET /thailand/trip-bangkok-beaches would be valid.

Limiting values from the router

This is the relevant extract of my routing.yml:

submit:
    path: /submit/{submitterForm}
    methods: [ POST ]
    defaults: { _controller: AppBundle:DataSubmission:submit }
    requirements:
        submitterForm: purchase-trip|contact

trip:
    path: /{destinationSeoUri}/{tripSeoUri}
    methods: [ GET ]
    defaults: { _controller: AppBundle:Trip:trip }

What I want

For any POST request with an invalid value of {submitterForm} in the route /submit/{submitterForm} I want that the system returns a 404 Not Found

It does not happen now because when the router does not match the submit route pattern, it still falls down to the next ones and then matches the trip pattern.

Then, the system says "okey, I have a route that matches, instead, this is only allowed for GET, so I'll respond a 405 Method not allowed".

This would hold true for something like POST /thailand/trip-bangkok-beaches but I want to specifically signal the client that if the POST matches the /submit/any-invalid-form-submitter-name it is then a Not Found.

Initial solution

To do so, I've inserted, in order, in the middle of the previous two, a catch-all for /submit/* like in this routing excerpt:

submit:
    path: /submit/{submitterForm}
    methods: [ POST ]
    defaults: { _controller: AppBundle:DataSubmission:submit }
    requirements:
        submitterForm: purchase-trip|contact

submit_fallback:
    path: /submit/{submitterForm}
    methods: [ POST ]
    defaults: { _controller: AppBundle:DataSubmission:notFound }

trip:
    path: /{destinationSeoUri}/{tripSeoUri}
    methods: [ GET ]
    defaults: { _controller: AppBundle:Trip:trip }

This way, requesting to POST /submit/any-invalid-form-submitter-name is matched by the submit_fallback route.

The controller

The controller is a pretty simple "on-liner":

{
    throw new NotFoundHttpException();
}

Preferred solution

I think I'm looking for something similar to this:

submit_fallback:
    path: /submit/{submitterForm}
    methods: [ POST ]
    status: 404

So, questions

Is it possible for me to tell the submit_fallback something like: hey guy you don't need a _controller just because you have to send a 404 Not found (or any other status I would want) and nothing else.

If so, how?

Body:
Just add requirements onto your other route so that destinationSeoUri cannot equal submit. This should force that route to not match, and throw the 404 instead of the 405 error.

trip:
    path: /{destinationSeoUri}/{tripSeoUri}
    methods: [ GET ]
    defaults: { _controller: AppBundle:Trip:trip }
    requirements:
        destinationSeoUri: "^(?!submit$)"


问:
something wrong with regex
That's my first project when I use regex and I have a little problem when I'm validating email. I use the following formula: ^[0-9]{5,6}+(@student\\\.de)|(@teacher\\\.de) (it starts with 5 or 6 numbers and then are two alternative domains). But it's still doesn't work and I can't find the mistake in the formula. Could anyone help me?

答:
I whould like to use ^[0-9]{5,6}@(teacher|student)\.de instead, which mean start with 5 or 6 degits followed by @teacher.de or @student.de

regex demo

Title: something wrong with regex


问:
Setter Routine from selectOneMenu not called
I'm using Primefaces 6.1 and have an issue with one of the selectOneMenu. I have reduced the page to the selectOneMenu-Item only, but couldn't figure out, where the issue is located.

xhtml-Page:

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui" template="/WEB-INF/template.xhtml">
    <ui:define name="content">
        <h:form id="formCenter">

                    <f:selectItem itemLabel="Bank-Daten auswählen" itemValue="#{null}" noSelectionOption="true"/>
                    <f:selectItems value="#{bankAccountEntryClearing.items}"
                                   var="interfaceFileItem"
                                   itemLabel="#{interfaceFileItem.fileName}"
                                   itemValue="#{interfaceFileItem}"/>

                        #{interfaceFileItem.fileName}

        </h:form>
    </ui:define>
</ui:composition>
```

<p>Converter:</p>

<pre class="lang-java prettyprint-override"><code>@ManagedBean
@SessionScoped
@Named("interfaceFileConverter")
public class InterfaceFileConverter implements Converter {

    private final Logger logger = Logger.getLogger(this.getClass().getName());

    @Inject
    private InterfaceFileFacade ejbFacade;

    private Integer getKey(String value) {
        Integer key = Integer.valueOf(value);
        return key;
    }

    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if (object == null) return null;
        if (object instanceof InterfaceFile)
            return String.valueOf(((InterfaceFile) object).getInterfaceFileId());
        return null;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.length() == 0) {
            logger.info("Interface Converter : null");
            return null;
        }
        InterfaceFile interfaceFile = this.ejbFacade.findInterfaceFile(getKey(value));
        logger.info("Interface Converter : " + interfaceFile.getInterfaceFileId());
        return interfaceFile;
    }
}
</code>```

Bean:

@SessionScoped
@ManagedBean
@Named(value = "bankAccountEntryClearing")
public class BankAccountEntryClearing extends AbstractHouseController<InterfaceFile> implements Serializable {

    private static final long serialVersionUID = 1L;
    private final Logger logger = Logger.getLogger(this.getClass().getName());

    @Inject
    private InterfaceFileFacade         ejbFacade;

    private InterfaceFile               interfaceFile = null;
    private Integer                     houseId;
    private List<InterfaceFile>         interfaceFiles = null;

    public BankAccountEntryClearing() {
        super(InterfaceFile.class);
    }

    @PostConstruct
    public void init() {
        super.setFacade(ejbFacade);
    }

    public List<InterfaceFile> getItems() {
        if (this.getHouseId() == null)
            return null;

        if (this.getHouseId() != this.houseId) {
            interfaceFiles = ejbFacade.getInterfaceFiles(this.getHouseId(),1);
        }

        return interfaceFiles;
    }

    public InterfaceFile getSelectedInterfaceFile() {
        logger.info("Interface Bean getter");
        return interfaceFile;
    }

    public void setSelectedInterfaceFile(InterfaceFile interfaceFile) {
        logger.info("Interface Bean setter: " + interfaceFile.getFileName());
        this.interfaceFile      = interfaceFile;
    }

    public String getFileName() {
        if (this.interfaceFile != null)
            return this.interfaceFile.getFileName();
        return "";
    }
}
```

<p>The items are loaded prober and could be selected. After an item is selected, the getAsObject from converter is called, but never the setter-routine.</p>

<pre class="lang-html prettyprint-override"><code>16:55:23,411 INFO  [com.np.propmgmt.controller.BankAccountEntryClearing] (default task-30) Interface Bean getter
16:55:23,412 INFO  [com.np.propmgmt.controller.BankAccountEntryClearing] (default task-30) Interface Bean getter
16:55:27,772 INFO  [com.np.propmgmt.converter.InterfaceFileConverter] (default task-48) Interface Converter : 69
</code>```

答:
I found an hind and solved the issue. The reason was the entity-class object InterfaceFile itself.
This JPA entity-class was the only one, which was generated by Eclipse JPA-Tool. In this case no "equals" and "hashCode" function
with the primary-key was generated. At the time the item was selected, the "selectOneMenu" compare of the returned InterfaceFile (from getAsObject) to
the list (from getItems) and failes. With adding a "" the validation-error was shown.

After adding this two functions to the InterfaceFile-entity-class, everything worked fine.

It is the same as Validation Error: Value is not valid

Body:
I'm using Primefaces 6.1 and have an issue with one of the selectOneMenu. I have reduced the page to the selectOneMenu-Item only, but couldn't figure out, where the issue is located.

xhtml-Page:

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui" template="/WEB-INF/template.xhtml">
    <ui:define name="content">
        <h:form id="formCenter">

                    <f:selectItem itemLabel="Bank-Daten auswählen" itemValue="#{null}" noSelectionOption="true"/>
                    <f:selectItems value="#{bankAccountEntryClearing.items}"
                                   var="interfaceFileItem"
                                   itemLabel="#{interfaceFileItem.fileName}"
                                   itemValue="#{interfaceFileItem}"/>

                        #{interfaceFileItem.fileName}

        </h:form>
    </ui:define>
</ui:composition>

Converter:

@ManagedBean
@SessionScoped
@Named("interfaceFileConverter")
public class InterfaceFileConverter implements Converter {

    private final Logger logger = Logger.getLogger(this.getClass().getName());

    @Inject
    private InterfaceFileFacade ejbFacade;

    private Integer getKey(String value) {
        Integer key = Integer.valueOf(value);
        return key;
    }

    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if (object == null) return null;
        if (object instanceof InterfaceFile)
            return String.valueOf(((InterfaceFile) object).getInterfaceFileId());
        return null;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.length() == 0) {
            logger.info("Interface Converter : null");
            return null;
        }
        InterfaceFile interfaceFile = this.ejbFacade.findInterfaceFile(getKey(value));
        logger.info("Interface Converter : " + interfaceFile.getInterfaceFileId());
        return interfaceFile;
    }
}

Bean:

@SessionScoped
@ManagedBean
@Named(value = "bankAccountEntryClearing")
public class BankAccountEntryClearing extends AbstractHouseController<InterfaceFile> implements Serializable {

    private static final long serialVersionUID = 1L;
    private final Logger logger = Logger.getLogger(this.getClass().getName());

    @Inject
    private InterfaceFileFacade         ejbFacade;

    private InterfaceFile               interfaceFile = null;
    private Integer                     houseId;
    private List<InterfaceFile>         interfaceFiles = null;

    public BankAccountEntryClearing() {
        super(InterfaceFile.class);
    }

    @PostConstruct
    public void init() {
        super.setFacade(ejbFacade);
    }

    public List<InterfaceFile> getItems() {
        if (this.getHouseId() == null)
            return null;

        if (this.getHouseId() != this.houseId) {
            interfaceFiles = ejbFacade.getInterfaceFiles(this.getHouseId(),1);
        }

        return interfaceFiles;
    }

    public InterfaceFile getSelectedInterfaceFile() {
        logger.info("Interface Bean getter");
        return interfaceFile;
    }

    public void setSelectedInterfaceFile(InterfaceFile interfaceFile) {
        logger.info("Interface Bean setter: " + interfaceFile.getFileName());
        this.interfaceFile      = interfaceFile;
    }

    public String getFileName() {
        if (this.interfaceFile != null)
            return this.interfaceFile.getFileName();
        return "";
    }
}

The items are loaded prober and could be selected. After an item is selected, the getAsObject from converter is called, but never the setter-routine.

16:55:23,411 INFO  [com.np.propmgmt.controller.BankAccountEntryClearing] (default task-30) Interface Bean getter
16:55:23,412 INFO  [com.np.propmgmt.controller.BankAccountEntryClearing] (default task-30) Interface Bean getter
16:55:27,772 INFO  [com.np.propmgmt.converter.InterfaceFileConverter] (default task-48) Interface Converter : 69


问:
Calculate average using Spark Scala
How do I calculate the Average salary per location in Spark Scala with below two data sets ?

File1.csv(Column 4 is salary)

```<code>Ram, 30, Engineer, 40000
Bala, 27, Doctor, 30000
Hari, 33, Engineer, 50000
Siva, 35, Doctor, 60000
</code>```

File2.csv(Column 2 is location)

```<code>Hari, Bangalore
Ram, Chennai
Bala, Bangalore
Siva, Chennai
</code>```

The above files are not sorted. Need to join these 2 files and find average salary per location. I tried with below code but unable to make it.

```<code>val salary = sc.textFile("File1.csv").map(e => e.split(","))
val location = sc.textFile("File2.csv").map(e.split(","))
val joined = salary.map(e=>(e(0),e(3))).join(location.map(e=>(e(0),e(1)))
val joinedData = joined.sortByKey()
val finalData = joinedData.map(v => (v._1,v._2._1._1,v._2._2))
val aggregatedDF = finalData.map(e=> e.groupby(e(2)).agg(avg(e(1))))
aggregatedDF.repartition(1).saveAsTextFile("output.txt")
</code>```

Please help with code and sample output how it will look.

Many Thanks

答:
You can read the CSV files as DataFrames, then join and group them to get the averages:

```<code>val df1 = spark.read.csv("/path/to/file1.csv").toDF(
  "name", "age", "title", "salary"
)

val df2 = spark.read.csv("/path/to/file2.csv").toDF(
  "name", "location"
)

import org.apache.spark.sql.functions._

val dfAverage = df1.join(df2, Seq("name")).
  groupBy(df2("location")).agg(avg(df1("salary")).as("average")).
  select("location", "average")

dfAverage.show
+-----------+-------+
|   location|average|
+-----------+-------+
|Bangalore  |40000.0|
|  Chennai  |50000.0|
+-----------+-------+
</code>```

[UPDATE] For calculating average dimensions:

```<code>// file1.csv:
Ram,30,Engineer,40000,600*200
Bala,27,Doctor,30000,800*400
Hari,33,Engineer,50000,700*300
Siva,35,Doctor,60000,600*200

// file2.csv
Hari,Bangalore
Ram,Chennai
Bala,Bangalore
Siva,Chennai

val df1 = spark.read.csv("/path/to/file1.csv").toDF(
  "name", "age", "title", "salary", "dimensions"
)

val df2 = spark.read.csv("/path/to/file2.csv").toDF(
  "name", "location"
)

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.IntegerType

val dfAverage = df1.join(df2, Seq("name")).
  groupBy(df2("location")).
  agg(
    avg(split(df1("dimensions"), ("\\*")).getItem(0).cast(IntegerType)).as("avg_length"),
    avg(split(df1("dimensions"), ("\\*")).getItem(1).cast(IntegerType)).as("avg_width")
  ).
  select(
    $"location", $"avg_length", $"avg_width",
    concat($"avg_length", lit("*"), $"avg_width").as("avg_dimensions")
  )

dfAverage.show
+---------+----------+---------+--------------+
| location|avg_length|avg_width|avg_dimensions|
+---------+----------+---------+--------------+
|Bangalore|     750.0|    350.0|   750.0*350.0|
|  Chennai|     600.0|    200.0|   600.0*200.0|
+---------+----------+---------+--------------+
</code>```

Title: Calculate average using Spark Scala

Body:
How do I calculate the Average salary per location in Spark Scala with below two data sets ?

File1.csv(Column 4 is salary)

Ram, 30, Engineer, 40000
Bala, 27, Doctor, 30000
Hari, 33, Engineer, 50000
Siva, 35, Doctor, 60000

File2.csv(Column 2 is location)

Hari, Bangalore
Ram, Chennai
Bala, Bangalore
Siva, Chennai

The above files are not sorted. Need to join these 2 files and find average salary per location. I tried with below code but unable to make it.

val salary = sc.textFile("File1.csv").map(e => e.split(","))
val location = sc.textFile("File2.csv").map(e.split(","))
val joined = salary.map(e=>(e(0),e(3))).join(location.map(e=>(e(0),e(1)))
val joinedData = joined.sortByKey()
val finalData = joinedData.map(v => (v._1,v._2._1._1,v._2._2))
val aggregatedDF = finalData.map(e=> e.groupby(e(2)).agg(avg(e(1))))
aggregatedDF.repartition(1).saveAsTextFile("output.txt")

Please help with code and sample output how it will look.

Many Thanks

Body:
You can read the CSV files as DataFrames, then join and group them to get the averages:

val df1 = spark.read.csv("/path/to/file1.csv").toDF(
  "name", "age", "title", "salary"
)

val df2 = spark.read.csv("/path/to/file2.csv").toDF(
  "name", "location"
)

import org.apache.spark.sql.functions._

val dfAverage = df1.join(df2, Seq("name")).
  groupBy(df2("location")).agg(avg(df1("salary")).as("average")).
  select("location", "average")

dfAverage.show
+-----------+-------+
|   location|average|
+-----------+-------+
|Bangalore  |40000.0|
|  Chennai  |50000.0|
+-----------+-------+

[UPDATE] For calculating average dimensions:

// file1.csv:
Ram,30,Engineer,40000,600*200
Bala,27,Doctor,30000,800*400
Hari,33,Engineer,50000,700*300
Siva,35,Doctor,60000,600*200

// file2.csv
Hari,Bangalore
Ram,Chennai
Bala,Bangalore
Siva,Chennai

val df1 = spark.read.csv("/path/to/file1.csv").toDF(
  "name", "age", "title", "salary", "dimensions"
)

val df2 = spark.read.csv("/path/to/file2.csv").toDF(
  "name", "location"
)

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.IntegerType

val dfAverage = df1.join(df2, Seq("name")).
  groupBy(df2("location")).
  agg(
    avg(split(df1("dimensions"), ("\\*")).getItem(0).cast(IntegerType)).as("avg_length"),
    avg(split(df1("dimensions"), ("\\*")).getItem(1).cast(IntegerType)).as("avg_width")
  ).
  select(
    $"location", $"avg_length", $"avg_width",
    concat($"avg_length", lit("*"), $"avg_width").as("avg_dimensions")
  )

dfAverage.show
+---------+----------+---------+--------------+
| location|avg_length|avg_width|avg_dimensions|
+---------+----------+---------+--------------+
|Bangalore|     750.0|    350.0|   750.0*350.0|
|  Chennai|     600.0|    200.0|   600.0*200.0|
+---------+----------+---------+--------------+


问:
max. length of List in Java
What is the maximum length of List in java? I mean that how many maximum elements can store in list?</p>

答:
```<code>Integer.MAX_VALUE
</code>```

or heap which ever is low will be the limit

Title: max. length of List in Java

Body:
Integer.MAX_VALUE

or heap which ever is low will be the limit


问:
how to get a value from function
i have a function that check if the value that the user entered is nil or not (spouse to be double). all the vars are declare inside the function.
now, I'm trying to get the var from the function and use it in my other code (outside the function). i tried to do it with return option but its show me an error.
i look for it in google and as i see there I'm not sure if i can actually do it.
does anyone have an idea how can i solve it?
here is my code:

```<code>func numbers() -> Double  {
print("enter plate heigh")
let num1 = Double(readLine()!)

if checkIfNil(value1: num1){
    print("plaese enter valid heigh")
    numbers()
}
else{
    let x = num1
    print("good! \(num1)")
    return x!
}
return 0.0
}

let platHeigh = numbers()
print("is: \(platHeigh)")
</code>```

tnx!

答:
The main issue with your posted code is the fact that you don't make use of the result of calling numbers() inside your numbers function. You also have problems with force-unwrapping nil values which will causes crashes.

Note: Don't run this in the playground. Only use this in a command-line app.

It should be (ignoring the force-unwrapping issues for now):

```<code>func numbers() -> Double  {
    print("enter plate heigh")
    let num1 = Double(readLine()!)

    if checkIfNil(value1: num1){
        print("plaese enter valid heigh")
        return numbers() // you need to return here
    }
    else{
        let x = num1
        print("good! \(num1)")
        return x!
    }
}
</code>```

But recursion isn't really a good solution for something like this. Use a simple loop.

```<code>func numbers() -> Double  {
    while true {
        print("enter plate height:")
        if let text = readLine() {
            if let num = Double(text) {
                print("good! \(num)")
                return num
            } else {
                print("Invalid number: \(text)")
            }
        }
    }
}
</code>```

Title: how to get a value from function

Body:
i have a function that check if the value that the user entered is nil or not (spouse to be double). all the vars are declare inside the function.
now, I'm trying to get the var from the function and use it in my other code (outside the function). i tried to do it with return option but its show me an error.
i look for it in google and as i see there I'm not sure if i can actually do it.
does anyone have an idea how can i solve it?
here is my code:

func numbers() -> Double  {
print("enter plate heigh")
let num1 = Double(readLine()!)

if checkIfNil(value1: num1){
    print("plaese enter valid heigh")
    numbers()
}
else{
    let x = num1
    print("good! \(num1)")
    return x!
}
return 0.0
}

let platHeigh = numbers()
print("is: \(platHeigh)")

tnx!

Body:
The main issue with your posted code is the fact that you don't make use of the result of calling numbers() inside your numbers function. You also have problems with force-unwrapping nil values which will causes crashes.

Note: Don't run this in the playground. Only use this in a command-line app.

It should be (ignoring the force-unwrapping issues for now):

func numbers() -> Double  {
    print("enter plate heigh")
    let num1 = Double(readLine()!)

    if checkIfNil(value1: num1){
        print("plaese enter valid heigh")
        return numbers() // you need to return here
    }
    else{
        let x = num1
        print("good! \(num1)")
        return x!
    }
}

But recursion isn't really a good solution for something like this. Use a simple loop.

func numbers() -> Double  {
    while true {
        print("enter plate height:")
        if let text = readLine() {
            if let num = Double(text) {
                print("good! \(num)")
                return num
            } else {
                print("Invalid number: \(text)")
            }
        }
    }
}


问:
Shuffle files while keeping filename the same
I need a script to shuffle around some images but leave the resource filename the same.

I'm using the following PHP script called from a cron job every five minutes.  It works, but is inelegant.

```<code><?php

rename("/www/images/vvx300-background.png", "/www/images/vvx300-background-X.png");

sleep(5); //a precaution I guess

rename("/www/images/vvx300-background-B.png", "/www/images/vvx300-background.png");

sleep(5);

rename("/www/images/vvx300-background-C.png", "/www/images/vvx300-background-B.png");

sleep(5);

rename("/www/images/vvx300-background-X.png", "/www/images/vvx300-background-C.png");

?>
</code>```

So, there are 3 images:

The current image is moved to X.
(pause 5)
B is moved to replace current image.
(pause 5)
C is renamed to B.
(pause 5)
X is renamed to C.

Surely this isn't the best way to do this....

If you are curious, these are IP phone screen idle images to give the user a bit of variety - the phones reach out to a fixed URL for their images, thus the need to keep the resource filename the same.  The files are on a web host and I can't do a shell script.

Your suggestions are most welcome.

答:
This was what I finally did but it does not comply with the original question. That is why I selected the answer above.  I used that answer's methods in addition to php's image handling functions.

This php is the image resource and not the static png file.

```<code><?php

$files = glob("images/*.png");
$current = file_get_contents("current.txt");

if (count($files) <= $current) {
    $current = 1;
} else {
     $current++;
}

$im = imagecreatefrompng("images/".$current.".png");

header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

file_put_contents("current.txt", $current);

?>
</code>```

Body:
I need a script to shuffle around some images but leave the resource filename the same.

I'm using the following PHP script called from a cron job every five minutes.  It works, but is inelegant.

<?php

rename("/www/images/vvx300-background.png", "/www/images/vvx300-background-X.png");

sleep(5); //a precaution I guess

rename("/www/images/vvx300-background-B.png", "/www/images/vvx300-background.png");

sleep(5);

rename("/www/images/vvx300-background-C.png", "/www/images/vvx300-background-B.png");

sleep(5);

rename("/www/images/vvx300-background-X.png", "/www/images/vvx300-background-C.png");

?>

So, there are 3 images:

The current image is moved to X.
(pause 5)
B is moved to replace current image.
(pause 5)
C is renamed to B.
(pause 5)
X is renamed to C.

Surely this isn't the best way to do this....

If you are curious, these are IP phone screen idle images to give the user a bit of variety - the phones reach out to a fixed URL for their images, thus the need to keep the resource filename the same.  The files are on a web host and I can't do a shell script.

Your suggestions are most welcome.

Body:
This was what I finally did but it does not comply with the original question. That is why I selected the answer above.  I used that answer's methods in addition to php's image handling functions.

This php is the image resource and not the static png file.

<?php

$files = glob("images/*.png");
$current = file_get_contents("current.txt");

if (count($files) <= $current) {
    $current = 1;
} else {
     $current++;
}

$im = imagecreatefrompng("images/".$current.".png");

header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

file_put_contents("current.txt", $current);

?>


问:
JSON deserialize array of long to list<long> not working
I have a controller giving JSON as response.

```<code>public ActionResult Messages()
{
   var Ids = new List<long>() { 1,2,3,4 };
   var data = JsonConvert.SerializeObject(Ids);
   return Json(data, JsonRequestBehavior.AllowGet);
}
</code>```

Results in this JSON being responded:

[1,2,3,4]

At the client-side I'm trying to deserialize that JSON back to a List using :

using (_HttpResponse = client.SendAsync(_HttpRequest).Result)
{
    _HttpResponse.EnsureSuccessStatusCode();
    var _ResponseContent = await _HttpResponse.Content.ReadAsStringAsync();
    var Ids = JsonConvert.DeserializeObject<List<long>>(_ResponseContent);
}
```

<p>_ResponseContent becomes:</p>

```"[1,2,3,4]"
```

Mark the " around the array.
At deserialization I get the following exception :

Error converting value "[1,2,3,4]" to type 'System.Collections.Generic.List`1[System.Int64]'. Path '', line 1, position 11.

Any suggestions ?

答:
JsonConvert.SerializeObject method convert your list of numbers to be a JSON string and you are returning that string from your action method. So basically your output is not really a json array of numbers, but a string like this

```<code>"[1,2,3,4]"
</code>```

You should simply use the Json method which returns the correct json array

```<code>public ActionResult Messages()
{
    var Ids = new List<long>() { 1, 2, 3, 4 };
    return Json(Ids, JsonRequestBehavior.AllowGet);
}
</code>```

This method should return a response like this

```<code>[1,2,3,4]
</code>```

With this response, your other client code should be able to properly deserialize it to a list of numbers

Body:
I have a controller giving JSON as response.

public ActionResult Messages()
{
   var Ids = new List<long>() { 1,2,3,4 };
   var data = JsonConvert.SerializeObject(Ids);
   return Json(data, JsonRequestBehavior.AllowGet);
}

Results in this JSON being responded:

[1,2,3,4]

At the client-side I'm trying to deserialize that JSON back to a List using :

using (_HttpResponse = client.SendAsync(_HttpRequest).Result)
{
    _HttpResponse.EnsureSuccessStatusCode();
    var _ResponseContent = await _HttpResponse.Content.ReadAsStringAsync();
    var Ids = JsonConvert.DeserializeObject<List<long>>(_ResponseContent);
}

_ResponseContent becomes:

"[1,2,3,4]"

Mark the " around the array.
At deserialization I get the following exception :

Error converting value "[1,2,3,4]" to type 'System.Collections.Generic.List`1[System.Int64]'. Path '', line 1, position 11.

Any suggestions ?

Body:
JsonConvert.SerializeObject method convert your list of numbers to be a JSON string and you are returning that string from your action method. So basically your output is not really a json array of numbers, but a string like this

"[1,2,3,4]"

You should simply use the Json method which returns the correct json array

public ActionResult Messages()
{
    var Ids = new List<long>() { 1, 2, 3, 4 };
    return Json(Ids, JsonRequestBehavior.AllowGet);
}

This method should return a response like this

[1,2,3,4]

With this response, your other client code should be able to properly deserialize it to a list of numbers


答:
Try

```<code>^[0-9]{5,6}@(student|teacher)\.de$
</code>```

This assumes that you want a five or six digit number (possibly with proceeding zeros) followed by an at sign followed by either the student or the teacher domain.

Title: something wrong with regex

Body: That's my first project when I use regex and I have a little problem when I'm validating email. I use the following formula: ^[0-9]{5,6}+(@student\\\.de)|(@teacher\\\.de) (it starts with 5 or 6 numbers and then are two alternative domains). But it's still doesn't work and I can't find the mistake in the formula. Could anyone help me?

Body:
Try

^[0-9]{5,6}@(student|teacher)\.de$

This assumes that you want a five or six digit number (possibly with proceeding zeros) followed by an at sign followed by either the student or the teacher domain.


问:
Share variables between elements in polymer
I have a component <my-comp> which has a property with double binding which I pass to a different component <my-sec-comp show-drawer="{{showDrawer}}">.
When I change the property showDrawer in the parent element it is also noticed in the child element. But not the other way around. How can I achieve this?

declaration in  child element is:

```<code> showDrawer : {
                type: Boolean,
                notify: true
            }
</code>```

declaration in parent element is:

```<code>showDrawer : {
                type: Boolean,
                notify: true,
                observer: '_drawerChanged'
            },
</code>```

答:
In Polymer before 2.0, you can't. There are no two way bindings between parent and child elements, only between properties and elements within the same element.

If you want to update variables from child to parent, use an event, like this.fire('drawerChanged', this.showDrawer) or try this.parentElement.set('showDrawer', this.showDrawer) inside your _drawerChanged method.

Body:
I have a component <my-comp> which has a property with double binding which I pass to a different component <my-sec-comp show-drawer="{{showDrawer}}">.
When I change the property showDrawer in the parent element it is also noticed in the child element. But not the other way around. How can I achieve this?

declaration in  child element is:

 showDrawer : {
                type: Boolean,
                notify: true
            }

declaration in parent element is:

showDrawer : {
                type: Boolean,
                notify: true,
                observer: '_drawerChanged'
            },


问:
"Do nothing" in the else-part of the ternary operator?
What's the standard line to add to the ternary operator in order to do nothing if the condition is not met?

Example:

```<code>int a = 0;
a > 10 ? a = 5 : /*do nothing*/;
</code>```

Using a seems to do the trick, but I am wondering if there is a more generally accepted way.

答:
You can do:

```<code>a > 10 ? a=5 : 0;
</code>```

But, I would prefer:

```<code>if (a > 10)
   a = 5;
</code>```

Body:
What's the standard line to add to the ternary operator in order to do nothing if the condition is not met?

Example:

int a = 0;
a > 10 ? a = 5 : /*do nothing*/;

Using a seems to do the trick, but I am wondering if there is a more generally accepted way.

Body:
You can do:

a > 10 ? a=5 : 0;

But, I would prefer:

if (a > 10)
   a = 5;