问:
Fading out a WPF control on Visibility.Hidden
I'd like to use style to make a WPF control (in this case a 3rd party one from Telerik, but could be anything) fade out as it's Visibility property is changed to Hidden. This approach I'm trying to use works well for fading in content after it's set to Visibility.Visible. But this does NOT work the opposite way:

```<code><Style x:Key="FadeoutStyle" TargetType="telerik:RadDiagramShape">
    <Style.Triggers>
        <Trigger Property="Visibility" Value="Hidden">
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                 From="1.0" To="0.0" Duration="0:0:1"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

I'm pretty sure of why this doesn't work: as soon as the control is set to Hidden, WPF stops drawing it. So my animation might even be playing, but it's not showing because Visibility.Hidden immediately got applied.

Question 1: Is my assumption correct? Question 2: What is a good pattern to work around this? I can imagine a solution where a custom property initiates the fadeout anim and uses a callback once done that applies the actual Visibility.Hidden setting. Is there a cleaner solution?

答:
Visibility.Hidden issues aside, ultimately it turned out that I was using the trigger incorrectly. My working version (using a different property) looks like this:</p>

```<code>  <Trigger Property="IsEnabled" Value="False">
      <Trigger.EnterActions>
          <BeginStoryboard>
              <Storyboard>
                  <DoubleAnimation Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:0.2"/>
              </Storyboard>
          </BeginStoryboard>
      </Trigger.EnterActions>
      <Trigger.ExitActions>
          <BeginStoryboard>
              <Storyboard>
                  <DoubleAnimation Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:0.2"/>
              </Storyboard>
          </BeginStoryboard>
      </Trigger.ExitActions>
  </Trigger>
</code>```

Body:
I'd like to use style to make a WPF control (in this case a 3rd party one from Telerik, but could be anything) fade out as it's Visibility property is changed to Hidden. This approach I'm trying to use works well for fading in content after it's set to Visibility.Visible. But this does NOT work the opposite way:

</Style>

I'm pretty sure of why this doesn't work: as soon as the control is set to Hidden, WPF stops drawing it. So my animation might even be playing, but it's not showing because Visibility.Hidden immediately got applied.

Question 1: Is my assumption correct? Question 2: What is a good pattern to work around this? I can imagine a solution where a custom property initiates the fadeout anim and uses a callback once done that applies the actual Visibility.Hidden setting. Is there a cleaner solution?

Body:
Visibility.Hidden issues aside, ultimately it turned out that I was using the trigger incorrectly. My working version (using a different property) looks like this:

  <Trigger Property="IsEnabled" Value="False">
      <Trigger.EnterActions>
          <BeginStoryboard>
              <Storyboard>
                  <DoubleAnimation Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:0.2"/>
              </Storyboard>
          </BeginStoryboard>
      </Trigger.EnterActions>
      <Trigger.ExitActions>
          <BeginStoryboard>
              <Storyboard>
                  <DoubleAnimation Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:0.2"/>
              </Storyboard>
          </BeginStoryboard>
      </Trigger.ExitActions>
  </Trigger>


来源: stackexchange

问:
How to apply CSS changes in every posts (every posts ID)
I want to hide the side bar and stretch the content box to full width to all posts from my WP blog. To individual posts that's what I'm doing, and it's working fine:

```<code>.postid-72 #main-sidebar {
display: none;
}
.postid-72 #main-content {
width: 100%;
}
</code>```

But I'm looking for some way to apply this changes to all my blog posts, something hypothetical like this:

```<code>.postid-**every id posts** #main-sidebar {
display: none;
}
.postid-**every id posts** #main-content {
width: 100%;
}
</code>```

I know that is possible to do something like this, which isn't usefull for me:

```<code>.postid-72, .postid-53, .postid-115 #main-sidebar {
display: none;
}
</code>```

答:
Sounds like you are looking for the CSS Attribute Selector. Specifically:

The [attribute^="value"] selector is used to select elements whose attribute value begins with a specified value.

So to select any element with a class that starts with "postid-" you could use the following:

```<code>[class^="postid-"] #main-sidebar {
display: none;
}
[class^="postid-"] #main-content {
width: 100%;
}
</code>```

Note the ^=

This will select all elements that have a class beginning with the string inside the quotes. Leaving out the ^ would yield the same results as using .postid- as the selector.

Also note, while these selectors can be a very powerful addition to your CSS toolkit they can have their pitfalls. It becomes much easier to unintentionally select other elements; especially in the large ecosystem of WP plugins.

ContentLicense: CC BY-SA 3.0

Body:
I want to hide the side bar and stretch the content box to full width to all posts from my WP blog. To individual posts that's what I'm doing, and it's working fine:

.postid-72 #main-sidebar {
display: none;
}
.postid-72 #main-content {
width: 100%;
}

But I'm looking for some way to apply this changes to all my blog posts, something hypothetical like this:

.postid-**every id posts** #main-sidebar {
display: none;
}
.postid-**every id posts** #main-content {
width: 100%;
}

I know that is possible to do something like this, which isn't usefull for me:

.postid-72, .postid-53, .postid-115 #main-sidebar {
display: none;
}

Body:
Sounds like you are looking for the CSS Attribute Selector. Specifically:

The [attribute^="value"] selector is used to select elements whose attribute value begins with a specified value.

So to select any element with a class that starts with "postid-" you could use the following:

[class^="postid-"] #main-sidebar {
display: none;
}
[class^="postid-"] #main-content {
width: 100%;
}

Note the ^=

This will select all elements that have a class beginning with the string inside the quotes. Leaving out the ^ would yield the same results as using .postid- as the selector.

Also note, while these selectors can be a very powerful addition to your CSS toolkit they can have their pitfalls. It becomes much easier to unintentionally select other elements; especially in the large ecosystem of WP plugins.


问:
cmd module - python
I am trying to build a python shell using cmd module.

```<code>from cmd import Cmd
import subprocess
import commands
import os
from subprocess import call

class Pirate(Cmd):
    intro = 'Welcome to shell\n'
    prompt = 'platform> '
    pass

if __name__ == '__main__':
    Pirate().cmdloop()
</code>```

I am trying to build a shell using python - cmd module. I am trying to build these two functionalities.

Welcome to shell

platform> ls

platform> cd ..

like if I want to perform
ls - list all files from that directory in my python shell
or
cd .. - go back to prev directory

Can anyone help in this?
I tried using subprocess library.. but didn't get it working.

Appreciate your help !
Ref Doc: https://docs.python.org/3/library/cmd.html

答:
```<code>def do_shell(self, line):
    "Run a shell command"
    print "running shell command:", line
    sub_cmd = subprocess.Popen(line,shell=True,stdout=subprocess.PIPE)
    output = sub_cmd.communicate()[0]
    print output
    self.last_output = output
</code>```

In command line:

```<code>(Cmd)!ls
(Cmd)!pwd
</code>```

Title: cmd module - python

Body:
I am trying to build a python shell using cmd module.

from cmd import Cmd
import subprocess
import commands
import os
from subprocess import call

class Pirate(Cmd):
    intro = 'Welcome to shell\n'
    prompt = 'platform> '
    pass

if __name__ == '__main__':
    Pirate().cmdloop()

I am trying to build a shell using python - cmd module. I am trying to build these two functionalities.

Welcome to shell

platform> ls

platform> cd ..

like if I want to perform
ls - list all files from that directory in my python shell
or
cd .. - go back to prev directory

Can anyone help in this?
I tried using subprocess library.. but didn't get it working.

Appreciate your help !
Ref Doc: https://docs.python.org/3/library/cmd.html

Body:
def do_shell(self, line):
    "Run a shell command"
    print "running shell command:", line
    sub_cmd = subprocess.Popen(line,shell=True,stdout=subprocess.PIPE)
    output = sub_cmd.communicate()[0]
    print output
    self.last_output = output

In command line:

(Cmd)!ls
(Cmd)!pwd


问:
Adding multiple elements of a single columns of dataframe in python
dataframe = ax

```<code>Col1
0.98 0.076 0.09
0.81 0.01  0.378
0.12 0.33 0.001
</code>```

I want to add these multiple elements of a single row which are separated by space in python such that my output be like

```<code>   Col1                    Summm
0.98 0.076 0.09        0.98+0.076+0.09
0.81 0.01  0.378       0.81+0.01+0.378
0.12 0.33 0.001        0.12+0.33+0.001
</code>```

I have tried this

```<code>summ = numpy.sum(array[0:len(ax),1:len(ax[0])],axis=1).tolist()
</code>```

but this doesnt giv me proper output
Any help would be much appreciated..Thanks

Body:
dataframe = ax

Col1
0.98 0.076 0.09
0.81 0.01  0.378
0.12 0.33 0.001

I want to add these multiple elements of a single row which are separated by space in python such that my output be like

   Col1                    Summm
0.98 0.076 0.09        0.98+0.076+0.09
0.81 0.01  0.378       0.81+0.01+0.378
0.12 0.33 0.001        0.12+0.33+0.001

I have tried this

summ = numpy.sum(array[0:len(ax),1:len(ax[0])],axis=1).tolist()

but this doesnt giv me proper output
Any help would be much appreciated..Thanks

Body:
Let's try:

df.assign(Summm=df.Col1.str.split('\s+',expand=True).astype(float).sum(1))

Output:

               Col1  Summm
0   0.98 0.076 0.09  1.146
1  0.81 0.01  0.378  1.198
2   0.12 0.33 0.001  0.451


问:
SQL joins by naming the different Tables
So I have learned to join tables in SQL like this:

```<code>SELECT data1, data2 FROM table1, table2 WHERE table1.ID = table2.ID
</code>```

Having problems with a task I researched and found sites that taught to use

```<code>SELECT table1.data1, table2.data2
FROM table1
INNER JOIN table2 ON table1.ID = table2.ID
</code>```

Is there a difference between the two or do they just do the same? Which one should I use?

答: Both of your queries are equivalent in function. The second is strongly preferred: a query with explicit joins is more understandable, with implicit joins (your first query) the join constraints and the general filtering constraints are intermingled. Also, inner join is not the only join type: for outer joins it can be challenging to get the syntax correct when the constraints are in the where clause.</p>

ContentLicense: CC BY-SA 4.0

Body:
So I have learned to join tables in SQL like this:

SELECT data1, data2 FROM table1, table2 WHERE table1.ID = table2.ID

Having problems with a task I researched and found sites that taught to use

SELECT table1.data1, table2.data2
FROM table1
INNER JOIN table2 ON table1.ID = table2.ID

Is there a difference between the two or do they just do the same? Which one should I use?


问:
What's the point of a view constraint?
Where are view constraints useful? By that I mean, Oracle allows a constraint to be created on a view. They are not enforced by the database. It seems to be just more metadata that can be used by the database, but I'm trying to understand under what circumstances they are useful.

Tom Kyte answered in a question:

They are used for complex query rewrites with materialized views and such.  It is more "meta data"
  -- it gives the optimizer more information, allows for a broader range of query rewriting to take
  place.

... but that's a bit brief.

答:
From Oracle Documentation :

View Constraints

You can create constraints on views. The only type of constraint supported on a view is a RELY constraint.

This type of constraint is useful when queries typically access views instead of base tables, and the database administrator thus needs to define the data relationships between views rather than tables. View constraints are particularly useful in OLAP environments, where they may enable more sophisticated rewrites for materialized views.

Quoted another Oracle Documentation page, but never used constraints on views anyway.

ContentLicense: CC BY-SA 2.5

Title: What's the point of a view constraint?


问:
Get first item of every sublist of list in Python
I have the following string which is a list of lists:

```<code>"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]
</code>```

I want to grab all the first values of each list into a variable, so the output should be in this case

```<code>print variable
</code>```

expected output:

```<code>310.5
310.0
310.0
309.5
</code>```

答:
To capture the first elements into a variable, you can use a list comprehension like:

Code:

```<code>data = {
    'ID': [[310.5, 1.1612828],
           [310.0, 15.0],
           [310.0, 2.9755309],
           [309.5, 30.0]]
}

variable = [x[0] for x in data['ID']]

print(variable)
</code>```

Results:

```<code>[310.5, 310.0, 310.0, 309.5]
</code>```

Body:
I have the following string which is a list of lists:

"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]

I want to grab all the first values of each list into a variable, so the output should be in this case

print variable

expected output:

310.5
310.0
310.0
309.5

Body:
To capture the first elements into a variable, you can use a list comprehension like:

Code:

data = {
    'ID': [[310.5, 1.1612828],
           [310.0, 15.0],
           [310.0, 2.9755309],
           [309.5, 30.0]]
}

variable = [x[0] for x in data['ID']]

print(variable)

Results:

[310.5, 310.0, 310.0, 309.5]


问:
Multitasking latency and throughput
I have been doing some experimentation around multi-threading and multi-tasking and I have a few questions.

1) Consider a machine with just one CPU core/processor. Running multiple threads parallely is achieved by time slicing (each thread is given a few milliseconds to run on the CPU) and if one thread is blocked on I/O, the others can run, thus giving an impression of doing multiple things concurrently.

Consider the same single processor CPU and say there are two threads, both of which is CPU intensive and does no I/O.
Each takes 5 seconds to complete its operation. Running it sequentially will take obviously 10 secs.

Will running it parallely (using executor service) also take 10 seconds since the threads are CPU intensive only? (given that there is only one CPU core)

2) On a machine with four cores, I have a task that will take 5 seconds to complete when run independently. I wanted to run a couple of them in parallel as separate processes using Java's ProcessBuilder (I don't want to run as parallel threads as the object that they share is not thread safe and cost of synchronization is too much).
I expected it to complete around 5 seconds.

Starting two parallel process did not yield much improvement as they still took around 9 seconds to complete. Why is that? (the task is both CPU intensive and consumes significant memory).
  Note: As I start three or four processes, the latency is more and more affected (worse or equivalent to running them in sequence).

EDIT

My intention/ question is more around why the performance is not improved when using processes rather than whether I should use multiple threads/process for my second question.
For question 2, (for the sake of discussion) you can simple imagine the task like this: (Although the numbers mentioned in the question above is not from the below snippet)

```<code>String s;
for (int i = 0; i < 50000; i++) {
 s += i; //consumes a lot of memory
}

long result = 0;
for(int j = 0; j < 3; j++) {
  for (double i = 0; i < 500000000; i++) { //Lot of CPU
    result += i;
   }
}
</code>```

答:
```<code>Answer to your 1st question:
</code>```

The process/thread burst diagram is shown below

I/O ==> CPU ==> I/O ===>  CPU ==>...... I/O..... ==> CPU == > I/o

It's pretty obvious that they will start and end up with an I/o burts And the multiprocessing/threading on a single processor is achieved only in time multiplexed manner, like you said.

Coming to your question:
Here both of your jobs/threads are CPu bound jobs and doesn't contain any any internal I/O(refer to flow referred above) operation. Therefore, It might take the same time as that of a sequential setup. In case you have a lot of threads running the same way , which donot have any internal I/o bound operations may take more time than the sequential access because then a lot of time is spent in context switching.

because of such scenarios LongTerm Schedulers are designed and programmed to put a proper mix of I/o bound and Cpu bound jobs in the ready queue.

Title: Multitasking latency and throughput

Body:
I have been doing some experimentation around multi-threading and multi-tasking and I have a few questions.

1) Consider a machine with just one CPU core/processor. Running multiple threads parallely is achieved by time slicing (each thread is given a few milliseconds to run on the CPU) and if one thread is blocked on I/O, the others can run, thus giving an impression of doing multiple things concurrently.

Consider the same single processor CPU and say there are two threads, both of which is CPU intensive and does no I/O.
Each takes 5 seconds to complete its operation. Running it sequentially will take obviously 10 secs.

Will running it parallely (using executor service) also take 10 seconds since the threads are CPU intensive only? (given that there is only one CPU core)

2) On a machine with four cores, I have a task that will take 5 seconds to complete when run independently. I wanted to run a couple of them in parallel as separate processes using Java's ProcessBuilder (I don't want to run as parallel threads as the object that they share is not thread safe and cost of synchronization is too much).
I expected it to complete around 5 seconds.

Starting two parallel process did not yield much improvement as they still took around 9 seconds to complete. Why is that? (the task is both CPU intensive and consumes significant memory).
  Note: As I start three or four processes, the latency is more and more affected (worse or equivalent to running them in sequence).

EDIT

My intention/ question is more around why the performance is not improved when using processes rather than whether I should use multiple threads/process for my second question.
For question 2, (for the sake of discussion) you can simple imagine the task like this: (Although the numbers mentioned in the question above is not from the below snippet)

String s;
for (int i = 0; i < 50000; i++) {
 s += i; //consumes a lot of memory
}

long result = 0;
for(int j = 0; j < 3; j++) {
  for (double i = 0; i < 500000000; i++) { //Lot of CPU
    result += i;
   }
}

Body:
Answer to your 1st question:

The process/thread burst diagram is shown below

I/O ==> CPU ==> I/O ===>  CPU ==>...... I/O..... ==> CPU == > I/o

It's pretty obvious that they will start and end up with an I/o burts And the multiprocessing/threading on a single processor is achieved only in time multiplexed manner, like you said.

Coming to your question:
Here both of your jobs/threads are CPu bound jobs and doesn't contain any any internal I/O(refer to flow referred above) operation. Therefore, It might take the same time as that of a sequential setup. In case you have a lot of threads running the same way , which donot have any internal I/o bound operations may take more time than the sequential access because then a lot of time is spent in context switching.

because of such scenarios LongTerm Schedulers are designed and programmed to put a proper mix of I/o bound and Cpu bound jobs in the ready queue.


问:
What the difference with Angular code
I'm a little confused about this way of getting data from a component in Angular. Why or when should I use the public and get keywords, and is it even needed?

```<code>public get data$(): Observable<any> {
    return this._data$;
}
</code>```

In most examples I've seen it would be like this,

```<code>getData(){
    return this._data;
}
</code>```

Also does the $ have any special meaning?
I tried to google this, but can't seem to find an answer.

答:
getting data from a component in Angular.

This has nothing to do with Angular or components. It's just TypeScript.

You use the public keyword to make a method public.

You use the get keyword to write a getter.

Both concepts are described well in the TypeScript docs, which you should run through.

The $ is merely a naming convention often used for the names of variables which hold streams (observables).

The code fragment you give is perfectly valid TypeScript, since after all TypeScript is just a superset of JavaScript.

```<code>getData(){
    return this._data;
}
</code>```

Title: What the difference with Angular code

Body:
I'm a little confused about this way of getting data from a component in Angular. Why or when should I use the public and get keywords, and is it even needed?

public get data$(): Observable<any> {
    return this._data$;
}

In most examples I've seen it would be like this,

getData(){
    return this._data;
}

Also does the $ have any special meaning?
I tried to google this, but can't seem to find an answer.

Body:
getting data from a component in Angular.

This has nothing to do with Angular or components. It's just TypeScript.

You use the public keyword to make a method public.

You use the get keyword to write a getter.

Both concepts are described well in the TypeScript docs, which you should run through.

The $ is merely a naming convention often used for the names of variables which hold streams (observables).

The code fragment you give is perfectly valid TypeScript, since after all TypeScript is just a superset of JavaScript.

getData(){
    return this._data;
}


问:
How to replace a string in a file?
I have 2 numbers in two similar files.  There is a new.txt and original.txt.  They both have the same string in them except for a number.  The new.txt has a string that says boothNumber="3".  The original.txt has a string that says boothNumber="1".

I want to be able to read the new.txt, pick the number 3 out of it and replace the number 1 in original.txt.

Any suggestions?  Here is what I am trying.

```<code>import re  # used to replace string
import sys # some of these are use for other code in my program

def readconfig():
    with open("new.text") as f:
        with open("original.txt", "w") as f1:
            for line in f:
                match = re.search(r'(?<=boothNumber=")\d+', line)
                for line in f1:
                    pattern = re.search(r'(?<=boothNumber=")\d+', line)
                    if re.search(pattern, line):
                        sys.stdout.write(re.sub(pattern, match, line))
</code>```

When I run this, my original.txt gets completely cleared of any text.
I did a traceback and I get this:

in readconfig
for line in f1:
io.UnsupportedOperationo: not readable
```

<p><strong>UPDATE</strong></p>

<p>I tried:</p>

```def readconfig(original_txt_path="original.txt",
               new_txt_path="new.txt"):
    with open(new_txt_path) as f:
        for line in f:
            if not ('boothNumber=') in line:
                continue
            booth_number = int(line.replace('boothNumber=', ''))
            # do we need check if there are more than one 'boothNumber=...' line?
            break
    with open(original_txt_path) as f1:
        modified_lines = [line.startswith('boothNumber=') if not line
                          else 'boothNumber={}'.format(booth_number)
                          for line in f1]
    with open(original_txt_path, mode='w') as f1:
        f1.writelines(modified_lines)
```

<p>And I get error:</p>

```booth_number = int(line.replace('boothNumber=', ''))
ValueError: invalid literal for int() with base 10: '
(workstationID="1" "1" window=1= area="" extra parts of the line here)\n
```

<p>the "1" after workstationID="1" is where the boothNumber=" " would normally go.  When I open up original.txt, I see that it actually did not change anything.</p>

<p><strong>UPDATE 3</strong></p>

<p>Here is my code in full.  Note, the file names are changed but I'm still trying to do the same thing.  This is another idea or revision I had that is still not working:</p>

```import os
import shutil
import fileinput
import re  # used to replace string
import sys # prevents extra lines being inputed in config
           # example: sys.stdout.write

def convertconfig(pattern):
    source = "template.config"
    with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
        for line in file:
            match = r'(?<=boothNumber=")\d+'
            sys.stdout.write(re.sub(match, pattern, line))

def readconfig():
    source = "bingo.config"
    pattern = r'(?<=boothNumber=")\d+'  # !!!!!!!!!! This probably needs fixed
    with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
        for line in file:
            if re.search(pattern, line):
                fileinput.close()
                convertconfig(pattern)

def copyfrom(servername):

    source = r'//' + servername + '/c$/remotedirectory'
    dest = r"C:/myprogram"
    file = "bingo.config"
    try:
        shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))

    except:
        print ("Error")

    readconfig()

# begin here
os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:
    for servername in f:

        copyfrom(servername.strip())
```

<p>bingo.config is my new file
template.config is my original</p>

<p>It's replacing the number in template.config with the literal string "r'(?<=boothNumber=")\d+'"</p>

<p>So template.config ends up looking like</p>

```boothNumber="r'(?<=boothNumber=")\d+'"
```

<p>instead of</p>

```boothNumber="2"
```

答:
To find boothNumber value we can use next regular expression (checked with regex101)

```<code>(?<=\sboothNumber=\")(\d+)(?=\")
</code>```

Something like this should work

```<code>import re
import sys # some of these are use for other code in my program

BOOTH_NUMBER_RE = re.compile('(?<=\sboothNumber=\")(\d+)(?=\")')
search_booth_number = BOOTH_NUMBER_RE.search
replace_booth_number = BOOTH_NUMBER_RE.sub

def readconfig(original_txt_path="original.txt",
               new_txt_path="new.txt"):
    with open(new_txt_path) as f:
        for line in f:
            search_res = search_booth_number(line)
            if search_res is None:
                continue
            booth_number = int(search_res.group(0))
            # do we need check if there are more than one 'boothNumber=...' line?
            break
        else:
            # no 'boothNumber=...' line was found, so next lines will fail,
            # maybe we should raise exception like
            # raise Exception('no line starting with "boothNumber" was found')
            # or assign some default value
            # booth_number = -1
            # or just return?
            return

    with open(original_txt_path) as f:
        modified_lines = []
        for line in f:
            search_res = search_booth_number(line)
            if search_res is not None:
                line = replace_booth_number(str(booth_number), line)
            modified_lines.append(line)
    with open(original_txt_path, mode='w') as f:
        f.writelines(modified_lines)
</code>```

Test

```<code># Preparation
with open('new.txt', mode='w') as f:
    f.write('some\n')
    f.write('<jack Fill workstationID="1" boothNumber="56565" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">')

with open('original.txt', mode='w') as f:
    f.write('other\n')
    f.write('<jack Fill workstationID="1" boothNumber="23" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">')

# Invocation
readconfig()

# Checking output
with open('original.txt') as f:
    for line in f:
        # stripping newline character
        print(line.rstrip('\n'))
</code>```

gives

```<code>other
<jack Fill workstationID="1" boothNumber="56565" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">
</code>```

Title: How to replace a string in a file?

Body:
I have 2 numbers in two similar files.  There is a new.txt and original.txt.  They both have the same string in them except for a number.  The new.txt has a string that says boothNumber="3".  The original.txt has a string that says boothNumber="1".

I want to be able to read the new.txt, pick the number 3 out of it and replace the number 1 in original.txt.

Any suggestions?  Here is what I am trying.

import re  # used to replace string
import sys # some of these are use for other code in my program

def readconfig():
    with open("new.text") as f:
        with open("original.txt", "w") as f1:
            for line in f:
                match = re.search(r'(?<=boothNumber=")\d+', line)
                for line in f1:
                    pattern = re.search(r'(?<=boothNumber=")\d+', line)
                    if re.search(pattern, line):
                        sys.stdout.write(re.sub(pattern, match, line))

When I run this, my original.txt gets completely cleared of any text.
I did a traceback and I get this:

in readconfig
for line in f1:
io.UnsupportedOperationo: not readable

UPDATE

I tried:

def readconfig(original_txt_path="original.txt",
               new_txt_path="new.txt"):
    with open(new_txt_path) as f:
        for line in f:
            if not ('boothNumber=') in line:
                continue
            booth_number = int(line.replace('boothNumber=', ''))
            # do we need check if there are more than one 'boothNumber=...' line?
            break
    with open(original_txt_path) as f1:
        modified_lines = [line.startswith('boothNumber=') if not line
                          else 'boothNumber={}'.format(booth_number)
                          for line in f1]
    with open(original_txt_path, mode='w') as f1:
        f1.writelines(modified_lines)

And I get error:

booth_number = int(line.replace('boothNumber=', ''))
ValueError: invalid literal for int() with base 10: '
(workstationID="1" "1" window=1= area="" extra parts of the line here)\n

the "1" after workstationID="1" is where the boothNumber=" " would normally go.  When I open up original.txt, I see that it actually did not change anything.

UPDATE 3

Here is my code in full.  Note, the file names are changed but I'm still trying to do the same thing.  This is another idea or revision I had that is still not working:

import os
import shutil
import fileinput
import re  # used to replace string
import sys # prevents extra lines being inputed in config
           # example: sys.stdout.write

def convertconfig(pattern):
    source = "template.config"
    with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
        for line in file:
            match = r'(?<=boothNumber=")\d+'
            sys.stdout.write(re.sub(match, pattern, line))

def readconfig():
    source = "bingo.config"
    pattern = r'(?<=boothNumber=")\d+'  # !!!!!!!!!! This probably needs fixed
    with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
        for line in file:
            if re.search(pattern, line):
                fileinput.close()
                convertconfig(pattern)

def copyfrom(servername):

    source = r'//' + servername + '/c$/remotedirectory'
    dest = r"C:/myprogram"
    file = "bingo.config"
    try:
        shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))

    except:
        print ("Error")

    readconfig()

# begin here
os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:
    for servername in f:

        copyfrom(servername.strip())

bingo.config is my new file
template.config is my original

It's replacing the number in template.config with the literal string "r'(?<=boothNumber=")\d+'"

So template.config ends up looking like

boothNumber="r'(?<=boothNumber=")\d+'"

instead of

boothNumber="2"

Body:
To find boothNumber value we can use next regular expression (checked with regex101)

(?<=\sboothNumber=\")(\d+)(?=\")

Something like this should work

import re
import sys # some of these are use for other code in my program

BOOTH_NUMBER_RE = re.compile('(?<=\sboothNumber=\")(\d+)(?=\")')
search_booth_number = BOOTH_NUMBER_RE.search
replace_booth_number = BOOTH_NUMBER_RE.sub

def readconfig(original_txt_path="original.txt",
               new_txt_path="new.txt"):
    with open(new_txt_path) as f:
        for line in f:
            search_res = search_booth_number(line)
            if search_res is None:
                continue
            booth_number = int(search_res.group(0))
            # do we need check if there are more than one 'boothNumber=...' line?
            break
        else:
            # no 'boothNumber=...' line was found, so next lines will fail,
            # maybe we should raise exception like
            # raise Exception('no line starting with "boothNumber" was found')
            # or assign some default value
            # booth_number = -1
            # or just return?
            return

    with open(original_txt_path) as f:
        modified_lines = []
        for line in f:
            search_res = search_booth_number(line)
            if search_res is not None:
                line = replace_booth_number(str(booth_number), line)
            modified_lines.append(line)
    with open(original_txt_path, mode='w') as f:
        f.writelines(modified_lines)

Test

# Preparation
with open('new.txt', mode='w') as f:
    f.write('some\n')
    f.write('<jack Fill workstationID="1" boothNumber="56565" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">')

with open('original.txt', mode='w') as f:
    f.write('other\n')
    f.write('<jack Fill workstationID="1" boothNumber="23" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">')

# Invocation
readconfig()

# Checking output
with open('original.txt') as f:
    for line in f:
        # stripping newline character
        print(line.rstrip('\n'))

gives

other
<jack Fill workstationID="1" boothNumber="56565" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">


问:
Is there a PHP function that will check to make sure fields are set in an array
Does php library have any function to check if all required fields are set in an array?  For example:

```<code>function required_fields($vals,$required_fields_names){
    for($i = 0; $i < count($required_fields_names); $i++){
        if(!array_key_exists($required_fields_names[$i],$vals)){
            return false
        }
    }
    return true;
}
</code>```

Is there already a native PHP function/method that does this?

答:
array_difference is the closest built-in function for this:

```<code>function required_fields($vals,$required_fields_names){
    $missing_fields = array_difference($required_fields_names, array_keys($vals));
    return empty($missing_fields);
}
</code>```

Body:
Does php library have any function to check if all required fields are set in an array?  For example:

function required_fields($vals,$required_fields_names){
    for($i = 0; $i < count($required_fields_names); $i++){
        if(!array_key_exists($required_fields_names[$i],$vals)){
            return false
        }
    }
    return true;
}

Is there already a native PHP function/method that does this?

Body:
array_difference is the closest built-in function for this:

function required_fields($vals,$required_fields_names){
    $missing_fields = array_difference($required_fields_names, array_keys($vals));
    return empty($missing_fields);
}


问:
chmod 600 on an apache server web file still allowing access to from world
My webserver is running as www-data, but for some reason this image file can be seen from the web without problem.  Here are the permissions/ownership:

```<code>ls -alht /var/www/html/file.jpeg
-rw------- 1 www-data www-data
</code>```

If I do a chmod 000 on that file, it cannot be seen as would be expected.

I'm completely stumped by this, anyone have any idea what is going on? Many thanks.

答:
Linux permissions work only in the context of linux users not website users.

Your webserver is a single app running as a user:group identity (www-data:www-data) within the linux system. That's all that matters. If your webserver can read/execute the file then technically anybody who visits the website can unless your website app explicitly prohibits them according to ip, app based credentials or similar.

The only thing you can effect by changing permissions on the Linux OS level is to prevent the webserver from reading the file or serving it to anybody or to make so that other linux users on the same system cannot access them. This is particularly important when using shared hosting, where multiple linux users represent many different people using the same Linux server.

http://linuxcommand.org/lts0070.php

If you want to prevent a file on your webserver from being served by your webserver to the public, you should configure your .htaccess file or similar website conf file such as /etc/apache2/sites-available/mysite.conf to disallow access to a particular location.

If you are using nginx as a webserver then your conf file should be found under /etc/nginx/conf.d or /etc/nginx/sites-available or similar

http://www.ducea.com/2006/08/11/apache-tips-tricks-deny-access-to-some-folders/

Alternatively you can restrict access via password using htpasswd

https://wiki.apache.org/httpd/PasswordBasicAuth

Body:
My webserver is running as www-data, but for some reason this image file can be seen from the web without problem.  Here are the permissions/ownership:

ls -alht /var/www/html/file.jpeg
-rw------- 1 www-data www-data

If I do a chmod 000 on that file, it cannot be seen as would be expected.

I'm completely stumped by this, anyone have any idea what is going on? Many thanks.


问:
Grid Layout elements issue
I have an issue with gidLayout. I have a this grid:

this is how it looks in android studio. But when I installing the app in a tablet, all elements look bad.

All the element, are placed correctly in his row and column, but
their background do not touch. Like the layout_columnWeight and layout_rowWeight doesn't works..
See the 200ºC text element:

The code of grid layout and all elements in xml:

```<code>    <GridLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnCount="12"
            android:rowCount="12"
            android:background="@color/black"
            android:layout_weight="1"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Barra notificacions"
                android:id="@+id/textView"
                android:layout_row="0"
                android:layout_column="0"
                android:layout_rowWeight="1"
                android:layout_columnWeight="1"
                android:gravity="center_vertical|center_horizontal"
                android:background="@color/fondoGrid"
                android:layout_margin="1dp"

                android:layout_gravity="fill_horizontal"
                android:layout_columnSpan="7" />
 ...other textViews
</code>```

答:
You need to set layout_width=wrap_content on the grid layout. This should fix the issue.
I had a similar issue; however, my gridlayout was contained inside a frame layout and so I had to set the width to wrap_content on both.

Title: Grid Layout elements issue

Body:
I have an issue with gidLayout. I have a this grid:

this is how it looks in android studio. But when I installing the app in a tablet, all elements look bad.

All the element, are placed correctly in his row and column, but
their background do not touch. Like the layout_columnWeight and layout_rowWeight doesn't works..
See the 200ºC text element:

The code of grid layout and all elements in xml:

    <GridLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnCount="12"
            android:rowCount="12"
            android:background="@color/black"
            android:layout_weight="1"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Barra notificacions"
                android:id="@+id/textView"
                android:layout_row="0"
                android:layout_column="0"
                android:layout_rowWeight="1"
                android:layout_columnWeight="1"
                android:gravity="center_vertical|center_horizontal"
                android:background="@color/fondoGrid"
                android:layout_margin="1dp"

                android:layout_gravity="fill_horizontal"
                android:layout_columnSpan="7" />
 ...other textViews


问:
Excel Form buttons remain in same place, but TopLeftCell is different (all after parent row is unhidden)
Cutting right to the chase, I have a tab with 4 Excel Tables stacked on top of each other. Each row has its own "up" and "down" buttons in the column to the left of the table, like this:

I shrunk the buttons to fit within the same cell (rowheight of 20). This allowed me to use the cell's TopLeftCell.Row property as follows: When clicked, stuff from the button's row is copy-pasted to the row above/below. This is the basic code:

```<code>currRow = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Row
If InStr(Application.Caller, "Up") > 0 Then
    Move_Project_Up currRow
Else
    Move_Project_Down currRow
End If
</code>```

When the user gets to this tab, any empty table-rows are hidden (with a Rows(rr).EntireRow.Hidden = True). The buttons Move and size with cells so they are automatically hidden). All visible buttons work as expected. However, sometimes a user wishes to move a project from the top of one table "up" to the bottom of the above table (i.e. to a currently hidden row). You can imagine wanting to move data from row 312 "up" to row 244 in the image below:

The code successfully makes the move and unhides the row. HERE'S THE PROBLEM: when the row is unhidden, the buttons are dark gray and their TopLeftCell.Row is wrong:

They are NOT disabled. When clicked, they still trigger the assigned macro. However, I can see from a Debug.Print that their TopLeftCell.Row is not necessarily the row they are actually in. In the image above, BOTH SETS OF BUTTONS have a TopLeftCell.Row of 97. That's correct for the first set, but not the second.

Any thoughts on why this might be happening? I suspect it has to do with the unhiding of the rows, and/or the fact that there's a lot happening on this tab (e.g. over 10,000 array formulas).

Thanks in advance!

答: As one commenter (jkpieterse) suggested, setting the .Top property of the "broken" buttons to the .Top value of a cell in the same row worked!

Body:
Cutting right to the chase, I have a tab with 4 Excel Tables stacked on top of each other. Each row has its own "up" and "down" buttons in the column to the left of the table, like this:

I shrunk the buttons to fit within the same cell (rowheight of 20). This allowed me to use the cell's TopLeftCell.Row property as follows: When clicked, stuff from the button's row is copy-pasted to the row above/below. This is the basic code:

currRow = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Row
If InStr(Application.Caller, "Up") > 0 Then
    Move_Project_Up currRow
Else
    Move_Project_Down currRow
End If

When the user gets to this tab, any empty table-rows are hidden (with a Rows(rr).EntireRow.Hidden = True). The buttons Move and size with cells so they are automatically hidden). All visible buttons work as expected. However, sometimes a user wishes to move a project from the top of one table "up" to the bottom of the above table (i.e. to a currently hidden row). You can imagine wanting to move data from row 312 "up" to row 244 in the image below:

The code successfully makes the move and unhides the row. HERE'S THE PROBLEM: when the row is unhidden, the buttons are dark gray and their TopLeftCell.Row is wrong:

They are NOT disabled. When clicked, they still trigger the assigned macro. However, I can see from a Debug.Print that their TopLeftCell.Row is not necessarily the row they are actually in. In the image above, BOTH SETS OF BUTTONS have a TopLeftCell.Row of 97. That's correct for the first set, but not the second.

Any thoughts on why this might be happening? I suspect it has to do with the unhiding of the rows, and/or the fact that there's a lot happening on this tab (e.g. over 10,000 array formulas).

Thanks in advance!


问:
Markdown nuget installation failed
I get this error when I try to install markdown.

Installing 'Markdown 2.2.1'.
  Successfully installed 'Markdown 2.2.1'.
  Adding 'Markdown 2.2.1' to SimpleCMS.
  Uninstalling 'Markdown 2.2.1'.
  Successfully uninstalled 'Markdown 2.2.1'.
  Install failed. Rolling back...
  Could not install package 'Markdown 2.2.1'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

I'm using Microsoft Visual Studio 2013 and I'm on Windows 10. I tried updating the Nuget Package Manager but to no avail.

答:
Markdown 2.2.1 depends on .Net Framework version 4.5.1

The error suggests you're trying to install it in a project targeting .Net framework 4.5

Two options:

Install Markdown 2.1.0

Update the target .Net framework for your application.  This would generally be frowned upon, if you're writing a commercial application.  Fine if it's just yours.

From the package manager console, you can do:

Install-Package Markdown -Version 2.1.0

Title: Markdown nuget installation failed


问:
Why clang report same types as incompatible?
I want to use the pointer returned by malloc() as the name of a multi-dimensional array, thus I cast the pointer. When compiling, I got an error:

```<code>clang++ -o cast cast.cpp
cast.cpp:29:12: error: assigning to 'int8_t (*)[width]' from incompatible type
      'int8_t (*)[width]'
  int8line = (int8_t (*)[width])(array);
           ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
</code>```

But compiling with icpc on the same platform (OS X) and g++/icpc on Linux, no error is thrown.

UPDATE: The width is variable, thus can not be const.

Tested compilers are:

Mac OS X

```<code>icpc (ICC) 17.0.4 20170411

clang --version
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.6.0
Thread model: posix
</code>```

Linux 2.6.32:

```<code>icpc (ICC) 14.0.0 20130728
g++ (GCC) 4.4.6 20110731
</code>```

The result should be:

```<code>icpc -std=c++11 -o cast cast.cpp && ./cast 5
0   1   2   3   4
5   6   7   8   9

0   1   2   3   4
5   6   7   8   9
</code>```

minimum compilable code (updated):

```<code>#include <iostream>
#include <cstdint>

using namespace std;

int main(int argc, char* argv[])
{
  if (argc != 2)
  {
    cerr << "needs one argument\n";
    exit(EXIT_FAILURE);
  }
  long width = atol(argv[1]);

  int8_t *array = static_cast<int8_t(*)>(malloc(sizeof(int8_t)*2*width));
  for (int i = 0; i < 2*width; i++)
    array[i] = i;

  for (int j = 0; j < 2; j++)
  {
    for (int i = 0; i < width; i++)
    {
      cout << static_cast<int>(array[i+j*width]);
      if (i < (width-1))
        cout << '\t';
    }
    cout << '\n';
  }

  cout << '\n';

  int8_t (*int8line)[width];
  int8line = (int8_t (*)[width])(array);
  for (int j = 0; j < 2; j++)
  {
    for (int i = 0; i < width; i++)
    {
      cout << static_cast<int>(int8line[j][i]);
      if (i < (width-1))
        cout << '\t';
    }
    cout << '\n';
  }

  free(array);
  exit(EXIT_SUCCESS);
}
</code>```

答:
I believe it's because it's regular non-constant variable. Other compilers may recognize immutability of this variable but that kind of guess is not something specified by standard.

If you make the variable width constant, it should work:

```<code>const long width = 5;
</code>```

Body:
I want to use the pointer returned by malloc() as the name of a multi-dimensional array, thus I cast the pointer. When compiling, I got an error:

clang++ -o cast cast.cpp
cast.cpp:29:12: error: assigning to 'int8_t (*)[width]' from incompatible type
      'int8_t (*)[width]'
  int8line = (int8_t (*)[width])(array);
           ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

But compiling with icpc on the same platform (OS X) and g++/icpc on Linux, no error is thrown.

UPDATE: The width is variable, thus can not be const.

Tested compilers are:

Mac OS X

icpc (ICC) 17.0.4 20170411

clang --version
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.6.0
Thread model: posix

Linux 2.6.32:

icpc (ICC) 14.0.0 20130728
g++ (GCC) 4.4.6 20110731

The result should be:

icpc -std=c++11 -o cast cast.cpp && ./cast 5
0   1   2   3   4
5   6   7   8   9

0   1   2   3   4
5   6   7   8   9

minimum compilable code (updated):

#include <iostream>
#include <cstdint>

using namespace std;

int main(int argc, char* argv[])
{
  if (argc != 2)
  {
    cerr << "needs one argument\n";
    exit(EXIT_FAILURE);
  }
  long width = atol(argv[1]);

  int8_t *array = static_cast<int8_t(*)>(malloc(sizeof(int8_t)*2*width));
  for (int i = 0; i < 2*width; i++)
    array[i] = i;

  for (int j = 0; j < 2; j++)
  {
    for (int i = 0; i < width; i++)
    {
      cout << static_cast<int>(array[i+j*width]);
      if (i < (width-1))
        cout << '\t';
    }
    cout << '\n';
  }

  cout << '\n';

  int8_t (*int8line)[width];
  int8line = (int8_t (*)[width])(array);
  for (int j = 0; j < 2; j++)
  {
    for (int i = 0; i < width; i++)
    {
      cout << static_cast<int>(int8line[j][i]);
      if (i < (width-1))
        cout << '\t';
    }
    cout << '\n';
  }

  free(array);
  exit(EXIT_SUCCESS);
}

Body:
I believe it's because it's regular non-constant variable. Other compilers may recognize immutability of this variable but that kind of guess is not something specified by standard.

If you make the variable width constant, it should work:

const long width = 5;


问:
Where does SQL Server store the DTS packages?
I have created a few DTS packages and saved them on the server. where I can edit these DTS packages on the server?</p>

答:
you should connect to integration services...
and then in the MSDB folder or in the FileSystem folder, it depends how did you save them</p>

OwnerDisplayName: syalam

OwnerDisplayName: Ironicnet


问:
Get the value of bootstrap Datetimepicker in JavaScript
I need to get the value of Datetimepicker in my JavaScript function. I have made something like this, but it doesn't work:

```<code>$("#date").click( function(){
    alert(document.getElementById('datetimepicker1').value);
});
</code>```

It gives me 'undefined'

答:
To call the Bootstrap-datetimepikcer supported functions, you should use the syntax:

```<code>$('#datetimepicker').data("DateTimePicker").FUNCTION()
</code>```

So you can try the function:

```<code>$('#datetimepicker').data("DateTimePicker").date();
</code>```

Documentation: http://eonasdan.github.io/bootstrap-datetimepicker/Functions/

Body:
I need to get the value of Datetimepicker in my JavaScript function. I have made something like this, but it doesn't work:

$("#date").click( function(){
    alert(document.getElementById('datetimepicker1').value);
});

It gives me 'undefined'

Body:
To call the Bootstrap-datetimepikcer supported functions, you should use the syntax:

$('#datetimepicker').data("DateTimePicker").FUNCTION()

So you can try the function:

$('#datetimepicker').data("DateTimePicker").date();

Documentation: http://eonasdan.github.io/bootstrap-datetimepicker/Functions/


问:
"using namespace std;" without any #include?
I tried following, it worked without problem, but in this situation, std was not defined.</p>

```<code>    using namespace std;

    int main()
    {
       ....
    }
</code>```

答:
Try and do std::cout, it won't work.

using namespace std just defines the namespace

#include {x} 'includes' the code within the namespace

I.e, std::cout would need #include <iostream>. Very simple explanation but it's what is going on.

Body:
I tried following, it worked without problem, but in this situation, std was not defined.

    using namespace std;

    int main()
    {
       ....
    }


问:
spring mvc how to bypass DispatcherServlet for *.html files?
web.xml fragment

```<code><!-- Handles all requests into the application -->
<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/app-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</code>```

It works fine but I'd like to NOT let the Dispatcher Servlet handle *.html requests. How do I I do that? Thanks.

答:
Map it on a more specific url-pattern.

```<code><servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/spring/*</url-pattern>
</servlet-mapping>
</code>```

Create a Filter which is mapped on /*.

```<code><filter-mapping>
    <filter-name>Your Dispatcher Filter</filter-name>
    <url-pattern>/*</url-pattern>
<filter-mapping>
</code>```

Which does the following in doFilter() method.

```<code>String uri = ((HttpServletRequest) request).getRequestURI();
if (uri.endsWith(".html")) {
    chain.doFilter(request, response); // Just let it go (assuming that files are in real not placed in a /spring folder!)
} else {
    request.getRequestDispatcher("/spring" + uri).forward(request, response); // Pass to Spring dispatcher servlet.
}
</code>```

Body:
web.xml fragment

<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/app-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

It works fine but I'd like to NOT let the Dispatcher Servlet handle *.html requests. How do I I do that? Thanks.

Body:
Map it on a more specific url-pattern.

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/spring/*</url-pattern>
</servlet-mapping>

Create a Filter which is mapped on /*.

<filter-mapping>
    <filter-name>Your Dispatcher Filter</filter-name>
    <url-pattern>/*</url-pattern>
<filter-mapping>

Which does the following in doFilter() method.

String uri = ((HttpServletRequest) request).getRequestURI();
if (uri.endsWith(".html")) {
    chain.doFilter(request, response); // Just let it go (assuming that files are in real not placed in a /spring folder!)
} else {
    request.getRequestDispatcher("/spring" + uri).forward(request, response); // Pass to Spring dispatcher servlet.
}


问:
Finding out nth fibonacci number for very large 'n'
I was wondering about how can one find the nth term of fibonacci sequence for a very large value of n say, 1000000. Using the grade-school recurrence equation fib(n)=fib(n-1)+fib(n-2), it takes 2-3 min to find the 50th term!

After googling, I came to know about Binet's formula but it is not appropriate for values of n>79 as it is said here

Is there an algorithm to do so just like we have for finding prime numbers?

答:
I have done a program.
It doesn't take long to calculate the values but the maximum term which can be displayed is the 1477th(because of the max range for double).
Results appear almost instantly.
The series starts from 0.
If there are any improvements needed,please feel free to edit it.</p>

```<code>#include<iostream>
using namespace std;
void fibseries(long int n)
{
    long double x=0;
    double y=1;
    for (long int i=1;i<=n;i++)
     {
        if(i%2==1)
         {
            if(i==n)
             {
              cout<<x<<" ";
             }
            x=x+y;
         }
        else
         {
            if(i==n)
             {
              cout<<x<<" ";
             }
            y=x+y;
         }
     }
}
main()
{
    long int n=0;
    cout<<"The number of terms ";
    cin>>n;
    fibseries(n);
    return 0;
}
</code>```

Body:
I have done a program.
It doesn't take long to calculate the values but the maximum term which can be displayed is the 1477th(because of the max range for double).
Results appear almost instantly.
The series starts from 0.
If there are any improvements needed,please feel free to edit it.

#include<iostream>
using namespace std;
void fibseries(long int n)
{
    long double x=0;
    double y=1;
    for (long int i=1;i<=n;i++)
     {
        if(i%2==1)
         {
            if(i==n)
             {
              cout<<x<<" ";
             }
            x=x+y;
         }
        else
         {
            if(i==n)
             {
              cout<<x<<" ";
             }
            y=x+y;
         }
     }
}
main()
{
    long int n=0;
    cout<<"The number of terms ";
    cin>>n;
    fibseries(n);
    return 0;
}


问:
Inserting a pdf BEFORE the bookdown frontpage
I'm writing my thesis with Bookdown in Rmarkdown (and I will export it to PDF format eventually). To hand in my thesis, I am required to include a few scanned documents with handwritten signatures BEFORE the first page of my thesis.

Bookdown is amazing in combining different Rmd files, but I have not managed to include a PDF document BEFORE the title page.

I have tried this:

```<code>bookdown::pdf_book:
  includes:
    in_header: preamble.tex
    before_body: beforebody.tex
</code>```

With in preamble.tex :

```<code>\usepackage{pdfpages}
</code>```

and in beforebody.tex:

```<code>\includepdf[pages={5}, scale=1]{OfficialFrontpages.pdf}
\newpage
</code>```

However, then it first creates the Bookdown titlepage, and only inserts these pages before the Table of Contents. Is there any way to force this document to be included BEFORE the first page of the final PDF document?

Inclusion of these commands as the lines of the first .Rmd files also doesn't work:

```<code>![Caption](OfficialFrontpages.pdf)
\raggedright
\clearpage
</code>```

答:
Option 1:
You can try something like this

```<code>includes:
    after_body:Title_page.tex
</code>```

Option 2:
Since I am more comfortable in latex, I would generate the main thesis and the official pages as two separate pdf documents, then use latex package pdfpages to combine these two.

Something like

```<code>\usepackage{pdfpages}

\begin{document}

\includepdf[pages={5}, scale=1]{OfficialFrontpages.pdf}
\newpage
\includepdf[pages={-}, scale=1]{MyThesis.pdf}

\end{document}
</code>```

I would finally compile with pdflatex.

Let me know if this was useful.

Body:
I'm writing my thesis with Bookdown in Rmarkdown (and I will export it to PDF format eventually). To hand in my thesis, I am required to include a few scanned documents with handwritten signatures BEFORE the first page of my thesis.

Bookdown is amazing in combining different Rmd files, but I have not managed to include a PDF document BEFORE the title page.

I have tried this:

bookdown::pdf_book:
  includes:
    in_header: preamble.tex
    before_body: beforebody.tex

With in preamble.tex :

\usepackage{pdfpages}

and in beforebody.tex:

\includepdf[pages={5}, scale=1]{OfficialFrontpages.pdf}
\newpage

However, then it first creates the Bookdown titlepage, and only inserts these pages before the Table of Contents. Is there any way to force this document to be included BEFORE the first page of the final PDF document?

Inclusion of these commands as the lines of the first .Rmd files also doesn't work:

![Caption](OfficialFrontpages.pdf)
\raggedright
\clearpage

Body:
Option 1:
You can try something like this

includes:
    after_body:Title_page.tex

Option 2:
Since I am more comfortable in latex, I would generate the main thesis and the official pages as two separate pdf documents, then use latex package pdfpages to combine these two.

Something like

\usepackage{pdfpages}

\begin{document}

\includepdf[pages={5}, scale=1]{OfficialFrontpages.pdf}
\newpage
\includepdf[pages={-}, scale=1]{MyThesis.pdf}

\end{document}

I would finally compile with pdflatex.

Let me know if this was useful.


问:
Writing reusable JsonConverters for json.net
I'm querying a service which returns a list of tags in multiple formats:

```<code>{
  "tags": "a,b,c"
}
</code>```

or

```<code>{
  "tags": "a b c"
}
</code>```

or

```<code>{
  "tags": "a+b+c"
}
</code>```

The object that I want to deserialize this to is a List<string>. I've written a TagsConverter that implements the necessary methods in JsonConverter like so:

```<code>public class TagsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader
                .Value
                .ToString()
                .Split(' ')
                .ToList();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (List<string>)value;
        var delimitedList = string.Join(" ", list);

        writer.WriteValue(delimitedList);
    }
}
</code>```

Then I annotate the field in the object like so:

```<code>public class Foo
{
  [JsonConverter(typeof(TagsConverter))]
  public List<string> Tags { get; set; }
}
</code>```

And this works, but only for tags that are separated by spaces.

However the TagsConverter can work in all 3 scenarios if I'm able to just change the Split and the Join functions in a parameterized fashion. But since we pass only the type to the JsonConverter attribute, I understand that we can't pass a "delimiter" as an argument there.

Is there any way to achieve this?

答:
If only needed for the reading/deserialization of the JSON do note that string.Split can take a character array char[]

```<code>public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    return reader
            .Value
            .ToString()
            .Split(new char[]{' ', ',', '+'}, StringSplitOptions.RemoveEmptyEntries)
            .ToList();
}
</code>```

Which means that the converter can handle all three delimiters when reading.

Body:
I'm querying a service which returns a list of tags in multiple formats:

{
  "tags": "a,b,c"
}

or

{
  "tags": "a b c"
}

or

{
  "tags": "a+b+c"
}

The object that I want to deserialize this to is a List<string>. I've written a TagsConverter that implements the necessary methods in JsonConverter like so:

public class TagsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader
                .Value
                .ToString()
                .Split(' ')
                .ToList();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (List<string>)value;
        var delimitedList = string.Join(" ", list);

        writer.WriteValue(delimitedList);
    }
}

Then I annotate the field in the object like so:

public class Foo
{
  [JsonConverter(typeof(TagsConverter))]
  public List<string> Tags { get; set; }
}

And this works, but only for tags that are separated by spaces.

However the TagsConverter can work in all 3 scenarios if I'm able to just change the Split and the Join functions in a parameterized fashion. But since we pass only the type to the JsonConverter attribute, I understand that we can't pass a "delimiter" as an argument there.

Is there any way to achieve this?

Body:
If only needed for the reading/deserialization of the JSON do note that string.Split can take a character array char[]

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    return reader
            .Value
            .ToString()
            .Split(new char[]{' ', ',', '+'}, StringSplitOptions.RemoveEmptyEntries)
            .ToList();
}

Which means that the converter can handle all three delimiters when reading.


问:
Shortcut Assign to Return Triggers Enter
I assigned a Shortcut in multiline textbox which is Ctrl+Return.

It works but, when I use Ctrl+Return, Enter button triggers and makes cursor go to bottom line. How can I disable Enter when I press Ctrl+Return?

```<code>if (e.Control==true && e.KeyCode == Keys.Return)
 {
        // do anything()
 }
</code>```

答:
If I recall correctly, keydown event will fire after the textbox receives the character. </p>

<p>Try keypress event instead: </p>

```<code>        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == '\n')
        {
            // do anything()
            e.Handled = true;
        }
    }
</code>```

Body:
I assigned a Shortcut in multiline textbox which is Ctrl+Return.

It works but, when I use Ctrl+Return, Enter button triggers and makes cursor go to bottom line. How can I disable Enter when I press Ctrl+Return?

if (e.Control==true && e.KeyCode == Keys.Return)
 {
        // do anything()
 }

Body:
If I recall correctly, keydown event will fire after the textbox receives the character.

Try keypress event instead:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == '\n')
        {
            // do anything()
            e.Handled = true;
        }
    }


问:
Subsonic 3 Newtonsoft JSON "Self referencing loop Exception"
Hi I been searching for my error but I can't find anything that help me. The problem is this. I been working with Subsonic 3, Newtonsoft Json and the linq way of write so I have this easy query:

```<code>var found = from client in newclients.All() where client.Period == "sometext" select client;

string periodoJSON = JsonConvert.SerializeObject(periodoFound); //this get "Self referencing loop Exception"
</code>```

the problem is when I run this script I get the horrible exception "Self referening loop exception" in the JsonConvert line, subsonic have all the objects without any problem but if I do the following.

```<code>var found = from client in newclients.All() where client.Period == "sometext" select new client{client.Name, client.LastName, etc};

string periodoJSON = JsonConvert.SerializeObject(periodoFound);
</code>```

I get the object serialize with a any problem with all the properties. I'm doing the last way because I have to finish my work but is any other way or solution for this problem, if not I will have to write all the properties every time I want to get a full table properties.

hope any can solve my problem o help me in the path for find a solution....

what I have is a really basic query with linq and I try the three values for JsonSerializerSettings and any work, again I'm working with subsonic 3 this not happend either with subsnoic 2 and I can make it work if I specify one by one the properties of the object in the linq query does any have any clue of what is happend, ANY more help would be great!!! If I put the value of Serialize my page get crazy and in a infinity loop state, if I decide for error simple doesn't work and Ignore nothing happen... some more information about this self referencia loop?

```<code>var u = usuario.SingleOrDefault(x => x.TipoUsuario == "A" || x.TipoUsuario == "W");
JsonSerializerSettings setting = new JsonSerializerSettings();
setting.ReferenceLoopHandling = ReferenceLoopHandling.Error; //.Serialize .Ignore

Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"usuario", "var usuario=" + JsonConvert.SerializeObject(u, Formatting.None, setting) + ";");
</code>```

Update ------

I code the following

```<code>string jsU = JsonConvert.SerializeObject(u,Formatting.None,new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
</code>```

and is workign but the only thing wrongs is that in the json object comes all the information about the columns of subsonic 3 and a BIG chunk of text explain it... does any one know how to not SEND this part of the object??

答:
Without knowing more about you object model it is hard to provide a definitive answer, but I would take a look at the ReferenceLoopHandling enum.

You're calling string SerializeObject(object value) on JsonConvert. Try the string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) method instead. The JsonSerializerSettings settings parameter lets you set a bunch of things, including the ReferenceLoopHandling ReferenceLoopHandling { get; set; } property.

You can try these values:

```<code>public enum ReferenceLoopHandling
{
    Error,
    Ignore,
    Serialize
}
</code>```

Obviously, Error is the default and that's what you're getting. Perhaps one of the others will help.

Body:
Hi I been searching for my error but I can't find anything that help me. The problem is this. I been working with Subsonic 3, Newtonsoft Json and the linq way of write so I have this easy query:

var found = from client in newclients.All() where client.Period == "sometext" select client;

string periodoJSON = JsonConvert.SerializeObject(periodoFound); //this get "Self referencing loop Exception"

the problem is when I run this script I get the horrible exception "Self referening loop exception" in the JsonConvert line, subsonic have all the objects without any problem but if I do the following.

var found = from client in newclients.All() where client.Period == "sometext" select new client{client.Name, client.LastName, etc};

string periodoJSON = JsonConvert.SerializeObject(periodoFound);

I get the object serialize with a any problem with all the properties. I'm doing the last way because I have to finish my work but is any other way or solution for this problem, if not I will have to write all the properties every time I want to get a full table properties.

hope any can solve my problem o help me in the path for find a solution....

what I have is a really basic query with linq and I try the three values for JsonSerializerSettings and any work, again I'm working with subsonic 3 this not happend either with subsnoic 2 and I can make it work if I specify one by one the properties of the object in the linq query does any have any clue of what is happend, ANY more help would be great!!! If I put the value of Serialize my page get crazy and in a infinity loop state, if I decide for error simple doesn't work and Ignore nothing happen... some more information about this self referencia loop?

var u = usuario.SingleOrDefault(x => x.TipoUsuario == "A" || x.TipoUsuario == "W");
JsonSerializerSettings setting = new JsonSerializerSettings();
setting.ReferenceLoopHandling = ReferenceLoopHandling.Error; //.Serialize .Ignore

Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"usuario", "var usuario=" + JsonConvert.SerializeObject(u, Formatting.None, setting) + ";");

Update ------

I code the following

string jsU = JsonConvert.SerializeObject(u,Formatting.None,new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

and is workign but the only thing wrongs is that in the json object comes all the information about the columns of subsonic 3 and a BIG chunk of text explain it... does any one know how to not SEND this part of the object??

Body:
Without knowing more about you object model it is hard to provide a definitive answer, but I would take a look at the ReferenceLoopHandling enum.

You're calling string SerializeObject(object value) on JsonConvert. Try the string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) method instead. The JsonSerializerSettings settings parameter lets you set a bunch of things, including the ReferenceLoopHandling ReferenceLoopHandling { get; set; } property.

You can try these values:

public enum ReferenceLoopHandling
{
    Error,
    Ignore,
    Serialize
}

Obviously, Error is the default and that's what you're getting. Perhaps one of the others will help.


问:
In Scala is there a way to reference the Companion Object from within an instance of a Case Class?
In my specific case I have a (growing) library of case classes with a base trait (TKModel)

Then I have an abstract class (TKModelFactory[T <: TKModel]) which is extended by all companion objects.

So my companion objects all inherently know the type ('T') of "answers" they need to provide as well as the type of objects they "normally" accept for commonly implemented methods. (If I get lazy and cut and paste chunks of code to search and destroy this save my bacon a lot!) I do see warnings on the Internet at large however that any form of CompanionObject.method(caseClassInstance: CaseClass) is rife with "code smell" however. Not sure if they actually apply to Scala or not?

There does not however seem to be any way to declare anything in the abstract case class (TKModel) that would refer to (at runtime) the proper companion object for a particular instance of a case class. This results in my having to write (and edit) a few method calls that I want standard in each and every case class.

case class Track(id: Long, name: String, statusID: Long) extends TKModel

object Track extends TKModelFactory[Track]

How would I write something in TKModel such that new Track(1, "x", 1).someMethod() could actually call Track.objectMethod()

Yes I can write val CO = MyCompanionObject along with something like  implicit val CO: ??? in the TKModel abstract class and make all the calls hang off of that value. Trying to find any incantation that makes the compiler happy for that however seems to be mission impossible. And since I can't declare that I can't reference it in any placeholder methods in the abstract class either.

Is there a more elegant way to simply get a reference to a case classes companion object?

My specific question, as the above has been asked before (but not yet answered it seems), is there a way to handle the inheritance of both the companion object and the case classes and find the reference such that I can code common method calls in the abstract class?

Or is there a completely different and better model?

答:
It's difficult. However you can create an implicit method in companion object. whenever you want to invoke your logic from instance, just trigger implicit rules and the implicit method will instantiate another class which will invoke whatever logic you desired.
I believe it's also possible to do this in generic ways.</p>


问:
New to Excel VBA: #Value error on string creation
Sorry all, I assume the error is basic but I am not sure what I am doing incorrectly.

I am attempting to write a function that takes a cell and converts the characters marked in red to lowercase. I do this by reconstructing the string in a new variable.

This reconstructed string is then returned. However, when I try to use this function in Excel on a string, it returns a #Value error. The code has no compilation errors so I am at a loss. Any help would be appreciated.

```<code>
    Function Convert_Red(rng As Range)

    If (rng.Cells.Count > 1) Then
         AcceptOneCell = "Only allow 1 cell"
         Exit Function
    End If

    Dim i As Long
    Dim text As String
    Dim new_text As String
    Dim placeholder As String

    text = rng.Cells(1, 1).Value

    For i = 1 To Len(text)
        If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color  vbRed
    Then
        new_text = new_text + LCase(rng.Cells(1, 1).Characters(Start:=i,
    Length:=1))
        Else
            new_text = new_text + rng.Cells(1, 1).Characters(Start:=i, Length:=1)
       End If
       i = i + 1
    Next

    Convert_Red = new_text

    End Function

</code>```

答:
Try this:

```<code>Option Explicit

Public Function LCaseReds(rng As Range)

    Dim i As Long, ltr As String, adr As String, result As String

    Select Case True
        Case rng.Cells.Count > 1: result = "Use only one cell"
        Case Len(rng.Value2) = 0: result = "Empty cell: '" & rng.Address(False, False) & "'"
        Case Else:
            For i = 1 To Len(rng)
                With rng.Characters(Start:=i, Length:=1)
                    ltr = .Text
                    result = result + IIf(.Font.Color = vbRed, LCase(ltr), ltr)
                End With
            Next
    End Select

    LCaseReds = result

End Function
</code>```

Note that you'll still get the #Value! when using multiple areas (C3, E3)

Body:
Sorry all, I assume the error is basic but I am not sure what I am doing incorrectly.

I am attempting to write a function that takes a cell and converts the characters marked in red to lowercase. I do this by reconstructing the string in a new variable.

This reconstructed string is then returned. However, when I try to use this function in Excel on a string, it returns a #Value error. The code has no compilation errors so I am at a loss. Any help would be appreciated.

    Function Convert_Red(rng As Range)

    If (rng.Cells.Count > 1) Then
         AcceptOneCell = "Only allow 1 cell"
         Exit Function
    End If

    Dim i As Long
    Dim text As String
    Dim new_text As String
    Dim placeholder As String

    text = rng.Cells(1, 1).Value

    For i = 1 To Len(text)
        If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color  vbRed
    Then
        new_text = new_text + LCase(rng.Cells(1, 1).Characters(Start:=i,
    Length:=1))
        Else
            new_text = new_text + rng.Cells(1, 1).Characters(Start:=i, Length:=1)
       End If
       i = i + 1
    Next

    Convert_Red = new_text

    End Function

Body:
Try this:

Option Explicit

Public Function LCaseReds(rng As Range)

    Dim i As Long, ltr As String, adr As String, result As String

    Select Case True
        Case rng.Cells.Count > 1: result = "Use only one cell"
        Case Len(rng.Value2) = 0: result = "Empty cell: '" & rng.Address(False, False) & "'"
        Case Else:
            For i = 1 To Len(rng)
                With rng.Characters(Start:=i, Length:=1)
                    ltr = .Text
                    result = result + IIf(.Font.Color = vbRed, LCase(ltr), ltr)
                End With
            Next
    End Select

    LCaseReds = result

End Function

Note that you'll still get the #Value! when using multiple areas (C3, E3)


问:
How to put name an array of JSON objects using GSON?
I'm creating a JSON file with GSON, but the arrays doesn't have names.

My result:

```<code>[
      {
      "name": Jonh,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   },
      {
      "name": Maria,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   }
]
</code>```

What I need:

```<code>{
  "users": {
    "user": [
      {
        "name": John,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      },
      {
        "name": Maria,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      }
    ]
  }
}
</code>```

Someone knows how can I put name an arrays?

--EDIT

I'm using this code for generate my JSON file.

```<code>    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("user/list")
    public String getListUsers() throws Exception {

        List<Object> list;

        UserDAOImpl daoUser = new UserDAOImpl();
        list = daoUser.listAllUsers();

        Gson g = new Gson();
        return g.toJson(list);

    }
</code>```

答:
What you need is a new Object inside which you'll have to put your list and convert that object to JSON.

```<code>Gson gson = new GsonBuilder().create();
JsonArray jsonArray = gson.toJsonTree(list).getAsJsonArray();
JsonObject userJsonObject = new JsonObject();
jsonObject.add("user", jsonArray);
JsonObject usersJsonObject = new JsonObject();
jsonObject.add("users", usersJsonObject);
</code>```

I haven't tried the code. I hope you get the idea.

Body:
I'm creating a JSON file with GSON, but the arrays doesn't have names.

My result:

[
      {
      "name": Jonh,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   },
      {
      "name": Maria,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   }
]

What I need:

{
  "users": {
    "user": [
      {
        "name": John,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      },
      {
        "name": Maria,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      }
    ]
  }
}

Someone knows how can I put name an arrays?

--EDIT

I'm using this code for generate my JSON file.

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("user/list")
    public String getListUsers() throws Exception {

        List<Object> list;

        UserDAOImpl daoUser = new UserDAOImpl();
        list = daoUser.listAllUsers();

        Gson g = new Gson();
        return g.toJson(list);

    }

Body:
What you need is a new Object inside which you'll have to put your list and convert that object to JSON.

Gson gson = new GsonBuilder().create();
JsonArray jsonArray = gson.toJsonTree(list).getAsJsonArray();
JsonObject userJsonObject = new JsonObject();
jsonObject.add("user", jsonArray);
JsonObject usersJsonObject = new JsonObject();
jsonObject.add("users", usersJsonObject);

I haven't tried the code. I hope you get the idea.


问:
How to make checkbox value non editable from inspect element
I have two checkbox's  where 2 different value set to the checkbox.when a user checked the boxes value will be set. But before save it if he inspects the element and edit the value set a new value  and save into database instead of default value new value save into database.How do i stop doing that to the user..any possible suggestion?</p>

```<code><input name="installation" value="{{$product->installation}}" type="checkbox">

<input name="support" value="{{$product->support}}" type="checkbox">
</code>```

答:
You can simply do not use the data from the value attribute of checkbox when working with the database.

For example, in controller, you can simply check whether the checkbox is checked, and then set any values you want:

```<code>$product->installation = ($request->has('installation')) ? 'checked' : 'not checked';
</code>```

Body:
I have two checkbox's  where 2 different value set to the checkbox.when a user checked the boxes value will be set. But before save it if he inspects the element and edit the value set a new value  and save into database instead of default value new value save into database.How do i stop doing that to the user..any possible suggestion?

<input name="installation" value="{{$product->installation}}" type="checkbox">

<input name="support" value="{{$product->support}}" type="checkbox">

Body:
You can simply do not use the data from the value attribute of checkbox when working with the database.

For example, in controller, you can simply check whether the checkbox is checked, and then set any values you want:

$product->installation = ($request->has('installation')) ? 'checked' : 'not checked';


问:
How can i use Localize in Function or property polymerJS using app-localize-behavior
Localization behavior is working fine for me, but i don't know if i can use it in a ready function and how.

If I use {{localize('greeting')}} in html, Its working fine. But I need to use through function

```<code>initErrorMessage: function(loc) {
  return localize(loc);
},
</code>```

And I need to use in property as well.

```<code>datePickerRangeArray: {
    type: Array,
    value: function() {
      return [
        {"key": "!h8", "val": this.localize('last8hrs')},
        {"key": "!h12", "val": this.localize('last12hrs')},
        {"key": "!h24", "val": this.localize('last24hrs')},
        {"key": "!h168", "val": this.localize('last48hrs')},
        {"key": "current-day", "val": this.localize('CurrentDay')},
        {"key": "previous-day", "val": this.localize('PreviousDay')}];
    }
  }
</code>```

I am getting error on this. How to achieve this. Thanks in advance.

答:
Use this.async function and initialize with  empty object and add localization in attached function with async function. </p>

```<code>datePickerRangeArray: {
    type: Array,
    value: {}
  }

attached: function(){
   this.async(function(){
     datePickerRangeArray = [
        {"key": "!h8", "val": this.localize('last8hrs')},
        {"key": "!h12", "val": this.localize('last12hrs')},
        {"key": "!h24", "val": this.localize('last24hrs')},
        {"key": "!h168", "val": this.localize('last48hrs')},
        {"key": "current-day", "val": this.localize('CurrentDay')},
        {"key": "previous-day", "val": this.localize('PreviousDay')}];
    },10);
}
</code>```

Body:
Localization behavior is working fine for me, but i don't know if i can use it in a ready function and how.

If I use {{localize('greeting')}} in html, Its working fine. But I need to use through function

initErrorMessage: function(loc) {
  return localize(loc);
},

And I need to use in property as well.

datePickerRangeArray: {
    type: Array,
    value: function() {
      return [
        {"key": "!h8", "val": this.localize('last8hrs')},
        {"key": "!h12", "val": this.localize('last12hrs')},
        {"key": "!h24", "val": this.localize('last24hrs')},
        {"key": "!h168", "val": this.localize('last48hrs')},
        {"key": "current-day", "val": this.localize('CurrentDay')},
        {"key": "previous-day", "val": this.localize('PreviousDay')}];
    }
  }

I am getting error on this. How to achieve this. Thanks in advance.

Body:
Use this.async function and initialize with  empty object and add localization in attached function with async function.

datePickerRangeArray: {
    type: Array,
    value: {}
  }

attached: function(){
   this.async(function(){
     datePickerRangeArray = [
        {"key": "!h8", "val": this.localize('last8hrs')},
        {"key": "!h12", "val": this.localize('last12hrs')},
        {"key": "!h24", "val": this.localize('last24hrs')},
        {"key": "!h168", "val": this.localize('last48hrs')},
        {"key": "current-day", "val": this.localize('CurrentDay')},
        {"key": "previous-day", "val": this.localize('PreviousDay')}];
    },10);
}


问:
How do I get the total Json record count using JQuery?
I couldn't find anything about getting the total JSON record count using jQuery.

Here is the JSON returned:

{"Email":"Please enter your Email.","Password":"Please enter a password."}

Here is my code:

```<code>$(function() {
    $("#btnSubmit").click(function() {
        $.ajax({
            url: "/account/signup",
            type: "POST",
            dataType: "json",
            data: {
                Email: $("#strEmail").val(),
                Password: $("#strPassword").val()
            },
            success: function(j) {
                    $(".errMsg").hide();
                    alert(j.length); // I couldn't get the total count
                $.each(j, function(n) {
                    $("#err" + n).html(j[n]);
                    $("#err" + n).show();
                })

            },
            error: function(req, status, error) {
                alert(req);
            }
        });
    });
});
</code>```

答:
The OP is trying to count the number of properties in a JSON object. This could be done with an incremented temp variable in the iterator, but he seems to want to know the count before the iteration begins. A simple function that meets the need is provided at the bottom of this page.

Here's a cut and paste of the code, which worked for me:

```<code>function countProperties(obj) {
  var prop;
  var propCount = 0;

  for (prop in obj) {
    propCount++;
  }
  return propCount;
}
</code>```

This should work well for a JSON object. For other objects, which may derive properties from their prototype chain, you would need to add a hasOwnProperty() test.

Body:
I couldn't find anything about getting the total JSON record count using jQuery.

Here is the JSON returned:

{"Email":"Please enter your Email.","Password":"Please enter a password."}

Here is my code:

$(function() {
    $("#btnSubmit").click(function() {
        $.ajax({
            url: "/account/signup",
            type: "POST",
            dataType: "json",
            data: {
                Email: $("#strEmail").val(),
                Password: $("#strPassword").val()
            },
            success: function(j) {
                    $(".errMsg").hide();
                    alert(j.length); // I couldn't get the total count
                $.each(j, function(n) {
                    $("#err" + n).html(j[n]);
                    $("#err" + n).show();
                })

            },
            error: function(req, status, error) {
                alert(req);
            }
        });
    });
});

Body:
The OP is trying to count the number of properties in a JSON object. This could be done with an incremented temp variable in the iterator, but he seems to want to know the count before the iteration begins. A simple function that meets the need is provided at the bottom of this page.

Here's a cut and paste of the code, which worked for me:

function countProperties(obj) {
  var prop;
  var propCount = 0;

  for (prop in obj) {
    propCount++;
  }
  return propCount;
}

This should work well for a JSON object. For other objects, which may derive properties from their prototype chain, you would need to add a hasOwnProperty() test.


问:
Mysql real escape string not working for textarea apostrophe on insert getting syntax error
Whenever I'm trying to insert data that has an apostrophe in it, I receive a

mysql syntax error

Example text in textarea : I'm an alien will throw a syntax error when I try to insert in the database. I'm using real_escape_string and still is not working.

query snippet

```<code>$text=mysqli_real_escape_string($db,stripslashes(strip_tags(trim($_POST['text']))));
</code>```

markup

```<code><textarea name='text' placeholder="Type your message here... " value=''></textarea>
</code>```

答:
Just use parameterized queries. Then you don't have to do any escaping, and apostrophes will never be a problem.

It's really easy:

```<code>$text=trim($_POST['text']);

$stmt = $pdo->prepare("UPDATE table SET text=? WHERE user=?");
$stmt->execute([$text, $id]);
</code>```

Using stripslashes() and striptags() should be unnecessary, too.

You can also do prepared statements with parameters with Mysqli. But you should use PDO.

Body:
Whenever I'm trying to insert data that has an apostrophe in it, I receive a

mysql syntax error

Example text in textarea : I'm an alien will throw a syntax error when I try to insert in the database. I'm using real_escape_string and still is not working.

query snippet

$text=mysqli_real_escape_string($db,stripslashes(strip_tags(trim($_POST['text']))));

markup

<textarea name='text' placeholder="Type your message here... " value=''></textarea>

Body:
Just use parameterized queries. Then you don't have to do any escaping, and apostrophes will never be a problem.

It's really easy:

$text=trim($_POST['text']);

$stmt = $pdo->prepare("UPDATE table SET text=? WHERE user=?");
$stmt->execute([$text, $id]);

Using stripslashes() and striptags() should be unnecessary, too.

You can also do prepared statements with parameters with Mysqli. But you should use PDO.


问:
Get first item of every sublist of list in Python
I have the following string which is a list of lists:

```<code>"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]
</code>```

I want to grab all the first values of each list into a variable, so the output should be in this case

```<code>print variable
</code>```

expected output:

```<code>310.5
310.0
310.0
309.5
</code>```

答:
This code will iterate over every first element and append it to the out list for ease of access in the future.

```<code>dict_ = {"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]}
out=[]

for item in dict_["ID"]:
    out.append(item[0])
print(out)
</code>```

This will output [310.5, 310.0, 310.0, 309.5]. Is this what you needed?

Body:
I have the following string which is a list of lists:

"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]

I want to grab all the first values of each list into a variable, so the output should be in this case

print variable

expected output:

310.5
310.0
310.0
309.5

Body:
This code will iterate over every first element and append it to the out list for ease of access in the future.

dict_ = {"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]}
out=[]

for item in dict_["ID"]:
    out.append(item[0])
print(out)

This will output [310.5, 310.0, 310.0, 309.5]. Is this what you needed?


问:
angular display ng-repeat only after clicking a button
I have a controller that runs with the page load. I would like to change it, so only after clicking a button the function will called and the results will be displayed.

HTML:

```<code><div ng-controller="MyController">Files on server: {{ mydata }}
</div>

<ul ng-controller="MyController as controller">
    <li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
</code>```

JS:

```<code>app.controller('MyController', function($http) {
var vm = this;
vm.mydata = [];

$http.get('list')
    .then(function(result) {
      console.log(result);
      vm.mydata = result.data;
     });
});
</code>```

答:
You could simply toggle the visibility. That way you can load the data upfront and show it when you want to.

```<code><ul ng-if="!controller.hide">
    <li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>

<button ng-click="controller.hide=false">Show Me!</button>
</code>```

I removed the ng-controller directive from your ul. I would put that on a higher level element that wraps all of the other elements.

Body:
I have a controller that runs with the page load. I would like to change it, so only after clicking a button the function will called and the results will be displayed.

HTML:

Files on server: {{ mydata }}

{{ data }}

JS:

app.controller('MyController', function($http) {
var vm = this;
vm.mydata = [];

$http.get('list')
    .then(function(result) {
      console.log(result);
      vm.mydata = result.data;
     });
});

Body:
You could simply toggle the visibility. That way you can load the data upfront and show it when you want to.

<ul ng-if="!controller.hide">
    <li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>

<button ng-click="controller.hide=false">Show Me!</button>

I removed the ng-controller directive from your ul. I would put that on a higher level element that wraps all of the other elements.