问:
How to select characters that are present in multiple columns of data
I am trying to select all the characters in this data set to make a data frame of only the character shared in common between the three columns

I tried using duplicated() from dyplr but that will only select duplicates from 2 of the columns.

```<code>#  UT          MT              HT
ABHD17C       ABCG1       AC005884.1
ABHD4         ABHD17C      AC009234.1
ABO           ABO         AC011933.1
AC009234.1    AC009234.1   AC097724.3
ACSL3        AC025627.9    ABO
ACSL5        AC097724.3    ACTA2
ACSS1        ACP5         ADAMTS15
ACTBP12      ACSS1        ADAMTS20
ACTG1        ACSL5        ADH7
ACTG1P12     ACSS1        AKR1C1
ACTN4        ACTA2        AKR1C2
ADAM19       ADAMTS15     AKR1C4
ADAMTS15     ADAMTS20     ALDH1L2
ADCK3        ADH7         ALDH3A1
</code>```

In this example, the columns should only share "ABO", but in my more extensive data set characters are selected that are not in all three columns

答:
Actually,   your data also has both "AC009234.1" and "ADAMTS15" in all three columns. </p>

```<code>intersect(df$UT, intersect(df$MT, df$HT))
[1] "ABO"        "AC009234.1" "ADAMTS15"
</code>```

Body:
I am trying to select all the characters in this data set to make a data frame of only the character shared in common between the three columns

I tried using duplicated() from dyplr but that will only select duplicates from 2 of the columns.

#  UT          MT              HT
ABHD17C       ABCG1       AC005884.1
ABHD4         ABHD17C      AC009234.1
ABO           ABO         AC011933.1
AC009234.1    AC009234.1   AC097724.3
ACSL3        AC025627.9    ABO
ACSL5        AC097724.3    ACTA2
ACSS1        ACP5         ADAMTS15
ACTBP12      ACSS1        ADAMTS20
ACTG1        ACSL5        ADH7
ACTG1P12     ACSS1        AKR1C1
ACTN4        ACTA2        AKR1C2
ADAM19       ADAMTS15     AKR1C4
ADAMTS15     ADAMTS20     ALDH1L2
ADCK3        ADH7         ALDH3A1

In this example, the columns should only share "ABO", but in my more extensive data set characters are selected that are not in all three columns

Body:
Actually,   your data also has both "AC009234.1" and "ADAMTS15" in all three columns.

intersect(df$UT, intersect(df$MT, df$HT))
[1] "ABO"        "AC009234.1" "ADAMTS15"


来源: stackexchange

问:
Rename a directory and its sub-directory with a one liner in Bash
I have a android app that i decompiled and im writing a script to rename directories.

Inside the decompiled folder is a path:

```<code>smali/com/FOLDER/SUB-FOLDER
</code>```

I want to rename the EXISTING folders to:

```<code>smali/com/NEW-NAME/SUB-NEW-NAME
</code>```

I was thinking i could use the mv command but digging through the man page it looks like it cant be done. I was trying this:

```<code>mv smali/com/FOLDER smali/com/FOLDER/SUB-FOLDER -t smali/com/NEW-NAME/SUB-NEW-NAME
</code>```

This only works for moving multiple files to a single destination.

EDIT:

Exisiting folders:

```<code>  smali/com/FOLDER/SUB-FOLDER
</code>```

I am trying to rename both folders while keeping the contents of each folder.

A example of renaming each folder one by one would be:

```<code>mv smali/com/FOLDER/ smali/com/NEW-NAME
mv smali/com/NEW-NAME/SUB-FOLDER smali/com/NEW-NAME/SUB-NEW-NAME
</code>```

答:
This is an entirely trivial one-liner; for example:

```<code>rename_pieces smali/com/FOLDER/SUB-FOLDER smali/com/NEW/SUBNEW
</code>```

...assuming, of course, that you run an appropriate function definition first. If you only want to rename SUB-FOLDER, after creating NEW-NAME should it not exist, that would look like:

```<code>rename_pieces() {
  local old=$1 new=$2
  [[ $new = */* ]] && mkdir -p -- "${new%/*}"
  mv -T -- "$old" "$new"
}
</code>```

...and this is much more likely to be the behavior you really do want than any other interpretation, insofar as it leaves contents of FOLDER other than SUB-FOLDER alone with its original name.

By contrast, if you really want to rename both directories, that gets a lot more interesting. If we have a guarantee that both source and destination are at the same depth, this might look something like:

```<code>log_or_run() {
  if [[ $log_only ]]; then   # just log what we would run
    printf '%q ' "$@" >&2    # use printf %q to generate a safely-escaped version
    printf '\n' >&2          # ...and terminate with a newline.
  else
    "$@"                     # actually run the command
  fi
}
rename_pieces() {
  local old=$1 new=$2 common
  while [[ ${old%%/*} = "${new%%/*}" ]]; do
    common+=/"${old%%/*}"
    old=${old#*/}; new=${new#*/}
  done
  while [[ $old && $new ]]; do
    log_or_run mv -T -- "${common#/}/${old%%/*}" "${common#/}/${new%%/*}"; echo
    common+=/"${new%%/*}"
    [[ $old = */* && $new = */* ]] || return
    old=${old#*/}; new=${new#*/}
  done
}
</code>```

Whereafter:

```<code>log_only=1 rename_pieces smali/com/FOLDER/SUB-FOLDER smali/com/NEW/SUBNEW
</code>```

...emits on output:

```<code>mv -T -- smali/com/FOLDER smali/com/NEW
mv -T -- smali/com/NEW/SUB-FOLDER smali/com/NEW/SUBNEW
</code>```

...and doing likewise without log_only=1 actually runs those commands.

ContentLicense: CC BY-SA 4.0

Body:
I have a android app that i decompiled and im writing a script to rename directories.

Inside the decompiled folder is a path:

smali/com/FOLDER/SUB-FOLDER

I want to rename the EXISTING folders to:

smali/com/NEW-NAME/SUB-NEW-NAME

I was thinking i could use the mv command but digging through the man page it looks like it cant be done. I was trying this:

mv smali/com/FOLDER smali/com/FOLDER/SUB-FOLDER -t smali/com/NEW-NAME/SUB-NEW-NAME

This only works for moving multiple files to a single destination.

EDIT:

Exisiting folders:

  smali/com/FOLDER/SUB-FOLDER

I am trying to rename both folders while keeping the contents of each folder.

A example of renaming each folder one by one would be:

mv smali/com/FOLDER/ smali/com/NEW-NAME
mv smali/com/NEW-NAME/SUB-FOLDER smali/com/NEW-NAME/SUB-NEW-NAME

Body:
This is an entirely trivial one-liner; for example:

rename_pieces smali/com/FOLDER/SUB-FOLDER smali/com/NEW/SUBNEW

...assuming, of course, that you run an appropriate function definition first. If you only want to rename SUB-FOLDER, after creating NEW-NAME should it not exist, that would look like:

rename_pieces() {
  local old=$1 new=$2
  [[ $new = */* ]] && mkdir -p -- "${new%/*}"
  mv -T -- "$old" "$new"
}

...and this is much more likely to be the behavior you really do want than any other interpretation, insofar as it leaves contents of FOLDER other than SUB-FOLDER alone with its original name.

By contrast, if you really want to rename both directories, that gets a lot more interesting. If we have a guarantee that both source and destination are at the same depth, this might look something like:

log_or_run() {
  if [[ $log_only ]]; then   # just log what we would run
    printf '%q ' "$@" >&2    # use printf %q to generate a safely-escaped version
    printf '\n' >&2          # ...and terminate with a newline.
  else
    "$@"                     # actually run the command
  fi
}
rename_pieces() {
  local old=$1 new=$2 common
  while [[ ${old%%/*} = "${new%%/*}" ]]; do
    common+=/"${old%%/*}"
    old=${old#*/}; new=${new#*/}
  done
  while [[ $old && $new ]]; do
    log_or_run mv -T -- "${common#/}/${old%%/*}" "${common#/}/${new%%/*}"; echo
    common+=/"${new%%/*}"
    [[ $old = */* && $new = */* ]] || return
    old=${old#*/}; new=${new#*/}
  done
}

Whereafter:

log_only=1 rename_pieces smali/com/FOLDER/SUB-FOLDER smali/com/NEW/SUBNEW

...emits on output:

mv -T -- smali/com/FOLDER smali/com/NEW
mv -T -- smali/com/NEW/SUB-FOLDER smali/com/NEW/SUBNEW

...and doing likewise without log_only=1 actually runs those commands.


问:
Converting Negative Number in String Format to Numeric when Sign as at the end
I have certain numbers within a column of my dataframe that have negative numbers in a string format like this: "500.00-" I need to convert every negative number within the column to numeric format. I'm sure there's an easy way to do this, but I have struggled finding one specific to pandas dataframe. Any help would be greatly appreciated.   </p>

<p>I have tried the basic to_numeric function as shown below, but it doesn't read it in correctly. Also, only some of the numbers within the column are negative, therefore I can't simply remove all the negative signs and multiply the column by 1. </p>

```<code>Q1['Credit'] = pd.to_numeric(Q1['Credit'])
</code>```

答:
Possibly a bit explicit but would work</p>

```<code># build a mask of negative numbers
m_neg = Q1["Credit"].str.endswith("-")
# remove - signs
Q1["Credit"] = Q1["Credit"].str.rstrip("-")
# convert to number
Q1["Credit"] = pd.to_numeric(Q1["Credit"])
# Apply the mask to create the negatives
Q1.loc[m_neg, "Credit"] *= -1
</code>```

Body:
I have certain numbers within a column of my dataframe that have negative numbers in a string format like this: "500.00-" I need to convert every negative number within the column to numeric format. I'm sure there's an easy way to do this, but I have struggled finding one specific to pandas dataframe. Any help would be greatly appreciated.

I have tried the basic to_numeric function as shown below, but it doesn't read it in correctly. Also, only some of the numbers within the column are negative, therefore I can't simply remove all the negative signs and multiply the column by 1.

Q1['Credit'] = pd.to_numeric(Q1['Credit'])

Body:
Possibly a bit explicit but would work

# build a mask of negative numbers
m_neg = Q1["Credit"].str.endswith("-")
# remove - signs
Q1["Credit"] = Q1["Credit"].str.rstrip("-")
# convert to number
Q1["Credit"] = pd.to_numeric(Q1["Credit"])
# Apply the mask to create the negatives
Q1.loc[m_neg, "Credit"] *= -1


问:
How to select multiple pattern from dataset in R
I have a dataset (data) with list of email ids:

```<code>email=c("susgho.agency@gmail.com","suagencyter.m@gmail.com",
        "duff.abcnkhgt@gmail.com","ftyhabcdfg@gmail.com",
        "gjhfhg1-ail.com","gjhgkjhgbrt.gh@aol.com")
</code>```

I have another dataset - (disp) with list of pattern:

```<code>pattern=c(".agency",".abc","1-ail.com"))
</code>```

I want to see if the pattern matches with the emails.
the expected output should be as follows:

```<code>email                         pattern
susgho.agency@gmail.com       .agency
suagencyter.m@gmail.com
duff.abcnkhgt@gmail.com       .abc
ftyhabcdfg@gmail.com
gjhfhg1-ail.com               1-ail.com
gjhgkjhgbrt.gh@aol.com
</code>```

I am using for loop but it is taking forever to execute.

```<code>w <- NULL
for(i in 1:nrow(disp))
{
  w1 <- as.character(disp[i,1])
  w2 <- data[grep(w1, data$email),]
  if(nrow(w2) > 0)
  {
    w2$pattern <- w1
    w <- rbind(w, w2)
  }
  else
    w <- rbind(w, w2)
}
</code>```

Any help would e highly appreciated. tia!

答:
Slightly different approach using stringr::str_match, though you need to escape the special characters in the pattern strings first, by adding the double-backslash prefix:

```<code>email=c("susgho.agency@gmail.com","suagencyter.m@gmail.com",
        "duff.abcnkhgt@gmail.com","ftyhabcdfg@gmail.com",
        "gjhfhg1-ail.com","gjhgkjhgbrt.gh@aol.com")

pattern=c("\\.agency","\\.abc","1\\-ail.com")

data.frame(email, pattern = stringr::str_match(email, paste(pattern, collapse = "|")))
</code>```

This produces the following output:

```<code>                    email   pattern
1 susgho.agency@gmail.com   .agency
2 suagencyter.m@gmail.com      <NA>
3 duff.abcnkhgt@gmail.com      .abc
4    ftyhabcdfg@gmail.com      <NA>
5         gjhfhg1-ail.com 1-ail.com
6  gjhgkjhgbrt.gh@aol.com      <NA>
</code>```

Body:
I have a dataset (data) with list of email ids:

email=c("susgho.agency@gmail.com","suagencyter.m@gmail.com",
        "duff.abcnkhgt@gmail.com","ftyhabcdfg@gmail.com",
        "gjhfhg1-ail.com","gjhgkjhgbrt.gh@aol.com")

I have another dataset - (disp) with list of pattern:

pattern=c(".agency",".abc","1-ail.com"))

I want to see if the pattern matches with the emails.
the expected output should be as follows:

email                         pattern
susgho.agency@gmail.com       .agency
suagencyter.m@gmail.com
duff.abcnkhgt@gmail.com       .abc
ftyhabcdfg@gmail.com
gjhfhg1-ail.com               1-ail.com
gjhgkjhgbrt.gh@aol.com

I am using for loop but it is taking forever to execute.

w <- NULL
for(i in 1:nrow(disp))
{
  w1 <- as.character(disp[i,1])
  w2 <- data[grep(w1, data$email),]
  if(nrow(w2) > 0)
  {
    w2$pattern <- w1
    w <- rbind(w, w2)
  }
  else
    w <- rbind(w, w2)
}

Any help would e highly appreciated. tia!

Body:
Slightly different approach using stringr::str_match, though you need to escape the special characters in the pattern strings first, by adding the double-backslash prefix:

email=c("susgho.agency@gmail.com","suagencyter.m@gmail.com",
        "duff.abcnkhgt@gmail.com","ftyhabcdfg@gmail.com",
        "gjhfhg1-ail.com","gjhgkjhgbrt.gh@aol.com")

pattern=c("\\.agency","\\.abc","1\\-ail.com")

data.frame(email, pattern = stringr::str_match(email, paste(pattern, collapse = "|")))

This produces the following output:

                    email   pattern
1 susgho.agency@gmail.com   .agency
2 suagencyter.m@gmail.com      <NA>
3 duff.abcnkhgt@gmail.com      .abc
4    ftyhabcdfg@gmail.com      <NA>
5         gjhfhg1-ail.com 1-ail.com
6  gjhgkjhgbrt.gh@aol.com      <NA>


问:
Return SAFEARRAY of custom interface types to VB6 through COM
Is it possible to return an array of defined interface objects from a C++ COM function (VC6) to a VB6 client? I've scoured the web and haven't been able to come across anything that describes what I need to do. I've seen a lot of passing BSTR and VARIANT types, but I need some way to actually have the client side utilise the interface type that I return inside the array.

What I assume I'll need to do

 - Use a SAFEARRAY

 - Use the SAFEARRAY with the VT_UNKNOWN type, which in turns means I need to place the objects into the array as IUnknown objects.

From here on in I'm stumped. Is it possible to interpret an IUnknown type in VB6, and somehow turn it into the type that I require? Or am I going about this in the complete wrong way...

Clarification:

The interfaces being placed in the collection are being used to mimic a struct. I essentially need to pass back an array of structs.

答:
VB will do a QueryInterface behind the scenes when you assign the IUnknown to a particular interface type, so that should Just Work.

I don't know if you can pass an array of user-defined type to VB6, all the documentaiton I can find on the web stops at VS2003, but I would expect it would be possible.

ContentLicense: CC BY-SA 3.0


问:
HTML Text That Transitions from Bottom to Top
I am now trying to create an HTML div that transitions upward when text is added to its inner HTML. I do not know how to properly explain what I want, but I will try.

Say you were using a code editor with a live preview that updates constantly, and you had typed in something like this

 and then you changed that code to
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut.
, and after you've changed that code the preview updated like this:

That is what I want text that transitions upward like the image above.

Here is another example of text transitioning from bottom to top instead of the default appear out of nowhere.

Hope you've understood this, thanks in advance.

Here is my code live.

答: TRY USING [div:empty{transition: (all) 970ms ease-in-out}] and see if it works</p>


问:
slicing a list as if it has the behavior of a ring buffer
To create a slicing function that has the lower and upper index and the size of the list as parameters so that when slicing the list given those parameters, it behaves like a gather function.

I've tried to define it using the filter concept and provide it with the testing function. Please see my code below

```<code>Require Import PeanoNat.
Require Import Coq.Init.Datatypes.
Require Import Notations.
Import Basics.

Fixpoint filter_index {X: Type} (currInd : nat) (test: nat -> bool) (l: list X ): list X :=
  match l with
  | [] => []
  | h::t =>  if test currInd then h :: filter_index (S currInd) test t else filter_index (S currInd) test t
  end.

Definition slicing_ring (tail head sz: nat) : nat -> bool :=
  fun n => if sz <=? head then orb ( n <=? head mod sz) ( tail <=? n) else andb ( tail <=? n) (n <=? head).

Example test1 : filter_index 0 (slicing_ring 3 5 4) [6;9;3;4] = [4;6;9].
</code>```

So in the above example, I expect to have the result list. However, if I do Compute filter_index 0 (slicing_ring 2 3 4) [6;9;3;4]. it gave me [6;9;4].

答:
Your filter_index function is never going to change the order of the elements of the list. The elements are tested in order and then conditionally inserted into the output in order.

A better approach might be based on indexed access.

```<code>Fixpoint get_index {X: Type} (ls: list X) (index: nat): option X :=
  match ls, index with
  | [], _ => None
  | x :: _, 0 => Some x
  | x :: tl, S index' => get_index tl index'
  end.
</code>```

(this is essentially nth_error from the standard library — there are variants for other kinds of access).

If you can enumerate the indices for your ring buffer slice in the desired order, this should work fine.

Body:
To create a slicing function that has the lower and upper index and the size of the list as parameters so that when slicing the list given those parameters, it behaves like a gather function.

I've tried to define it using the filter concept and provide it with the testing function. Please see my code below

Require Import PeanoNat.
Require Import Coq.Init.Datatypes.
Require Import Notations.
Import Basics.

Fixpoint filter_index {X: Type} (currInd : nat) (test: nat -> bool) (l: list X ): list X :=
  match l with
  | [] => []
  | h::t =>  if test currInd then h :: filter_index (S currInd) test t else filter_index (S currInd) test t
  end.

Definition slicing_ring (tail head sz: nat) : nat -> bool :=
  fun n => if sz <=? head then orb ( n <=? head mod sz) ( tail <=? n) else andb ( tail <=? n) (n <=? head).

Example test1 : filter_index 0 (slicing_ring 3 5 4) [6;9;3;4] = [4;6;9].

So in the above example, I expect to have the result list. However, if I do Compute filter_index 0 (slicing_ring 2 3 4) [6;9;3;4]. it gave me [6;9;4].

Body:
Your filter_index function is never going to change the order of the elements of the list. The elements are tested in order and then conditionally inserted into the output in order.

A better approach might be based on indexed access.

Fixpoint get_index {X: Type} (ls: list X) (index: nat): option X :=
  match ls, index with
  | [], _ => None
  | x :: _, 0 => Some x
  | x :: tl, S index' => get_index tl index'
  end.

(this is essentially nth_error from the standard library — there are variants for other kinds of access).

If you can enumerate the indices for your ring buffer slice in the desired order, this should work fine.


问:
Variables for multiple parameters in R functions
I'd like to use a variable (xdata) to define, which data to display with the vioplot function. Tried the below ways but unfortunately, they do not work. How can I achieve this?</p>

```<code>library(vioplot)
x1 = mtcars$mpg[mtcars$cyl==4]
x2 = mtcars$mpg[mtcars$cyl==6]
x3 = mtcars$mpg[mtcars$cyl==8]
xdata = paste("x1","x2","x3",sep=",") # Try 1
xdata = c("x1","x2","x3")             # Try 2
vioplot(xdata, names=c("4 cyl", "6 cyl", "8 cyl"),col="grey")
</code>```

答:
I came to this question trying to figure out how to save a configuration of parameters that you would have passed into a function, and pass them on demand in a different line. The question and top answer weren't initially clear to me, so I have a simple demonstration for those just starting to learn R.

Let's say for example that you have the function substr that takes parameters x, start, and stop.

Instead of calling substr("Hello World", 2, 5) to get "ello", we can save the parameters into a list and call the function with the parameters using do.call:

```<code>params <- list("Hello World", 2, 5)
do.call(substr, params)
>> "ello"
</code>```

If you only want to save start and stop, you can prepend the first argument with the combine function c:

```<code>params <- list(2, 5)
do.call(substr, c("Hello World", params))
>> "ello"
</code>```

You can also add named arguments to the list the same way you specify parameters in a function call:

```<code>params <- list(stop=5, x="Hello World", start=2)
do.call(substr, params)
>> "ello"
</code>```

And the list can mix named and non-named parameters:

```<code>params <- list("Hello World", start=2, stop=5)
do.call(substr, params)
>> "ello"
</code>```

If you need more complex logic, you can also wrap your call in a factory function:

```<code>make_substr <- function(start, stop){
  return(
    function(string) {
      substr(string, start, stop)
    }
  )
}
substr_2_5 <- make_substr(2, 5)

substr_2_5("Hello World")
>> "ello"
substr_2_5("Goodbye")
>> "oodb"
</code>```

Body:
I'd like to use a variable (xdata) to define, which data to display with the vioplot function. Tried the below ways but unfortunately, they do not work. How can I achieve this?

library(vioplot)
x1 = mtcars$mpg[mtcars$cyl==4]
x2 = mtcars$mpg[mtcars$cyl==6]
x3 = mtcars$mpg[mtcars$cyl==8]
xdata = paste("x1","x2","x3",sep=",") # Try 1
xdata = c("x1","x2","x3")             # Try 2
vioplot(xdata, names=c("4 cyl", "6 cyl", "8 cyl"),col="grey")

Body:
I came to this question trying to figure out how to save a configuration of parameters that you would have passed into a function, and pass them on demand in a different line. The question and top answer weren't initially clear to me, so I have a simple demonstration for those just starting to learn R.

Let's say for example that you have the function substr that takes parameters x, start, and stop.

Instead of calling substr("Hello World", 2, 5) to get "ello", we can save the parameters into a list and call the function with the parameters using do.call:

params <- list("Hello World", 2, 5)
do.call(substr, params)
>> "ello"

If you only want to save start and stop, you can prepend the first argument with the combine function c:

params <- list(2, 5)
do.call(substr, c("Hello World", params))
>> "ello"

You can also add named arguments to the list the same way you specify parameters in a function call:

params <- list(stop=5, x="Hello World", start=2)
do.call(substr, params)
>> "ello"

And the list can mix named and non-named parameters:

params <- list("Hello World", start=2, stop=5)
do.call(substr, params)
>> "ello"

If you need more complex logic, you can also wrap your call in a factory function:

make_substr <- function(start, stop){
  return(
    function(string) {
      substr(string, start, stop)
    }
  )
}
substr_2_5 <- make_substr(2, 5)

substr_2_5("Hello World")
>> "ello"
substr_2_5("Goodbye")
>> "oodb"


问:
How to repetitively update a portion of GUI after show.dialog()?
I have a list of statuses that will need to be checked every 5 seconds, then update a panel in my gui. With my current code, I have a Timeout set to an hour and a while loop that will run the Show-Statuses function which updates the GUI.

My issue is that when this While loop is entered, the Form.ShowDialog() will never bet triggered.

How do I make it so I can show the form and the continuously update a portion of it?

```<code>Function Determine-JabadStatus {

    $JabadLOStatus = (Get-Aduser adepolo -Properties LockedOut).LockedOut

    If ($JabadLOStatus -eq $False) {
        $JabadStatusF = "Unlocked"
    } else {
        $JabadStatusF = "Locked"
    }

    $JabadStatusF
}

Function Show-Statuses {

    #Load statuses
    $JabadStatus = Determine-JabadStatus

    #Add each status seperated by + "`r`n`r`n" + quotes
    $ImportantInformationStatuses.Text = $JabadStatus
}

$Timeout = New-TimeSpan -Hours 1
$sw = [diagnostics.stopwatch]::StartNew()

While ($sw.Elapsed -lt $Timeout) {
    Show-Statuses
    Start-Sleep -Seconds 5
}

$form.ShowDialog()
</code>```

答:
Assuming your $ImportantInformationStatuses is a label or something similar, then a .Refresh() should work.

```<code>Function Show-Statuses{
    #Load statuses
    $JabadStatus = Determine-JabadStatus

    #Add each status seperated by + "`r`n`r`n" + quotes
    $ImportantInformationStatuses.Text = $JabadStatus
    $ImportantInformationStatuses.Refresh()
}
</code>```

I would recommend looking into jobs though using the windows forms timer to trigger your loop, something like this.

```<code>$JobScript = {
    If((get-aduser adepolo -Properties LockedOut).LockedOut) {
        $JabadStatusF = "Locked"
    } Else {
        $JabadStatusF = "Unlocked"
    }
    Return $JabadStatusF
}

Function JobLoop {
    $Job = Start-Job -ScriptBlock $JobScript
    $Status = (Receive-job $job -Wait)
    $ImportantInformationStatuses.Text = $Status
}

$Timer = New-Object System.Windows.Forms.Timer
$Timer.Interval = 5000
$Timer.add_tick({JobLoop})
$Timer.Start() # Do $Timer.Stop() & $Timer.Dispose() to stop the loop.
</code>```

Maybe add the .Start() to a button and the .Stop() .Dispose() to another button. Or the same button in a toggle.

Body:
I have a list of statuses that will need to be checked every 5 seconds, then update a panel in my gui. With my current code, I have a Timeout set to an hour and a while loop that will run the Show-Statuses function which updates the GUI.

My issue is that when this While loop is entered, the Form.ShowDialog() will never bet triggered.

How do I make it so I can show the form and the continuously update a portion of it?

Function Determine-JabadStatus {

    $JabadLOStatus = (Get-Aduser adepolo -Properties LockedOut).LockedOut

    If ($JabadLOStatus -eq $False) {
        $JabadStatusF = "Unlocked"
    } else {
        $JabadStatusF = "Locked"
    }

    $JabadStatusF
}

Function Show-Statuses {

    #Load statuses
    $JabadStatus = Determine-JabadStatus

    #Add each status seperated by + "`r`n`r`n" + quotes
    $ImportantInformationStatuses.Text = $JabadStatus
}

$Timeout = New-TimeSpan -Hours 1
$sw = [diagnostics.stopwatch]::StartNew()

While ($sw.Elapsed -lt $Timeout) {
    Show-Statuses
    Start-Sleep -Seconds 5
}

$form.ShowDialog()

Body:
Assuming your $ImportantInformationStatuses is a label or something similar, then a .Refresh() should work.

Function Show-Statuses{
    #Load statuses
    $JabadStatus = Determine-JabadStatus

    #Add each status seperated by + "`r`n`r`n" + quotes
    $ImportantInformationStatuses.Text = $JabadStatus
    $ImportantInformationStatuses.Refresh()
}

I would recommend looking into jobs though using the windows forms timer to trigger your loop, something like this.

$JobScript = {
    If((get-aduser adepolo -Properties LockedOut).LockedOut) {
        $JabadStatusF = "Locked"
    } Else {
        $JabadStatusF = "Unlocked"
    }
    Return $JabadStatusF
}

Function JobLoop {
    $Job = Start-Job -ScriptBlock $JobScript
    $Status = (Receive-job $job -Wait)
    $ImportantInformationStatuses.Text = $Status
}

$Timer = New-Object System.Windows.Forms.Timer
$Timer.Interval = 5000
$Timer.add_tick({JobLoop})
$Timer.Start() # Do $Timer.Stop() & $Timer.Dispose() to stop the loop.

Maybe add the .Start() to a button and the .Stop() .Dispose() to another button. Or the same button in a toggle.


问:
How to check for undefined when using find on an javascript array
In my array I am using .find to find an object and set its property to some value.
  I want to set the name only if there is a value. i.e; check for undefined
  Below is my array, am using .find to find the object and set its name.
  I want to set only if the object with id === checkid is found.</p>

```<code> this.myarray.find(colDef => colDef.id === checkid).name = newname;.
</code>```

答:
You can do this in one statement with Object.assign like this:

let myArray = [{id: 1, name: 'Boris'}, {id: 2}]

// id 3 does not exist no changes would be made to myArray
Object.assign(myArray.find(x => x.id == 3) || {}, {name: 'Foo'})

// id 1 is there so name would be changed to 'john'
Object.assign(myArray.find(x => x.id == 1) || {}, {name: 'john'})

console.log(myArray)```
</div>
</div>
</p>

<p>The idea is to provide <code>Object.assign</code> with an <code>object literal</code> if <code>Array.find</code> does not find an object with the provided id.</p>

<p>The other benefit of this is that you now pass an object for the update so you can easily update more than one property at a time:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let myArray = [{id: 1, name: 'Boris'}, {id: 2}]

// id 1 is there so name would be changed to 'john'
Object.assign(myArray.find(x => x.id == 1) || {}, {name: 'john', state: 'FL'})

console.log(myArray)</code>```

Body:
In my array I am using .find to find an object and set its property to some value.
  I want to set the name only if there is a value. i.e; check for undefined
  Below is my array, am using .find to find the object and set its name.
  I want to set only if the object with id === checkid is found.

 this.myarray.find(colDef => colDef.id === checkid).name = newname;.

Body:
You can do this in one statement with Object.assign like this:

let myArray = [{id: 1, name: 'Boris'}, {id: 2}]

// id 3 does not exist no changes would be made to myArray
Object.assign(myArray.find(x => x.id == 3) || {}, {name: 'Foo'})

// id 1 is there so name would be changed to 'john'
Object.assign(myArray.find(x => x.id == 1) || {}, {name: 'john'})

console.log(myArray)

The idea is to provide Object.assign with an object literal if Array.find does not find an object with the provided id.

The other benefit of this is that you now pass an object for the update so you can easily update more than one property at a time:

let myArray = [{id: 1, name: 'Boris'}, {id: 2}]

// id 1 is there so name would be changed to 'john'
Object.assign(myArray.find(x => x.id == 1) || {}, {name: 'john', state: 'FL'})

console.log(myArray)


问:
How to define `type` for `Electron` in typescript?
When I write below code in Electron in TypeScript,

```<code>const { app, BrowserWindow } = require("electron");

let mainWindow: Electron.BrowserWindow;
</code>```

I got this error: Cannot find namespace 'Electron'..

I seems there is not namespace defined for the typeElectron. I wonder where I can load this type definition. I have added these dependencies on my project:

```<code>"electron": "^5.0.2",
</code>```

答:
No need to prefix your usage of BrowserWindow. You've already got the type imported, just use it directly.

```<code>import { BrowserWindow } from "electron";

let mainWindow: BrowserWindow;
</code>```

Additionally, you don't need a separate @types/electron package for electron. The electron package is already typed.

Body:
When I write below code in Electron in TypeScript,

const { app, BrowserWindow } = require("electron");

let mainWindow: Electron.BrowserWindow;

I got this error: Cannot find namespace 'Electron'..

I seems there is not namespace defined for the typeElectron. I wonder where I can load this type definition. I have added these dependencies on my project:

"electron": "^5.0.2",

Body:
No need to prefix your usage of BrowserWindow. You've already got the type imported, just use it directly.

import { BrowserWindow } from "electron";

let mainWindow: BrowserWindow;

Additionally, you don't need a separate @types/electron package for electron. The electron package is already typed.


问:
how can i fix this get query string?
the code

```<code><?php

$_SERVER['QUERY_STRING'];

$text = $_SERVER['QUERY_STRING'];
$var_str = var_export($text, true);
$var = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('testnew.php', $var);

echo $text;

 ?>
</code>```

what i want to do is get query-string from the url  and store it in a php file testnew.php

http://test.com/query.php?asdawdawd

note i am very beginner

edit: now the get query string part is working after @tim suggestion but it still doesn't write the query-string to the file

答:
the working code

```<code><?php

$text = $_SERVER['QUERY_STRING'];
$file = fopen("testnew.txt","ab");
fwrite($file,$text."\n");
fclose($file);

echo $text;

 ?>
</code>```

edit : as @tim suggested i don't need  the line     $_SERVER['QUERY_STRING'];

so i removed it from the code .

edit 2 : as i asked @tim about

how can i make it type in a new line like using this
  fwrite($file,$text \n); but it doesn't work

so he gave me the working one fwrite($file,$text."\n"); and i replaced the old one from the code with it  fwrite($file,$text);

Title: how can i fix this get query string?

Body:
the code

<?php

$_SERVER['QUERY_STRING'];

$text = $_SERVER['QUERY_STRING'];
$var_str = var_export($text, true);
$var = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('testnew.php', $var);

echo $text;

 ?>

what i want to do is get query-string from the url  and store it in a php file testnew.php

http://test.com/query.php?asdawdawd

note i am very beginner

edit: now the get query string part is working after @tim suggestion but it still doesn't write the query-string to the file

Body:
the working code

<?php

$text = $_SERVER['QUERY_STRING'];
$file = fopen("testnew.txt","ab");
fwrite($file,$text."\n");
fclose($file);

echo $text;

 ?>

edit : as @tim suggested i don't need  the line     $_SERVER['QUERY_STRING'];

so i removed it from the code .

edit 2 : as i asked @tim about

how can i make it type in a new line like using this
  fwrite($file,$text \n); but it doesn't work

so he gave me the working one fwrite($file,$text."\n"); and i replaced the old one from the code with it  fwrite($file,$text);


问:
Multiple speed-dial with vuetify
I want to have multiple speed-dials in table, one for each row.
But when I open one of them, activator opens all.
In the Data object there is property 'fab' and it is initially set to false.

```<code><v-data-table
        :headers="testHeaders"
        indeterminate: false
        :items="testDesserts"
        :search="searchWord"
        :loading="loading"
        class="elevation-1 mt-1"
        hide-actions
        expand
        item-key="id_doc"
        no-data-text="Нема доступних података..."
      >
        <template slot="items" slot-scope="props">
          <tr @click="props.expanded = !props.expanded;"
            style="cursor: pointer;">
          <td>{{ props.item.receiver_full_name }}</td>
          <td>{{ props.item.id_doc }}</td>
          <td>{{ props.item.note }}</td>
          <td>

            <v-speed-dial
              v-model="fab"
              transition="scale-transition"
              fixed
              direction="left"
              open-on-hover
                    >
                  <v-btn slot="activator" fab flat small color="info">
                      <v-icon>account_circle</v-icon>
                      <v-icon>close</v-icon>
                  </v-btn>
                  <v-btn fab small flat color="info">
                      <v-icon>search</v-icon>
                  </v-btn>
                  <v-btn fab small flat color="primary">
                      <v-icon>edit</v-icon>
                  </v-btn>
                  <v-btn fab small flat color="error">
                      <v-icon>delete</v-icon>
                  </v-btn>
              </v-speed-dial>

          </td>
          <!--  -->
        </tr>
        </template>
</code>```

Please help...

答:
I solved this by changing the v-model in the v-speed-dial and v-btn to :id="xxx"

In my case, the 'idx' is the index of the v-for, but it could probably be any unique identifier.

Like this:

```<code>          <v-speed-dial
            :id="idx"
            bottom
            right
            absolute
            direction="left"
            transition="slide-x-transition"
          >
            <template v-slot:activator>
              <v-btn :id="idx" color="blue-grey" dark fab>
                <v-icon>settings</v-icon>
                <v-icon>close</v-icon>
              </v-btn>
            </template>
            <v-btn ...

            </v-btn>
          </v-speed-dial>
</code>```

Title: Multiple speed-dial with vuetify

Body:
I want to have multiple speed-dials in table, one for each row.
But when I open one of them, activator opens all.
In the Data object there is property 'fab' and it is initially set to false.

<v-data-table
        :headers="testHeaders"
        indeterminate: false
        :items="testDesserts"
        :search="searchWord"
        :loading="loading"
        class="elevation-1 mt-1"
        hide-actions
        expand
        item-key="id_doc"
        no-data-text="Нема доступних података..."
      >
        <template slot="items" slot-scope="props">

          {{ props.item.receiver_full_name }}
          {{ props.item.id_doc }}
          {{ props.item.note }}

            <v-speed-dial
              v-model="fab"
              transition="scale-transition"
              fixed
              direction="left"
              open-on-hover
                    >
                  <v-btn slot="activator" fab flat small color="info">
                      <v-icon>account_circle</v-icon>
                      <v-icon>close</v-icon>
                  </v-btn>
                  <v-btn fab small flat color="info">
                      <v-icon>search</v-icon>
                  </v-btn>
                  <v-btn fab small flat color="primary">
                      <v-icon>edit</v-icon>
                  </v-btn>
                  <v-btn fab small flat color="error">
                      <v-icon>delete</v-icon>
                  </v-btn>
              </v-speed-dial>

        </template>

Please help...

Body:
I solved this by changing the v-model in the v-speed-dial and v-btn to :id="xxx"

In my case, the 'idx' is the index of the v-for, but it could probably be any unique identifier.

Like this:

          <v-speed-dial
            :id="idx"
            bottom
            right
            absolute
            direction="left"
            transition="slide-x-transition"
          >
            <template v-slot:activator>
              <v-btn :id="idx" color="blue-grey" dark fab>
                <v-icon>settings</v-icon>
                <v-icon>close</v-icon>
              </v-btn>
            </template>
            <v-btn ...

            </v-btn>
          </v-speed-dial>


问:
Disable ListBoxItem based on the DataContext of another element in the window
I have a ListBox with a bunch of items in it. I also have another ListBox with a bunch of items in it. The two are related to each in other, in that if the user selects an item from ListBox1, a corresponding item will be created in ListBox2. If the item exists in ListBox2, I want the corresponding item in ListBox1 to be disabled, so that the user can only have one of these items in ListBox2.

I've noticed some shortfalls with Silverlight compared to WPF in that you can't use ItemContainerStyle bindings, and you can't use RelativeSources... These are exactly the two things that first came to mind when trying to do it (having a null-to-enabled converter on the relative source of the ListBox DataContext (this DataContext would hold the collection of items for ListBox2).

So for example:

ListBox1 has items:

```<code>Red
Blue
Yellow
</code>```

ListBox2 has 1 item currently:

```<code>RedCar
</code>```

I have Red corresponding to RedCar, so would want Red to be disabled in ListBox1, and have Blue and Yellow enabled.

答:
I ended up creating an event for when the user clicks on the 'add new' button. At that point an event is called that looks at what systems are in the second listbox, and then disables any of the corresponding items. I wouldn't normally like to have UI-esque code in the ViewModel, but in this particular case it's a one-off, and works rather well. Since I'm data-binding, there is really only one piece of UI code in there anyway, and that's getting the ListBoxItem to enable/disable using:

var lbi = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromItem(member);

I have a reference to the ListBox as that's the control that called the action.

ContentLicense: CC BY-SA 2.5

Body:
I have a ListBox with a bunch of items in it. I also have another ListBox with a bunch of items in it. The two are related to each in other, in that if the user selects an item from ListBox1, a corresponding item will be created in ListBox2. If the item exists in ListBox2, I want the corresponding item in ListBox1 to be disabled, so that the user can only have one of these items in ListBox2.

I've noticed some shortfalls with Silverlight compared to WPF in that you can't use ItemContainerStyle bindings, and you can't use RelativeSources... These are exactly the two things that first came to mind when trying to do it (having a null-to-enabled converter on the relative source of the ListBox DataContext (this DataContext would hold the collection of items for ListBox2).

So for example:

ListBox1 has items:

Red
Blue
Yellow

ListBox2 has 1 item currently:

RedCar

I have Red corresponding to RedCar, so would want Red to be disabled in ListBox1, and have Blue and Yellow enabled.


问:
RegEx for segmenting a string
I found this Answer for how to paras movie names with RegExp, its working fine but not exactly what i need.

The input string is : 2001.A.Space.Odyssey.1968.720p.BluRay.DD5.1.x264-LiNG.mkv

The Regular Expression that used in the answer like this  :^(.+).(\d{4}).+.(mp4|avi|mkv)$ and the output is:

```<code>2001.A.Space.Odyssey
1968
mkv
</code>```

What i need is like the below :

```<code>2001.A.Space.Odyssey
1968
LiNG
mkv
</code>```

My try was: ^(.+).(\d{4}).+([^_]).(mp4|avi|mkv)$ but the output is:

```<code>2001.A.Space.Odyssey
1968
G
mkv
</code>```

How i can get LiNG instead of G ?

答:
This expression has four capturing groups:

```<code>(.+?)\.([0-9]{4}).+?-(.+)\.(mkv|avi|mp4)
</code>```

where our desired outputs are.

The name of the movie is in the first capturing group:

```<code>(.+?)
</code>```

followed by a . and the desired year in the second group:

```<code>([0-9]{4})
</code>```

followed by everything else upto the last dash and here we are having the last word:

```<code>(.+)
</code>```

and the desired extensions are in the last capturing group:

```<code>(mkv|avi|mp4)
</code>```

DEMO

Test

const regex = /(.+?)\.([0-9]{4}).+?-(.+)\.(mkv|avi|mp4)/;
const str = `2001.A.Space.Odyssey.1968.720p.BluRay.DD5.1.x264-LiNG.mkv`;
const subst = `$1\n$2\n$3\n$4`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);```

Title: RegEx for segmenting a string

Body:
I found this Answer for how to paras movie names with RegExp, its working fine but not exactly what i need.

The input string is : 2001.A.Space.Odyssey.1968.720p.BluRay.DD5.1.x264-LiNG.mkv

The Regular Expression that used in the answer like this  :^(.+).(\d{4}).+.(mp4|avi|mkv)$ and the output is:

2001.A.Space.Odyssey
1968
mkv

What i need is like the below :

2001.A.Space.Odyssey
1968
LiNG
mkv

My try was: ^(.+).(\d{4}).+([^_]).(mp4|avi|mkv)$ but the output is:

2001.A.Space.Odyssey
1968
G
mkv

How i can get LiNG instead of G ?

Body:
This expression has four capturing groups:

(.+?)\.([0-9]{4}).+?-(.+)\.(mkv|avi|mp4)

where our desired outputs are.

The name of the movie is in the first capturing group:

(.+?)

followed by a . and the desired year in the second group:

([0-9]{4})

followed by everything else upto the last dash and here we are having the last word:

(.+)

and the desired extensions are in the last capturing group:

(mkv|avi|mp4)

DEMO

Test

const regex = /(.+?)\.([0-9]{4}).+?-(.+)\.(mkv|avi|mp4)/;
const str = `2001.A.Space.Odyssey.1968.720p.BluRay.DD5.1.x264-LiNG.mkv`;
const subst = `$1\n$2\n$3\n$4`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);


问:
How to list all installed, runnable cmdlets in powershell?
I want to list all installed, runable cmdlets and functions in powershell but Get-Command is listing cmdlets which are somehow "there" but not loaded and not runnable.

As an example, Get-Command lists New-IseSnippet:

```<code>PS W:\> get-command "*-*" -CommandType Function,Cmdlet | where name -like "New-IseSnippet" | select name,module,path

Name           Module path
----           ------ ----
New-IseSnippet ISE
</code>```

So it looks like we have a New-IseSnippet command - let's inspect it:

```<code>PS W:\> get-command New-IseSnippet
get-command : The term 'New-IseSnippet' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that
the path is correct and try again.
At line:1 char:1
+ get-command New-IseSnippet
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (New-IseSnippet:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand
</code>```

Nope,  can we run it?:

```<code>PS W:\> New-IseSnippet
New-IseSnippet : The 'New-IseSnippet' command was found in the module 'ISE', but the module could not be loaded. For more information, run 'Import-Module ISE'.
At line:1 char:1
+ New-IseSnippet
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (New-IseSnippet:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CouldNotAutoloadMatchingModule

</code>```

Nope.

How do we get only installed, runnable commands?

答:
Unfortunately, as you've discovered, PowerShell's command discovery, as surfaced by Get-Command, may also include commands that you cannot actually run in your session.

There are good reasons for that, and not so good reasons:

(a) Commands from modules that - do or may - require a different PowerShell edition are still included, the only exception being the ones on Windows in $PSHOME/Modules - modules in other directories on Windows and on Unix-like platforms all modules in $env:PSModulePath are invariably considered compatible - the PSCompatibleEdition module-manifest entry is NOT consulted as of PowerShell Core 6.2.1.

(b) As of PowerShell Core 6.2.1 / Windows PowerShell v5.1, there is NO way to restrict modules by supported platform(s) (OS)

See https://github.com/PowerShell/PowerShell/issues/5541

(c) The PowerShellHostName and PowerShellHostVersion module-manifest entries are NOT checked for compatibility during command discovery to ensure PowerShell host compatibility - only at module-import time.

(a) is a design decision (at least for now), (b) is not implemented yet, but (c) - the issue you ran into - should arguably be fixed, because it is an easy check to perform.
I encourage you to request a change at https://github.com/PowerShell/PowerShell/issues.

Generally speaking, command discovery must be limited to examining module manifests to determine compatibility; anything beyond that - trying to actually load each module - would be too time- and resource-intensive.

What adds to the confusion is that Get-Command with a literal command name reports a misleading error message as of PowerShell Core 6.2.1 / Windows PowerShell v5.1:

Unlike with a wildcard expression (e.g, *-*), a literal command name (e.g., New-IseSnippet) causes Get-Command to implicitly import the command's module, which is the ultimate tests of the command's availability in the current session - and that may fail.

Unfortunately, the way it fails misleadingly suggests that no such command is defined, whereas the real problem is the inability to import the module that contains the command.

Direct invocation of the same command more helpfully indicates that the real problem is the inability to import the module (though, arguably, it shouldn't just tell you to run Import-Module yourself in order to learn the specific reason, and instead do that for you and then report that reason).

Body:
I want to list all installed, runable cmdlets and functions in powershell but Get-Command is listing cmdlets which are somehow "there" but not loaded and not runnable.

As an example, Get-Command lists New-IseSnippet:

PS W:\> get-command "*-*" -CommandType Function,Cmdlet | where name -like "New-IseSnippet" | select name,module,path

Name           Module path
----           ------ ----
New-IseSnippet ISE

So it looks like we have a New-IseSnippet command - let's inspect it:

PS W:\> get-command New-IseSnippet
get-command : The term 'New-IseSnippet' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that
the path is correct and try again.
At line:1 char:1
+ get-command New-IseSnippet
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (New-IseSnippet:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Nope,  can we run it?:

PS W:\> New-IseSnippet
New-IseSnippet : The 'New-IseSnippet' command was found in the module 'ISE', but the module could not be loaded. For more information, run 'Import-Module ISE'.
At line:1 char:1
+ New-IseSnippet
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (New-IseSnippet:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CouldNotAutoloadMatchingModule

Nope.

How do we get only installed, runnable commands?


问:
Python, BeautifulSoup - Can't get specific element's text without its siblings as well
I'm a bit of a novice here, so please forgive my ignorance. I'm trying to get a line of code to return just on specific tag's elements. The problem is, my approaches yield these respective results...:

```<code>for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
ticker = [items.text.strip()]
print(ticker)

['Trading Symbol']
['AAPL']
['']
</code>```

and

```<code>    for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
    for td in items.find('td', {'class':['text']}):
        ticker = [td.text.strip()]
        print(ticker)

....error message....for td in items.find('td', {'class':['text']}):
    TypeError: 'NoneType' object is not iterable
</code>```

I understand why the first code does what it does-I've not specified exactly what I'm after (the stock ticker AAPL), but I don't know why adding one additional line of code specifying the class doesn't narrow the list down. By looking at the soup (which I've provided below) I figure the additional line of code would remove 'Trading Symbol' and leave 'AAPL' and '[]' but it comes up with nothing. Any help here?

Here's the soup. There are hundreds of "re" class tags so filtering using that may be helpful but it won't be the end-all.

```<code>##      <tr class="re">
##      <td class="pl " style="border-bottom: 0px;" valign="top"><a class="a" href="javascript:void(0);" onclick="top.Show.showAR( this, 'defref_dei_TradingSymbol', window );">Trading Symbol</a></td>
##      <td class="text">AAPL<span></span>
##      </td>
</code>```

答:
With bs4 4.7.1 you can use :contains along with general sibling combinator to get those tds</p>

```<code>import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.sec.gov/Archives/edgar/data/320193/0000320193-18-000070.txt')
soup = bs(r.content, 'lxml')
siblings = [item.text.strip() for item in soup.select('td:contains("Trading Symbol") ~ td')]
print(siblings)
</code>```

Body:
I'm a bit of a novice here, so please forgive my ignorance. I'm trying to get a line of code to return just on specific tag's elements. The problem is, my approaches yield these respective results...:

for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
ticker = [items.text.strip()]
print(ticker)

['Trading Symbol']
['AAPL']
['']

and

    for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
    for td in items.find('td', {'class':['text']}):
        ticker = [td.text.strip()]
        print(ticker)

....error message....for td in items.find('td', {'class':['text']}):
    TypeError: 'NoneType' object is not iterable

I understand why the first code does what it does-I've not specified exactly what I'm after (the stock ticker AAPL), but I don't know why adding one additional line of code specifying the class doesn't narrow the list down. By looking at the soup (which I've provided below) I figure the additional line of code would remove 'Trading Symbol' and leave 'AAPL' and '[]' but it comes up with nothing. Any help here?

Here's the soup. There are hundreds of "re" class tags so filtering using that may be helpful but it won't be the end-all.

##

##      Trading Symbol
##      AAPL
##

Body:
With bs4 4.7.1 you can use :contains along with general sibling combinator to get those tds

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.sec.gov/Archives/edgar/data/320193/0000320193-18-000070.txt')
soup = bs(r.content, 'lxml')
siblings = [item.text.strip() for item in soup.select('td:contains("Trading Symbol") ~ td')]
print(siblings)


问:
Efficient way to substitute repeating np.vstack in python?
I am trying to implement this post in python.

```<code>import numpy as np
x = np.array([0,0,0])
for r in range(3):
    x = np.vstack((x, np.array([-r, r, -r])))
</code>```

x gets this value

```<code>array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])
</code>```

I am concerned the runtime efficiency about the repeating np.vstack. Is there a more efficient way to do this?

答:
Would it be useful to use numpy.tile?

```<code> N = 3
 A = np.array([[0, *range(0, -N, -1)]]).T
 B = np.tile(A, (1, N))
 B[:,1] = -B[:,1]
</code>```

The first line sets the expected number of rows after the first row of zeroes.  The second creates a NumPy array by creating an initial value of 0, followed by the linear sequence of 0, -1, -2, up to -N + 1.  Note the use of the splat operator which unpacks the range object and creates elements in an individual list.  These are concatenated with the first value of 0, and we create a 2D NumPy array that is a column vector.  The third line tiles this vector N times horizontally to get the desired output.  Finally the fourth line negates the second column to get your desired output

Example Run

```<code>In [175]: N = 3

In [176]: A = np.array([[0, *range(0, -N, -1)]]).T

In [177]: B = np.tile(A, (1, N))

In [178]: B[:,1] = -B[:,1]

In [178]: B
Out[178]:
array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])
</code>```

Body:
I am trying to implement this post in python.

import numpy as np
x = np.array([0,0,0])
for r in range(3):
    x = np.vstack((x, np.array([-r, r, -r])))

x gets this value

array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])

I am concerned the runtime efficiency about the repeating np.vstack. Is there a more efficient way to do this?

Body:
Would it be useful to use numpy.tile?

 N = 3
 A = np.array([[0, *range(0, -N, -1)]]).T
 B = np.tile(A, (1, N))
 B[:,1] = -B[:,1]

The first line sets the expected number of rows after the first row of zeroes.  The second creates a NumPy array by creating an initial value of 0, followed by the linear sequence of 0, -1, -2, up to -N + 1.  Note the use of the splat operator which unpacks the range object and creates elements in an individual list.  These are concatenated with the first value of 0, and we create a 2D NumPy array that is a column vector.  The third line tiles this vector N times horizontally to get the desired output.  Finally the fourth line negates the second column to get your desired output

Example Run

In [175]: N = 3

In [176]: A = np.array([[0, *range(0, -N, -1)]]).T

In [177]: B = np.tile(A, (1, N))

In [178]: B[:,1] = -B[:,1]

In [178]: B
Out[178]:
array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])


答:
Build a list of arrays or lists, and apply np.array (or vstack) to that once:

```<code>In [598]: np.array([[-r,r,-r] for r in [0,0,1,2]])
Out[598]:
array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])
</code>```

But if the column pattern is consistent, broadcasting two arrays against each other will be faster

```<code>In [599]: np.array([-1,1,-1])*np.array([0,0,1,2])[:,None]
Out[599]:
array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])
</code>```

Title: Efficient way to substitute repeating np.vstack in python?

Body:
Build a list of arrays or lists, and apply np.array (or vstack) to that once:

In [598]: np.array([[-r,r,-r] for r in [0,0,1,2]])
Out[598]:
array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])

But if the column pattern is consistent, broadcasting two arrays against each other will be faster

In [599]: np.array([-1,1,-1])*np.array([0,0,1,2])[:,None]
Out[599]:
array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])


问:
Variation swatches are loaded 2 times
I am making a webshop, but having some trouble with the variables on a product page.
[Example page can be seen here][1]

I have installed the plugin WooCommerce Variation Swatches. On the product page I choose that the variables should be shown as buttons. But when the page loads, the page is first showing the normal WooCommerce variables and also the Variation Swatches from the plugin.

After 1 sec the 2 are merged together(see on the example page). Is it not possible to make only the swatches load?

I tried to change the site to another server, I tried to use a plugin to change the order of loading js and css, but that did not help anything.

Does anybody have a suggestion how I can solve this?

Best regards

答:
The problem is that your website is not very good optimized, it is taking a lot of time to finish loading all extra CSS and assets from all the plugins, including the WooCommerce Variation Swatches one.

And thus the CSS from the plugin that hides the native WooCommerce Swatches takes about 0.5 to 2 sec to kick in, that's why the web page makes a repaint and shows the two 'Swatches bars'.

Easy solution, add this on top of the main CSS file or as an inline style.  in your theme header.php file before a line that has wp_head(); function call:

.woo-variation-swatches-theme-child-woodmart .woo-variation-items-wrapper>.swatches-select,
.woo-variation-swatches-theme-woodmart .woo-variation-items-wrapper>.swatches-select {
  display: none;
}
```

Better and clean solution, devote sometime to improve your WordPress performance, try to use as few plugins as possible as many of them are badly coded, follow Google Page Speed advices here and also I recommend that you check and make sure you're using PHP 7+ in case you're not already.

Title: Variation swatches are loaded 2 times

Body:
The problem is that your website is not very good optimized, it is taking a lot of time to finish loading all extra CSS and assets from all the plugins, including the WooCommerce Variation Swatches one.

And thus the CSS from the plugin that hides the native WooCommerce Swatches takes about 0.5 to 2 sec to kick in, that's why the web page makes a repaint and shows the two 'Swatches bars'.

Easy solution, add this on top of the main CSS file or as an inline style. <style></style> in your theme header.php file before a line that has wp_head(); function call:

.woo-variation-swatches-theme-child-woodmart .woo-variation-items-wrapper>.swatches-select,
.woo-variation-swatches-theme-woodmart .woo-variation-items-wrapper>.swatches-select {
  display: none;
}

Better and clean solution, devote sometime to improve your WordPress performance, try to use as few plugins as possible as many of them are badly coded, follow Google Page Speed advices here and also I recommend that you check and make sure you're using PHP 7+ in case you're not already.


问:
NHibernate SaveOrUpdate Child Collection Not Updated With Identity Ids
I am clearly missing something (hopefully obvious), and I have had no luck with Google so far.

I have a Parent-Child relationship mapped as follows

Simplified Parent Map

```<code>  public sealed class ParentMap : ClassMap<ParentEntity>
  {
    public ParentMap()
    {
      Table("Parent");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.ServeralNotNullableProperties).Not.Nullable();

      HasMany(x => x.Children).KeyColumn("ChildId")
                              .Inverse()
                              .LazyLoad()
                              .Cascade
                              .AllDeleteOrphan();

      References(x => x.SomeUnrelatedLookupColumn).Column("LookupColumnId").Not.Nullable();
    }
  }
</code>```

Simplified Child Map

```<code>  public sealed class ChildMap : ClassMap<ChildEntity>
  {
    public ChildMap()
    {
      Table("Child");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.MoreNotNullableProperties).Not.Nullable();

      References(x => x.Parent).Column("ParentId").Not.Nullable();
    }
  }
</code>```

Simplified Service Method Steps

I then have a service method that retrieves Parent and adds a new Child via some domain method. The underlying NHibernate code boils down to:

1) Session Opened on WCF AfterReceiveRequest (IDispatchMessageInspector)

```<code>_sessionFactory.OpenSession();
</code>```

2) Retrieve existing instance of parent via .Query

```<code>_session.Query<ParentEntity>()
        .Where(item => item.Id == parentId)
        .Fetch(item => item.SomeLookupColumn)
        .First();
</code>```

3) Add new 'Child' entity to 'Parent' via domain object method such as...

```<code>public ChildEntity CreateChild()
{
  var child = new ChildEntity{ Parent = this };

  Children.Add(child);

  return child;
}
</code>```

4) Ultimately calls SaveOrUpdate on 'Parent' entity.

```<code> // ChildEntity Id is 0
 _session.SaveOrUpdate(parentEntity)
 // Expect ChildEntity Id to NOT be 0
</code>```

Note: Use of SaveOrUpdate Does persist changes to database; use of Merge results in TransientObjectException mentioned below.

5) Finally, transaction committed on WCF BeforeSendReply (IDispatchMessageInspector)

```<code> _session.Commit();
</code>```

The Problem

Typically when an entity is saved, after the call to SaveOrUpdate, the Id of said entity refects the Identity generated by the INSERT statement. However, when I add a new child entity to an existing parent, the associated entity in Children does not get assigned an Id. I need to pass this Id back to the caller so subsequent calls result in UPDATES and not additional INSERTS.

Why is NHibernate not updating the underlying entity?
Do I explicitly have to call SaveOrUpdate on the child (that sucks if that is the case)?

Any thoughts on the matter greatly appreciated. Thanks!

EDIT
I should note, that the new child entity IS being saved as expected; I just don't get back the Id assigned.

UPDATE
Tried switching to .Merge(~) as suggested by Michael Buen below; resulting in a TransientObjectException telling me to explicitly save my modified child entity before calling merge. I also experimented with .Persist(~) to no avail. Any additional insight greatly appreciated.

object is an unsaved transient instance - save the transient instance before merging: My.NameSpace.ChildEntity

答:
For detached scenario, use Merge(formerly known as SaveOrUpdateCopy)

Example: http://www.ienablemuch.com/2011/01/nhibernate-saves-your-whole-object.html

Regarding:

Do I explicitly have to call
  SaveOrUpdate on the child (that sucks
  if that is the case)?

You don't need to, in fact that's where an ORM like NHibernate shines, it can save the whole object graph, and it really solves the impedance mismatch between the Object and database.

The physical implementation(for example, int or guid) of how a parent and child records(and sub-child records and so on) are linked is completely invisible from the app. You can concentrate well on your objects rather than the under-the-hood plumbing on what datatypes(int,guid,etc) your object relationships should use

[UPDATE]

You can still save the parent and the saving will cascade to children, and can get the child's id too. If you need to get the child id, get it after commit.

You cannot get the child id this way:

```<code>s.SaveOrUpdate(parentEntity);
Console.WriteLine("{0}", parentEntity.ChildIdentity.First().ChildId);
tx.Commit();
</code>```

Must do this:

```<code>s.SaveOrUpdate(parentEntity);
tx.Commit();
Console.WriteLine("{0}", parentEntity.ChildIdentity.First().ChildId);
</code>```

Body:
I am clearly missing something (hopefully obvious), and I have had no luck with Google so far.

I have a Parent-Child relationship mapped as follows

Simplified Parent Map

  public sealed class ParentMap : ClassMap<ParentEntity>
  {
    public ParentMap()
    {
      Table("Parent");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.ServeralNotNullableProperties).Not.Nullable();

      HasMany(x => x.Children).KeyColumn("ChildId")
                              .Inverse()
                              .LazyLoad()
                              .Cascade
                              .AllDeleteOrphan();

      References(x => x.SomeUnrelatedLookupColumn).Column("LookupColumnId").Not.Nullable();
    }
  }

Simplified Child Map

  public sealed class ChildMap : ClassMap<ChildEntity>
  {
    public ChildMap()
    {
      Table("Child");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.MoreNotNullableProperties).Not.Nullable();

      References(x => x.Parent).Column("ParentId").Not.Nullable();
    }
  }

Simplified Service Method Steps

I then have a service method that retrieves Parent and adds a new Child via some domain method. The underlying NHibernate code boils down to:

1) Session Opened on WCF AfterReceiveRequest (IDispatchMessageInspector)

_sessionFactory.OpenSession();

2) Retrieve existing instance of parent via .Query

_session.Query<ParentEntity>()
        .Where(item => item.Id == parentId)
        .Fetch(item => item.SomeLookupColumn)
        .First();

3) Add new 'Child' entity to 'Parent' via domain object method such as...

public ChildEntity CreateChild()
{
  var child = new ChildEntity{ Parent = this };

  Children.Add(child);

  return child;
}

4) Ultimately calls SaveOrUpdate on 'Parent' entity.

 // ChildEntity Id is 0
 _session.SaveOrUpdate(parentEntity)
 // Expect ChildEntity Id to NOT be 0

Note: Use of SaveOrUpdate Does persist changes to database; use of Merge results in TransientObjectException mentioned below.

5) Finally, transaction committed on WCF BeforeSendReply (IDispatchMessageInspector)

 _session.Commit();

The Problem

Typically when an entity is saved, after the call to SaveOrUpdate, the Id of said entity refects the Identity generated by the INSERT statement. However, when I add a new child entity to an existing parent, the associated entity in Children does not get assigned an Id. I need to pass this Id back to the caller so subsequent calls result in UPDATES and not additional INSERTS.

Why is NHibernate not updating the underlying entity?
Do I explicitly have to call SaveOrUpdate on the child (that sucks if that is the case)?

Any thoughts on the matter greatly appreciated. Thanks!

EDIT
I should note, that the new child entity IS being saved as expected; I just don't get back the Id assigned.

UPDATE
Tried switching to .Merge(~) as suggested by Michael Buen below; resulting in a TransientObjectException telling me to explicitly save my modified child entity before calling merge. I also experimented with .Persist(~) to no avail. Any additional insight greatly appreciated.

object is an unsaved transient instance - save the transient instance before merging: My.NameSpace.ChildEntity

Body:
For detached scenario, use Merge(formerly known as SaveOrUpdateCopy)

Example: http://www.ienablemuch.com/2011/01/nhibernate-saves-your-whole-object.html

Regarding:

Do I explicitly have to call
  SaveOrUpdate on the child (that sucks
  if that is the case)?

You don't need to, in fact that's where an ORM like NHibernate shines, it can save the whole object graph, and it really solves the impedance mismatch between the Object and database.

The physical implementation(for example, int or guid) of how a parent and child records(and sub-child records and so on) are linked is completely invisible from the app. You can concentrate well on your objects rather than the under-the-hood plumbing on what datatypes(int,guid,etc) your object relationships should use

[UPDATE]

You can still save the parent and the saving will cascade to children, and can get the child's id too. If you need to get the child id, get it after commit.

You cannot get the child id this way:

s.SaveOrUpdate(parentEntity);
Console.WriteLine("{0}", parentEntity.ChildIdentity.First().ChildId);
tx.Commit();

Must do this:

s.SaveOrUpdate(parentEntity);
tx.Commit();
Console.WriteLine("{0}", parentEntity.ChildIdentity.First().ChildId);


问:
smooth signal and find peaks
Given I have an X and Y array such that:

```<code>X = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
</code>```

and

```<code>Y = np.array([-19.9, -19.6, -17.6, -15.9, -19.9, -18.4, -17.7, -16.6, -19.5, -20.4, -17.6, -15.9])
</code>```

I get a plot like:

Here there are 3 very clear peaks that I can see. I can fit this data using:

```<code># fit polynomial
z = np.polyfit(X1, Y, 8)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(X[0], X[-1], 100)
y_new = f(x_new)
</code>```

and I can get the following which shows the change in signal over the course of a year - in this case in rice agriculture and the number of agricultural cycles (3 peaks) :

Here I use scipy.signal.argrelextrema to find the peaks and troughs of the curve. However, to get a curve with a good fit is a very 'manual' approach and I have to interpret the data by eye first, in order to choose the polynomial order. I will be repeating this process on many datasets (100,000's) so won't be able to do this manually each time.

Furthermore, the number of peaks I have is likely to change. In fact my ultimate goal here is to categorize the datasets I have into the number of peaks I can detect. There are also cases where the signal has more noise.

I have looked into scipy.signal.find_peaks (and related algorithms) but this finds every peak and not just the major ones, particularly in noisier data. I have also looked into savgol filters and gaussian filters and am able to get a result but often have to specify the order of the polynomial etc, which is likely to change with the number of peaks.

Is there a way to smooth a signal to get an approximation of the number of peaks without having to manually specify polynomial orders etc? Is there an algorithm/method available that can detect general trends without too much user input?

I'm also open to alternative methods if there is a better method than curve fitting. I fear that the result I get out will only be as good as what I put in, and so any general curve fitting approaches will deliver poorer results.

答:
Here is a graphical fitter using your data and a simple equation, a Fourier series 1 Term with offset, that appears to give an automatic smooth fit.

```<code>import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

xData = numpy.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0])
yData = numpy.array([-19.9, -19.6, -17.6, -15.9, -19.9, -18.4, -17.7, -16.6, -19.5, -20.4, -17.6, -15.9])

# Fourier Series 1 Term (scaled X) from zunzun.com
def func(x, offset, a1, b1, c1):
    return a1 *numpy.sin(c1 * x) + b1 *numpy.cos(c1 * x) + offset

# these are the same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0, 1.0, 1.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)
</code>```

Title: smooth signal and find peaks

Body:
Given I have an X and Y array such that:

X = np.array([1,2,3,4,5,6,7,8,9,10,11,12])

and

Y = np.array([-19.9, -19.6, -17.6, -15.9, -19.9, -18.4, -17.7, -16.6, -19.5, -20.4, -17.6, -15.9])

I get a plot like:

Here there are 3 very clear peaks that I can see. I can fit this data using:

# fit polynomial
z = np.polyfit(X1, Y, 8)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(X[0], X[-1], 100)
y_new = f(x_new)

and I can get the following which shows the change in signal over the course of a year - in this case in rice agriculture and the number of agricultural cycles (3 peaks) :

Here I use scipy.signal.argrelextrema to find the peaks and troughs of the curve. However, to get a curve with a good fit is a very 'manual' approach and I have to interpret the data by eye first, in order to choose the polynomial order. I will be repeating this process on many datasets (100,000's) so won't be able to do this manually each time.

Furthermore, the number of peaks I have is likely to change. In fact my ultimate goal here is to categorize the datasets I have into the number of peaks I can detect. There are also cases where the signal has more noise.

I have looked into scipy.signal.find_peaks (and related algorithms) but this finds every peak and not just the major ones, particularly in noisier data. I have also looked into savgol filters and gaussian filters and am able to get a result but often have to specify the order of the polynomial etc, which is likely to change with the number of peaks.

Is there a way to smooth a signal to get an approximation of the number of peaks without having to manually specify polynomial orders etc? Is there an algorithm/method available that can detect general trends without too much user input?

I'm also open to alternative methods if there is a better method than curve fitting. I fear that the result I get out will only be as good as what I put in, and so any general curve fitting approaches will deliver poorer results.

Body:
Here is a graphical fitter using your data and a simple equation, a Fourier series 1 Term with offset, that appears to give an automatic smooth fit.

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

xData = numpy.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0])
yData = numpy.array([-19.9, -19.6, -17.6, -15.9, -19.9, -18.4, -17.7, -16.6, -19.5, -20.4, -17.6, -15.9])

# Fourier Series 1 Term (scaled X) from zunzun.com
def func(x, offset, a1, b1, c1):
    return a1 *numpy.sin(c1 * x) + b1 *numpy.cos(c1 * x) + offset

# these are the same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0, 1.0, 1.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)


问:
ASP.NET MVC login layout page not displaying CSS
I have created a new login layout for my login page and cannot get the css file to link.

I have tried not using a layout page at all, using @{Layout = null} and rendering an entire HTML page (header tags...etc) and linking the CSS in the header tags and nothing. I have also moved the login.css link above the bootstrap link and it still isn't rendering any CSS. Now I have a LoginLayout with the CSS and bootstrap files linked in the header tags. Still nothing.

My bootstrap is rendering, but not my CSS. Can anyone help with linking the login.css file to _LoginLayout.cshtml?

_LoginLayout.cshtml:

```<code><!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title | Knowledgebase</title>
    <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/login.css")" rel="stylesheet" type="text/css" />
</head>
<body>
    <div>
         @RenderBody()
    </div>
</body>
</html>
</code>```

Login.cshtml View:

```<code>@model ITKnowledgebase.Models.LoginModel

@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_LoginLayout.cshtml";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="container">
        <div class="form-horizontal">
            <br>
            <img src="~/Content/Images/logo.png">
            <br> <br>
            <h2>Knowledgebase Sign In</h2>

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="pnlMain">
                <label class="sr-only">ID</label>
                @Html.EditorFor(model => model.Id, new { htmlAttributes = new { placeholder = "ID", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
                <label class="sr-only">Username</label>
                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { placeholder = "Username", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
                <label class="sr-only">Password</label>
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { placeholder = "Password", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
            <input type="submit" value="Sign In" class="btn btn-primary" id="btnSubmit" />
        </div>
    </div>
}
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

    <hr />
    <footer>
        <p>© | All rights reserved.</p>
    </footer>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</code>```

AccountController:

```<code>namespace ITKnowledgebase.Controllers
{
    public class AccountController : Controller
    {
        // GET: Account
        public ActionResult Login()
        {
            var login = new LoginModel();
            return View(login);
        }

        [HttpPost]
        public ActionResult Login(LoginModel login)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("Index", "Home", login);
            }
            return View(login);
        }
    }
}
</code>```

I am expecting the background to turn blue as my login.css file includes:

```<code>body {
    font-size: 27px;
    background-color: lightblue;
}
</code>```

答:
1.Try giving the source like this:

Instead of this

```<code> <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
</code>```

Use this

```<code> <link href="~/Content/bootstrap.css" rel="stylesheet" type="text/css" />
</code>```

If you are using visual studio it will be better do drag and drop the css file so you'll be sure that the source is correct.

Try refreshing your site if you're not.  ( Refresh with CTRL + F5 )

Instert !important after your attribute to overwrite the same attr in another css file. Like this

body {
font-size: 27px !important;
background-color: lightblue !important;
}

Body:
I have created a new login layout for my login page and cannot get the css file to link.

I have tried not using a layout page at all, using @{Layout = null} and rendering an entire HTML page (header tags...etc) and linking the CSS in the header tags and nothing. I have also moved the login.css link above the bootstrap link and it still isn't rendering any CSS. Now I have a LoginLayout with the CSS and bootstrap files linked in the header tags. Still nothing.

My bootstrap is rendering, but not my CSS. Can anyone help with linking the login.css file to _LoginLayout.cshtml?

_LoginLayout.cshtml:

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title | Knowledgebase</title>
    <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/login.css")" rel="stylesheet" type="text/css" />

         @RenderBody()

Login.cshtml View:

@model ITKnowledgebase.Models.LoginModel

@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_LoginLayout.cshtml";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Knowledgebase Sign In

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                ID
                @Html.EditorFor(model => model.Id, new { htmlAttributes = new { placeholder = "ID", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
                Username
                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { placeholder = "Username", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
                Password
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { placeholder = "Password", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

            <input type="submit" value="Sign In" class="btn btn-primary" id="btnSubmit" />

}

        @Html.ActionLink("Back to List", "Index")

© | All rights reserved.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")

AccountController:

namespace ITKnowledgebase.Controllers
{
    public class AccountController : Controller
    {
        // GET: Account
        public ActionResult Login()
        {
            var login = new LoginModel();
            return View(login);
        }

        [HttpPost]
        public ActionResult Login(LoginModel login)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("Index", "Home", login);
            }
            return View(login);
        }
    }
}

I am expecting the background to turn blue as my login.css file includes:

body {
    font-size: 27px;
    background-color: lightblue;
}

Body:
1.Try giving the source like this:

Instead of this

 <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />

Use this

 <link href="~/Content/bootstrap.css" rel="stylesheet" type="text/css" />

If you are using visual studio it will be better do drag and drop the css file so you'll be sure that the source is correct.

Try refreshing your site if you're not.  ( Refresh with CTRL + F5 )

Instert !important after your attribute to overwrite the same attr in another css file. Like this

body {
font-size: 27px !important;
background-color: lightblue !important;
}


问:
How to call functions with tkinter from existing script
The title isnt very accurate i think

Here is the begining of my script

```<code>rom colorama import init, Fore, Back, Style
import commands
import config
import sys

# Coloroma autoreset
init(autoreset=True)

while True:
    # Database Check.
    while True:
        db = input("Check for new databases? Y/N: ")
        if db.lower() == 'y':
            commands.db_download()
            break
        elif db.lower() == 'n':
            break
        else:
            continue
</code>```

It's a bot to automatize some actions. Now i want to add some gui to it but i dont know how.

And here's the start of what i tried to do with tkinter

```<code>import tkinter
import questions

top = tkinter.Tk()

B = tkinter.Button(top, text ="Lancer", command = db)

top.mainloop()
</code>```

Like you see at the left, i have " import questions" but cuz of it when I launch the tkinter file, it automatically launches the questions without taking my "B" code into account.

How can I add gui to each command of my questions.py?

答:
If you import a script then it will run all the code in that script, if you want to only run certain parts of your script at a time you have to put those bits of code into functions.

For example:

def coloroma_autoreset():
    init(autoreset=True)

    while True:
        # Database Check.
        while True:
            db = input("Check for new databases? Y/N: ")
            if db.lower() == 'y':
                commands.db_download()
                break
            elif db.lower() == 'n':
                break
            else:
                continue
```

<blockquote>
  <p>If this code was in a file "questions.py" you could then <code>import
  questions</code> and run this function like this:</p>
</blockquote>

<pre class="lang-py prettyprint-override"><code>import questions

questions.coloroma_autoreset() # this would run the code
</code>```

Another problem with your code is that you aren't displaying your
  buttons, you need to use some sort of geometry manager that tkinter
  offers to display any widgets you add to your window.

Like so:

import tkinter
import questions

top = tkinter.Tk()

B = tkinter.Button(top, text ="Lancer", command = db)
B.pack()

top.mainloop()
```

Body:
The title isnt very accurate i think

Here is the begining of my script

rom colorama import init, Fore, Back, Style
import commands
import config
import sys

# Coloroma autoreset
init(autoreset=True)

while True:
    # Database Check.
    while True:
        db = input("Check for new databases? Y/N: ")
        if db.lower() == 'y':
            commands.db_download()
            break
        elif db.lower() == 'n':
            break
        else:
            continue

It's a bot to automatize some actions. Now i want to add some gui to it but i dont know how.

And here's the start of what i tried to do with tkinter

import tkinter
import questions

top = tkinter.Tk()

B = tkinter.Button(top, text ="Lancer", command = db)

top.mainloop()

Like you see at the left, i have " import questions" but cuz of it when I launch the tkinter file, it automatically launches the questions without taking my "B" code into account.

How can I add gui to each command of my questions.py?

Body:
If you import a script then it will run all the code in that script, if you want to only run certain parts of your script at a time you have to put those bits of code into functions.

For example:

def coloroma_autoreset():
    init(autoreset=True)

    while True:
        # Database Check.
        while True:
            db = input("Check for new databases? Y/N: ")
            if db.lower() == 'y':
                commands.db_download()
                break
            elif db.lower() == 'n':
                break
            else:
                continue

If this code was in a file "questions.py" you could then import
  questions and run this function like this:

import questions

questions.coloroma_autoreset() # this would run the code

Another problem with your code is that you aren't displaying your
  buttons, you need to use some sort of geometry manager that tkinter
  offers to display any widgets you add to your window.

Like so:

import tkinter
import questions

top = tkinter.Tk()

B = tkinter.Button(top, text ="Lancer", command = db)
B.pack()

top.mainloop()


问:
Opening and hiding web-page
I tried using window.open() with '_blank' and then window.blur() in chrome, but the web-page does not hide itself from the user. All I want to do is open a child web-page from its parent (with same origin) while hiding the child, scrape some of the html from the child's body, then close the child web-page. I know I could also do this with an iframe, but I am building a chrome extension that needs to interact with the child web-page and won't do so with an iframe, unless there's a way I can do that? Here is my working code I have so far:</p>

```<code>  var links = document.getElementsByClassName("link");
  var num = links.length;

  for (var i = 0; i < num; i++) {
    var win = window.open(links[i].href, "_blank");
    win.blur();
  }
</code>```

答:
```<code>    var links = document.getElementsByClassName("link");
  var num = links.length;

  for (var i = 0; i < num; i++) {

    var win = window.open(links[i].href,"_blank")

    win.close();

  }
</code>```

with modifying your method window will be closed immediately but the user will able to detect that(means any window is opened and close sudden) (tested on chrome)

```<code>      var links = document.getElementsByClassName("link");
      var num = links.length;

      for (var i = 0; i < num; i++) {

        var win = window.open(links[i].href,"_blank",'toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,left=10000, top=10000, width=10, height=10, visible=none', '')

        win.close();

  }
</code>```

with this method, the user will not able to see if there is any window open or not.

Title: Opening and hiding web-page

Body:
I tried using window.open() with '_blank' and then window.blur() in chrome, but the web-page does not hide itself from the user. All I want to do is open a child web-page from its parent (with same origin) while hiding the child, scrape some of the html from the child's body, then close the child web-page. I know I could also do this with an iframe, but I am building a chrome extension that needs to interact with the child web-page and won't do so with an iframe, unless there's a way I can do that? Here is my working code I have so far:

  var links = document.getElementsByClassName("link");
  var num = links.length;

  for (var i = 0; i < num; i++) {
    var win = window.open(links[i].href, "_blank");
    win.blur();
  }

Body:
    var links = document.getElementsByClassName("link");
  var num = links.length;

  for (var i = 0; i < num; i++) {

    var win = window.open(links[i].href,"_blank")

    win.close();

  }

with modifying your method window will be closed immediately but the user will able to detect that(means any window is opened and close sudden) (tested on chrome)

      var links = document.getElementsByClassName("link");
      var num = links.length;

      for (var i = 0; i < num; i++) {

        var win = window.open(links[i].href,"_blank",'toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,left=10000, top=10000, width=10, height=10, visible=none', '')

        win.close();

  }

with this method, the user will not able to see if there is any window open or not.


问:
Heroku not finding procfile - Flask-SocketIO
I am trying to deploy a flask-socketio project to the web, but the build isn't noticing the web dyno. I made a file called Procfile, without an extension. Inside procfile it has

```<code>web:gunicorn manage:app
</code>```

Should I change manage to manage.py? Why does the build look like

```<code>-----> Python app detected
-----> Installing requirements with pip
-----> Discovering process types
-----> Compressing...
       Done: 46.1M
-----> Launching...
       Released v32
       https://use-chats.herokuapp.com/ deployed to Heroku
</code>```

One time it said it had found a web dyno, but now it isn't.

答:
I think the Procfile requires a space between the <process_type>: and the command to run:

```<code>web: gunicorn manage:app
</code>```

A useful resource:

https://devcenter.heroku.com/articles/python-gunicorn

Body:
I am trying to deploy a flask-socketio project to the web, but the build isn't noticing the web dyno. I made a file called Procfile, without an extension. Inside procfile it has

web:gunicorn manage:app

Should I change manage to manage.py? Why does the build look like

-----> Python app detected
-----> Installing requirements with pip
-----> Discovering process types
-----> Compressing...
       Done: 46.1M
-----> Launching...
       Released v32
       https://use-chats.herokuapp.com/ deployed to Heroku

One time it said it had found a web dyno, but now it isn't.

Body:
I think the Procfile requires a space between the <process_type>: and the command to run:

web: gunicorn manage:app

A useful resource:

https://devcenter.heroku.com/articles/python-gunicorn


问:
Issue with randomForest & long vectors
I am running random forest on a data set with 8 numeric columns (the predictors), and 1 factor (the outcome).  There are 1.2M rows in the dataset.  When I do:

randomForest(outcome.f ~ a + b + c + d + e + f + g + h,data=mdata)), I get an error:

```<code>"Error in randomForest.default(m, y, ...) :
 long vectors (argument 26) are not supported in .Fortran"
</code>```

Is there any way to prevent this?  I don't understand why the package is (apparently) trying to allocate a vector of length 2^31-1.  I'm using Mac OS X 10.9.2, with an Intel Core i7 (in case the architecture matters).

Session info

```<code>R version 3.1.0 (2014-04-10)
Platform: x86_64-apple-darwin13.1.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] randomForest_4.6-7

loaded via a namespace (and not attached):
[1] tools_3.1.0
</code>```

答: I've had this issue before, and it was solved by using proximity = FALSE. This way the proximity matrix is not computed and R is able to finish the process

Title: Issue with randomForest & long vectors

Body:
I am running random forest on a data set with 8 numeric columns (the predictors), and 1 factor (the outcome).  There are 1.2M rows in the dataset.  When I do:

randomForest(outcome.f ~ a + b + c + d + e + f + g + h,data=mdata)), I get an error:

"Error in randomForest.default(m, y, ...) :
 long vectors (argument 26) are not supported in .Fortran"

Is there any way to prevent this?  I don't understand why the package is (apparently) trying to allocate a vector of length 2^31-1.  I'm using Mac OS X 10.9.2, with an Intel Core i7 (in case the architecture matters).

Session info

R version 3.1.0 (2014-04-10)
Platform: x86_64-apple-darwin13.1.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] randomForest_4.6-7

loaded via a namespace (and not attached):
[1] tools_3.1.0


问:
How to display information on rollover image like facebook people taging
I wonder if anyone can post a code example on how I can display some information when I hover a certain pixel cordinate on an image (just like when I hover a picture on a facebook image and it displays a text of who that person is that I currently have my mouse pointer over).

The diffrence between facebook and my solution is that my picture is not a picture which contains people, but multiple graphs on same picture, so alot of image pixelcordinates is going to display some data when I hover over them.

I also want my sollution to be webbased, and if possible only contain javascript, jquery css html.

Thanks so much in advance =)

答:
Here are a few links for the same.They make use of a css technique known as "image maps"

http://www.frankmanno.com/ideas/css-imagemap/

http://frankmanno.com/ideas/css-imagemap-redux/

http://www.noobcube.com/tutorials/html-css/css-image-maps-a-beginners-guide-/