问:
R Loop Iterating Over Two Lists
I am attempting to loop over multiple dataframes in R and to extract one column from each dataframe and subtract the value of an element in a separate list. So for example, I want

```<code>df1$my_new_col<-df1$my_col - my_list[[1]]
df2$my_new_col<-df2$my_col - my_list[[2]]

etc...
</code>```

The code I have written only extracts the last element in the list and uses it in all of the calculations.

Simply put, I have one list called dates which is a list of dates and another list called spx_list which is a list of annualized returns of the S&P 500.

In my code, I am attempting to loop over each date and extract a data frame of stock returns for that date. In my second loop, I am looping over the list of S&P returns which also correspond to each date and I attempt to subtract each S&P 500 return from each stock's return in that period. My dataframes look like the following when pulled for each date:

For Date 1

```<code>Ticker            Name                  Total.Return.Y.3..I.
JNS US Equity   JANUS CAPITAL GR    25.27
UNP US Equity   UNION PAC CORP      24.98
CVX US Equity   CHEVRON CORP        24.87
BHI US Equity   BAKER HUGHES A G    24.81
RAI US Equity   REYNOLDS AMERICA    24.72
XOM US Equity   EXXON MOBIL CORP    24.55
CBRE US Equity  CBRE GROUP INC-A    24.43
GT US Equity    GOODYEAR TIRE       24.39

</code>```

For Date 2

```<code>Ticker            Name                  Total.Return.Y.3..I.
JNS US Equity   JANUS CAPITAL GR    21.03
UNP US Equity   UNION PAC CORP      16.33
CVX US Equity   CHEVRON CORP        12.21
BHI US Equity   BAKER HUGHES A G    47.69
RAI US Equity   REYNOLDS AMERICA    18.39
XOM US Equity   EXXON MOBIL CORP    24.50
CBRE US Equity  CBRE GROUP INC-A    10.81
GT US Equity    GOODYEAR TIRE       11.13

</code>```

And for my S&P data:

```<code>Ticker     date         Annualized 3
SPX INDEX   3/31/2019   11.22854225
SPX INDEX   12/31/2018  7.041799573
SPX INDEX   9/30/2018   14.91926793
SPX INDEX   6/30/2018   9.629826851

</code>```

List data

```<code>dates <- list('2019-03-31','2018-12-31','2018-09-30','2018-06-30',
            '2018-03-31','2017-12-31','2017-09-30','2017-06-30',
            '2017-03-31','2016-12-31','2016-09-30','2016-06-30',
            '2016-03-31','2015-12-31','2015-09-30','2015-06-30',
            '2015-03-31','2014-12-31','2014-09-30','2014-06-30',
            '2014-03-31','2013-12-31','2013-09-30','2013-06-30',
            '2013-03-31','2012-12-31','2012-09-30','2012-06-30',
            '2012-03-31','2011-12-31','2011-09-30','2011-06-30',
            '2011-03-31','2010-12-31','2010-09-30','2010-06-30',
            '2010-03-31','2009-12-31','2009-09-30','2009-06-30',
            '2009-03-31','2008-12-31','2008-09-30','2008-06-30',
            '2008-03-31','2007-12-31','2007-09-30','2007-06-30',
            '2007-03-31','2006-12-31','2006-09-30','2006-06-30',
            '2006-03-31','2005-12-31','2005-09-30','2005-06-30',
            '2005-03-31','2004-12-31','2004-09-30','2004-06-30',
            '2004-03-31','2003-12-31','2003-09-30','2003-06-30',
            '2003-03-31','2002-12-31','2002-09-30','2002-06-30',
            '2002-03-31','2001-12-31','2001-09-30','2001-06-30',
            '2001-03-31','2000-12-31','2000-09-30','2000-06-30',
            '2000-03-31')
</code>```

Code

```<code>library(Rblpapi)
blpConnect()

library(dplyr)

spx <- read.csv('spx_3.csv')
spx_list <- as.list(spx$Annualized.3)

totals <- list()
returns <- list()

for(i in dates){

  df <- beqs('ROLLING RETURNS','PRIVATE',date=as.Date(i))
  df_beats <- df%>%
    select(date,Ticker,Total.Return.Y.3..I.)

  df_beats <- na.omit(df_beats)

  for(j in 1:length(spx_list)){

    df_beats$Relative_Performance <- df_beats$Total.Return.Y.3..I.-spx_list[[j]]

    counts <- sum(df_beats$Relative_Performance>0)
    yes <- df_beats%>%
      filter(df_beats$Relative_Performance>0)

    averages <- mean(yes$Total.Return.Y.3..I.)

    totals[[i]] <- counts
    returns[[i]] <- averages

  }
}
</code>```

The goal is to find what percentage of stocks outperformed the S&P 500 in a given year and to find out how much each stock underperformed or outperformed by subtracting the S&P 500's return form the individual stock return.

When the loop is completed, I find that only the last element of the S&p 500 list is used in the calculations, the other returns are skipped over. So in this case, the value of 9.629 is used in the calculation for each dataframe in each time period. Ideally I would like Date 1 Total.Return.Y.3..I to have 11.22 subtracted from it and Date 2$Total.Return.Y.3..I to have 7.04 subtracted from it etc...

I was wondering if anyone might be able help to me extract the data for each period as opposed to just using the last element in the S&P 500 list?

答:
Consider handling your process in sets instead of nested loops. Specifically, build a single beqs dataset, then merge it with spx by date for difference calculation. Finally, aggregate by date for needed totals and returns.

```<code>spx <- read.csv('spx_3.csv')

# BUILD LIST OF BEQS DATA FRAMES FOR EACH QUARTERLY DATE
df_list <- lapply(spx$date, function(i) {
      df <- beqs('ROLLING RETURNS', 'PRIVATE', date=as.Date(i))
      df <- df[c("date", "Ticker", "Total.Return.Y.3..I.")]
      return(na.omit(df))
})

# APPEND ALL FOR SINGLE DATA FRAME
df_beqs <- do.call(rbind, df_list)

# MERGE AND ADD NEW COLUMN
final_df <- transform(merge(df_beats, spx, by = "date"),
                      Relative_Performance = `Total.Return.Y.3..I.` - `Annualized 3`)
# FILTER DATA FRAME
final_df <- final_df[final_df$Relative_Performance > 0,]

# AGGREGATE BY DATE FOR MATRIX OUTPUT
agg_df <- aggregate(Total.Return.Y.3..I. ~ date, final_df,
                    function(x) c(totals = length(x), returns = mean(x)))
</code>```

Title: R Loop Iterating Over Two Lists

Body:
I am attempting to loop over multiple dataframes in R and to extract one column from each dataframe and subtract the value of an element in a separate list. So for example, I want

df1$my_new_col<-df1$my_col - my_list[[1]]
df2$my_new_col<-df2$my_col - my_list[[2]]

etc...

The code I have written only extracts the last element in the list and uses it in all of the calculations.

Simply put, I have one list called dates which is a list of dates and another list called spx_list which is a list of annualized returns of the S&P 500.

In my code, I am attempting to loop over each date and extract a data frame of stock returns for that date. In my second loop, I am looping over the list of S&P returns which also correspond to each date and I attempt to subtract each S&P 500 return from each stock's return in that period. My dataframes look like the following when pulled for each date:

For Date 1

Ticker            Name                  Total.Return.Y.3..I.
JNS US Equity   JANUS CAPITAL GR    25.27
UNP US Equity   UNION PAC CORP      24.98
CVX US Equity   CHEVRON CORP        24.87
BHI US Equity   BAKER HUGHES A G    24.81
RAI US Equity   REYNOLDS AMERICA    24.72
XOM US Equity   EXXON MOBIL CORP    24.55
CBRE US Equity  CBRE GROUP INC-A    24.43
GT US Equity    GOODYEAR TIRE       24.39

For Date 2

Ticker            Name                  Total.Return.Y.3..I.
JNS US Equity   JANUS CAPITAL GR    21.03
UNP US Equity   UNION PAC CORP      16.33
CVX US Equity   CHEVRON CORP        12.21
BHI US Equity   BAKER HUGHES A G    47.69
RAI US Equity   REYNOLDS AMERICA    18.39
XOM US Equity   EXXON MOBIL CORP    24.50
CBRE US Equity  CBRE GROUP INC-A    10.81
GT US Equity    GOODYEAR TIRE       11.13

And for my S&P data:

Ticker     date         Annualized 3
SPX INDEX   3/31/2019   11.22854225
SPX INDEX   12/31/2018  7.041799573
SPX INDEX   9/30/2018   14.91926793
SPX INDEX   6/30/2018   9.629826851

List data

dates <- list('2019-03-31','2018-12-31','2018-09-30','2018-06-30',
            '2018-03-31','2017-12-31','2017-09-30','2017-06-30',
            '2017-03-31','2016-12-31','2016-09-30','2016-06-30',
            '2016-03-31','2015-12-31','2015-09-30','2015-06-30',
            '2015-03-31','2014-12-31','2014-09-30','2014-06-30',
            '2014-03-31','2013-12-31','2013-09-30','2013-06-30',
            '2013-03-31','2012-12-31','2012-09-30','2012-06-30',
            '2012-03-31','2011-12-31','2011-09-30','2011-06-30',
            '2011-03-31','2010-12-31','2010-09-30','2010-06-30',
            '2010-03-31','2009-12-31','2009-09-30','2009-06-30',
            '2009-03-31','2008-12-31','2008-09-30','2008-06-30',
            '2008-03-31','2007-12-31','2007-09-30','2007-06-30',
            '2007-03-31','2006-12-31','2006-09-30','2006-06-30',
            '2006-03-31','2005-12-31','2005-09-30','2005-06-30',
            '2005-03-31','2004-12-31','2004-09-30','2004-06-30',
            '2004-03-31','2003-12-31','2003-09-30','2003-06-30',
            '2003-03-31','2002-12-31','2002-09-30','2002-06-30',
            '2002-03-31','2001-12-31','2001-09-30','2001-06-30',
            '2001-03-31','2000-12-31','2000-09-30','2000-06-30',
            '2000-03-31')

Code

library(Rblpapi)
blpConnect()

library(dplyr)

spx <- read.csv('spx_3.csv')
spx_list <- as.list(spx$Annualized.3)

totals <- list()
returns <- list()

for(i in dates){

  df <- beqs('ROLLING RETURNS','PRIVATE',date=as.Date(i))
  df_beats <- df%>%
    select(date,Ticker,Total.Return.Y.3..I.)

  df_beats <- na.omit(df_beats)

  for(j in 1:length(spx_list)){

    df_beats$Relative_Performance <- df_beats$Total.Return.Y.3..I.-spx_list[[j]]

    counts <- sum(df_beats$Relative_Performance>0)
    yes <- df_beats%>%
      filter(df_beats$Relative_Performance>0)

    averages <- mean(yes$Total.Return.Y.3..I.)

    totals[[i]] <- counts
    returns[[i]] <- averages

  }
}

The goal is to find what percentage of stocks outperformed the S&P 500 in a given year and to find out how much each stock underperformed or outperformed by subtracting the S&P 500's return form the individual stock return.

When the loop is completed, I find that only the last element of the S&p 500 list is used in the calculations, the other returns are skipped over. So in this case, the value of 9.629 is used in the calculation for each dataframe in each time period. Ideally I would like Date 1 Total.Return.Y.3..I to have 11.22 subtracted from it and Date 2$Total.Return.Y.3..I to have 7.04 subtracted from it etc...

I was wondering if anyone might be able help to me extract the data for each period as opposed to just using the last element in the S&P 500 list?

Body:
Consider handling your process in sets instead of nested loops. Specifically, build a single beqs dataset, then merge it with spx by date for difference calculation. Finally, aggregate by date for needed totals and returns.

spx <- read.csv('spx_3.csv')

# BUILD LIST OF BEQS DATA FRAMES FOR EACH QUARTERLY DATE
df_list <- lapply(spx$date, function(i) {
      df <- beqs('ROLLING RETURNS', 'PRIVATE', date=as.Date(i))
      df <- df[c("date", "Ticker", "Total.Return.Y.3..I.")]
      return(na.omit(df))
})

# APPEND ALL FOR SINGLE DATA FRAME
df_beqs <- do.call(rbind, df_list)

# MERGE AND ADD NEW COLUMN
final_df <- transform(merge(df_beats, spx, by = "date"),
                      Relative_Performance = `Total.Return.Y.3..I.` - `Annualized 3`)
# FILTER DATA FRAME
final_df <- final_df[final_df$Relative_Performance > 0,]

# AGGREGATE BY DATE FOR MATRIX OUTPUT
agg_df <- aggregate(Total.Return.Y.3..I. ~ date, final_df,
                    function(x) c(totals = length(x), returns = mean(x)))


来源: stackexchange

问:
Get datetime from a table row in MySQL
Let suppose that a row was inserted in a table with "id,name" fields (only), is it possible to get what date/time this record was inserted or updated using some mysql internal table or something like this? How? Thank you.</p>

答:
Sorry, there's no timestamp metadata on individual rows.

You'll have to add a timestamp column yourself, defaulting to CURRENT_TIMESTAMP.

The closest thing you can get to what you're asking for is to comb through the binary log (if there is one), but this will have the commit time for the transaction, which may be different from the timestamp when the record was inserted.

ContentLicense: CC BY-SA 4.0

Title: Get datetime from a table row in MySQL


问:
Can pureconfig use camel case config
I'm using pureconfig pureconfig lib with pureconfig-yaml module. Everything works like a charm, my only problem is that I have to convert the property names from camel case to kebab case.

Painful examples from real world:

```<code>case class Config(log4JPath: String, registryURL: String, HOUR_FORMAT: String)

Yaml:
log-4-j-path: /conf/log4j.properties
registry-url: http://foo.com
hour-_-format: dd-mm-yy
</code>```

I don't want to maintain 2 different case types and think about how to convert from one to the other, I would love to have pure copy&paste scala class -> yaml config solution. Is there a chance I could achieve camel case on both sides ?

Edit:

I've created a wrapper around pureconfig lib, which does some config overriding by environment variables. Client should use the wrapper in following manner:

```<code>val conf: Config = ConfigLoader(file).load[Config]
</code>```

However this is not sufficient and the client needs to provide 2 imports:

```<code>// to find implicit reader
import pureconfig.generic.auto._
// to use Camelcase - as suggested from the answer
import ConfigLoader.productHint
</code>```

It would be great if the wrapper (ConfigLoader) could deal with the imports and they would not be left on client's responsibility.
Moreover the imports are identified as "Unused" by IntelliJ IDE and when "optimize imports" is triggered or "Optimize imports on the fly" is enabled the imports are auto-erased. According to this thread (accepted answer is not working for me), we can solve this with "Mark import as always used...", however this is not an ideal solution because other team members will have to do the same for every project or we should commit .idea to VCS (which I'd like to avoid).

I'm attaching screenshot of my test (dependency pureconfig.generic.auto._ have already been marked as allways used):

答:
Yes you can. Take a look to the documentation - field-mappings.

```<code>import pureconfig._
import pureconfig.generic.auto._
import pureconfig.generic.ProductHint

// Case classes should be final ;)
final case class Config(log4JPath: String, registryURL: String, HOUR_FORMAT: String)

val yaml =
  """log4JPath: /conf/log4j.properties
    |registryURL: http://foo.com
    |HOUR_FORMAT: dd-mm-yy""".stripMargin

implicit val indentityHint: ProductHint[Conf] =
  ProductHint[Conf](new ConfigFieldMapping {
    def apply(fieldName: String) = fieldName // Basically the identity.
  })

loadYaml[Config](yaml)
// res: ConfigReader.Result[Config] = Right(Config("/conf/log4j.properties", "http://foo.com", "dd-mm-yy"))
</code>```

(Note, this was tested in ammonite, using pureconfig 0.11.0).

Title: Can pureconfig use camel case config

Body:
I'm using pureconfig pureconfig lib with pureconfig-yaml module. Everything works like a charm, my only problem is that I have to convert the property names from camel case to kebab case.

Painful examples from real world:

case class Config(log4JPath: String, registryURL: String, HOUR_FORMAT: String)

Yaml:
log-4-j-path: /conf/log4j.properties
registry-url: http://foo.com
hour-_-format: dd-mm-yy

I don't want to maintain 2 different case types and think about how to convert from one to the other, I would love to have pure copy&paste scala class -> yaml config solution. Is there a chance I could achieve camel case on both sides ?

Edit:

I've created a wrapper around pureconfig lib, which does some config overriding by environment variables. Client should use the wrapper in following manner:

val conf: Config = ConfigLoader(file).load[Config]

However this is not sufficient and the client needs to provide 2 imports:

// to find implicit reader
import pureconfig.generic.auto._
// to use Camelcase - as suggested from the answer
import ConfigLoader.productHint

It would be great if the wrapper (ConfigLoader) could deal with the imports and they would not be left on client's responsibility.
Moreover the imports are identified as "Unused" by IntelliJ IDE and when "optimize imports" is triggered or "Optimize imports on the fly" is enabled the imports are auto-erased. According to this thread (accepted answer is not working for me), we can solve this with "Mark import as always used...", however this is not an ideal solution because other team members will have to do the same for every project or we should commit .idea to VCS (which I'd like to avoid).

I'm attaching screenshot of my test (dependency pureconfig.generic.auto._ have already been marked as allways used):

Body:
Yes you can. Take a look to the documentation - field-mappings.

import pureconfig._
import pureconfig.generic.auto._
import pureconfig.generic.ProductHint

// Case classes should be final ;)
final case class Config(log4JPath: String, registryURL: String, HOUR_FORMAT: String)

val yaml =
  """log4JPath: /conf/log4j.properties
    |registryURL: http://foo.com
    |HOUR_FORMAT: dd-mm-yy""".stripMargin

implicit val indentityHint: ProductHint[Conf] =
  ProductHint[Conf](new ConfigFieldMapping {
    def apply(fieldName: String) = fieldName // Basically the identity.
  })

loadYaml[Config](yaml)
// res: ConfigReader.Result[Config] = Right(Config("/conf/log4j.properties", "http://foo.com", "dd-mm-yy"))

(Note, this was tested in ammonite, using pureconfig 0.11.0).


问:
Return all node values with their parents in PHP multidimensional array
I have a simple multidimensional array like this:
`

```<code>$array= [
    'A' => [
        'B' => ['D', 'E', 'F'],
    'C' => 'G',
    ],
];
</code>```

I need to return all node values with their parents. So I need an output like:

```<code>P[A] = 0;
P[B] = A;
P[D] = B;
P[E] = B;
P[F] = B;
P[C] = A;
P[G] = C;
</code>```

I've tried some functions like array_search(), array_walk_recursive and so on, but I couldn't apply these functions to my situation.
Thanks very much for any help!

答:
You could do this with an recursive function, that has the "parent" as optional second parameter.

$array = [
    'A' => [
        'B' => [ 'D', 'E', 'F' ],
        'C' => 'G',
    ],
];

function showParents($arr, $parent = 0) {
    foreach($arr as $key => $val) {
        if(is_array($val)) {
            // for when the element is an array
            echo '[' . $key . '] ' . $parent . '
';
        } else if(is_int($key)){
            // for when the array is an not-associative one (or are you using INTs as keys also?)
            echo '[' . $val . '] ' . $parent . '
';
        } else if(is_string($val)){
            // for when the value is a string ('C' => 'G')
            echo '[' . $key . '] ' . $parent . '
';// display parent of C
            echo '[' . $val . '] ' . $key . '
';// display parent of G
        }

        if(is_array($val)) {
            // when the current value is an array, go deeper
            showParents($val, $key);
        }
    }
}

showParents($array);
```

<p>Displays:</p>

```[A] 0
[B] A
[D] B
[E] B
[F] B
[C] A
[G] C
```

Body:
I have a simple multidimensional array like this:
`

$array= [
    'A' => [
        'B' => ['D', 'E', 'F'],
    'C' => 'G',
    ],
];

I need to return all node values with their parents. So I need an output like:

P[A] = 0;
P[B] = A;
P[D] = B;
P[E] = B;
P[F] = B;
P[C] = A;
P[G] = C;

I've tried some functions like array_search(), array_walk_recursive and so on, but I couldn't apply these functions to my situation.
Thanks very much for any help!

Body:
You could do this with an recursive function, that has the "parent" as optional second parameter.

$array = [
    'A' => [
        'B' => [ 'D', 'E', 'F' ],
        'C' => 'G',
    ],
];

function showParents($arr, $parent = 0) {
    foreach($arr as $key => $val) {
        if(is_array($val)) {
            // for when the element is an array
            echo '[' . $key . '] ' . $parent . '<br>';
        } else if(is_int($key)){
            // for when the array is an not-associative one (or are you using INTs as keys also?)
            echo '[' . $val . '] ' . $parent . '<br>';
        } else if(is_string($val)){
            // for when the value is a string ('C' => 'G')
            echo '[' . $key . '] ' . $parent . '<br>';// display parent of C
            echo '[' . $val . '] ' . $key . '<br>';// display parent of G
        }

        if(is_array($val)) {
            // when the current value is an array, go deeper
            showParents($val, $key);
        }
    }
}

showParents($array);

Displays:

[A] 0
[B] A
[D] B
[E] B
[F] B
[C] A
[G] C


问:
How to activate a wookbook named in a different module
I call module2 from module1 where I name a workbook "x" in module2. But later when I try "x.Activate" in module1 I get an error "Run-time error '424': Object required"

I have a rather lengthy module that I would like to organize by breaking it up into multiple modules. So far I have created a module called "INPUTS" in this module I have a "Sub RT_CMM_DATA_COMPILER_INPUTS()" presumably in the future I will have other Subs in this module "Sub RT_Some_Other_Project_INPUTS()" I name a workbook in "Sub RT_CMM_DATA_COMPILER_INPUTS()" and try to activate that workbook by name in a separate module called sandbox. But it displays an error.

```<code>'RT_Sandbox Module
Sub sandbox()

    Call RT_CMM_DATA_COMPILER_INPUTS

    wkbwatchFolders_table.Activate
    lastShtRow = LASTSHEETROW(ActiveSheet)

    MsgBox lastShtRow

End Sub

'Inputs module
Sub RT_CMM_DATA_COMPILER_INPUTS()

    watchFolders_filePath = "D:\RT_CMM_Data_File_Paths.xlsx"
    Set wkbwatchFolders_table = Workbooks.Open(Filename:=watchFolders_filePath)

End Sub
</code>```

Am I going about this attempt to organize my code completely wrong? Should I be using class modules for this instead? Or is it just some syntax I am missing?

答:
Using Public statement will work here:

```<code>Public x As Workbook
Public your_var As Object
</code>```

You need to declare these outside your procedure, at the top of the module. After declaring these you can access them anywhere in any module.

Read More here: Declaring Variables

Body:
I call module2 from module1 where I name a workbook "x" in module2. But later when I try "x.Activate" in module1 I get an error "Run-time error '424': Object required"

I have a rather lengthy module that I would like to organize by breaking it up into multiple modules. So far I have created a module called "INPUTS" in this module I have a "Sub RT_CMM_DATA_COMPILER_INPUTS()" presumably in the future I will have other Subs in this module "Sub RT_Some_Other_Project_INPUTS()" I name a workbook in "Sub RT_CMM_DATA_COMPILER_INPUTS()" and try to activate that workbook by name in a separate module called sandbox. But it displays an error.

'RT_Sandbox Module
Sub sandbox()

    Call RT_CMM_DATA_COMPILER_INPUTS

    wkbwatchFolders_table.Activate
    lastShtRow = LASTSHEETROW(ActiveSheet)

    MsgBox lastShtRow

End Sub

'Inputs module
Sub RT_CMM_DATA_COMPILER_INPUTS()

    watchFolders_filePath = "D:\RT_CMM_Data_File_Paths.xlsx"
    Set wkbwatchFolders_table = Workbooks.Open(Filename:=watchFolders_filePath)

End Sub

Am I going about this attempt to organize my code completely wrong? Should I be using class modules for this instead? Or is it just some syntax I am missing?

Body:
Using Public statement will work here:

Public x As Workbook
Public your_var As Object

You need to declare these outside your procedure, at the top of the module. After declaring these you can access them anywhere in any module.

Read More here: Declaring Variables


问:
UIImage in a Rounded UIView swift
I created a UIView and inthe UIView, I added an Imageview. I gave the UIView corner radius and it works, the propble I have now is that the image that I place inside does not respect the cornerradius of the view and as a result, it shows the entire image as a rectangle instead of having the topleft and topRight corner curved to the same radius of the UIView. my code is shown below.

```<code>let bgView: UIView = {
        let bgView = UIView()
        bgView.backgroundColor = .white
        return bgView
    }()

    let propertyImage: DefaultImageView = {
        let img = DefaultImageView(frame: .zero)
        img.clipsToBounds = true
        img.layer.masksToBounds = true
        img.image = #imageLiteral(resourceName: "icons8-name-filled-30")
        img.contentMode = .scaleToFill
        return img
    }()
</code>```

this gives the rounded cardview

```<code>extension UIView {
func addShadowAndRoundCorners() {
        layer.shadowOpacity = 1
        layer.shadowOffset = CGSize.zero
        layer.shadowColor = UIColor.darkGray.cgColor
        layer.cornerRadius = 12
    }
 }
</code>```

so I added the rounded style like bgView.addShadowAndRoundCorners

How can I make the imageview stay withing the rounded corners of the UIView

答:
The clipsToBounds to yes needs to be added to the container view as well in order to force the subviews not to render outside:

```<code>bgView.clipsToBounds = true
</code>```

Or you can just round the imageView itself.

Title: UIImage in a Rounded UIView swift

Body:
I created a UIView and inthe UIView, I added an Imageview. I gave the UIView corner radius and it works, the propble I have now is that the image that I place inside does not respect the cornerradius of the view and as a result, it shows the entire image as a rectangle instead of having the topleft and topRight corner curved to the same radius of the UIView. my code is shown below.

let bgView: UIView = {
        let bgView = UIView()
        bgView.backgroundColor = .white
        return bgView
    }()

    let propertyImage: DefaultImageView = {
        let img = DefaultImageView(frame: .zero)
        img.clipsToBounds = true
        img.layer.masksToBounds = true
        img.image = #imageLiteral(resourceName: "icons8-name-filled-30")
        img.contentMode = .scaleToFill
        return img
    }()

this gives the rounded cardview

extension UIView {
func addShadowAndRoundCorners() {
        layer.shadowOpacity = 1
        layer.shadowOffset = CGSize.zero
        layer.shadowColor = UIColor.darkGray.cgColor
        layer.cornerRadius = 12
    }
 }

so I added the rounded style like bgView.addShadowAndRoundCorners

How can I make the imageview stay withing the rounded corners of the UIView

Body:
The clipsToBounds to yes needs to be added to the container view as well in order to force the subviews not to render outside:

bgView.clipsToBounds = true

Or you can just round the imageView itself.


问:
JTokenType.Date is not matching in switch case
I have the following code snippet,

private static string CreateFilter(JProperty property)
{
    if (property?.Value == null)
    {
        return null;
    }

    switch (property.Value.Type)
    {
        case JTokenType.Array:
            return CreateFilterForArray(property.Name, (JArray)property.Value);

        case JTokenType.Object:
            return CreateFilterForObject(property.Name, (JObject)property.Value);
        case JTokenType.Date:
            Console.WriteLine("date");
            return null;

        case JTokenType.String:
            return CreateFilterForString(property.Name, ((JValue)property.Value).Value);

        case JTokenType.Integer:
            return CreateFilterForInteger(property.Name, ((JValue)property.Value).Value);
        default:
            throw new NotSupportedException($"No known way to handle json value with type of {property.Value.Type}");
    }
}
```

When the property.Value has a value of {05/22/2019}, instead of matching to
case JTokenType.Date: it matches to case JTokenType.String:
I guess this is probably because of the format expected for JTokenType.Date is different than what I'm providing to it.
What is the format expected by JTokenType.Date ?.
Is there any way to match the date format I have, to the JTokenType.Date ?

答: Thanks for @dbc's comment, I send the date in "2012-03-19T07:22:00Z" and it is now recognizing as JTokenType.Date

Body:
I have the following code snippet,

private static string CreateFilter(JProperty property)
{
    if (property?.Value == null)
    {
        return null;
    }

    switch (property.Value.Type)
    {
        case JTokenType.Array:
            return CreateFilterForArray(property.Name, (JArray)property.Value);

        case JTokenType.Object:
            return CreateFilterForObject(property.Name, (JObject)property.Value);
        case JTokenType.Date:
            Console.WriteLine("date");
            return null;

        case JTokenType.String:
            return CreateFilterForString(property.Name, ((JValue)property.Value).Value);

        case JTokenType.Integer:
            return CreateFilterForInteger(property.Name, ((JValue)property.Value).Value);
        default:
            throw new NotSupportedException($"No known way to handle json value with type of {property.Value.Type}");
    }
}

When the property.Value has a value of {05/22/2019}, instead of matching to
case JTokenType.Date: it matches to case JTokenType.String:
I guess this is probably because of the format expected for JTokenType.Date is different than what I'm providing to it.
What is the format expected by JTokenType.Date ?.
Is there any way to match the date format I have, to the JTokenType.Date ?


问:
jquery scroll to div and focus a textbox
I am trying to achieve two things with a single onclick of anchor tag. First, when I click on search, I am scrolling to a particular div, and then trying to focus on the textbox within that div. Below is the link to the sample code. I am able to scroll to the div, but somehow the textbox is losing focus. What is wrong with the code?

http://jsfiddle.net/e9tJ5/1/

答:
```<code>      $("#searchlink").click(function(){
        $("#searchtext").focus();
        return false;
      });
</code>```

ContentLicense: CC BY-SA 3.0


问:
PHP Echo within paragraph doesn't work with all records
I have a simple form, like this;

        <form action="column1.php" method="post">
        <input type="text" placeholder="URL:" name="url" required="">

        <input type="text" placeholder="Job Title:" name="title" required="">

        <input type="text" placeholder="Job Site & Additional Details" name="details">

        <input type="submit">

        </form>

```
</div>
</div>
</p>

<p>That form is then handled by <code>column1.php</code> which contains the following PHP;</p>

```<?php
$url = $_POST["url"];
$title = $_POST["title"];
$details = $_POST ["details"];
$timestamp =date('l jS \of F Y h:i:s A');
$text = "{$title}

 ".($details)."
 At: {$timestamp}

 \n";
$file = fopen("./data/column1.html","a+ \n");
 fwrite($file, $text);
 fclose($file);
?>
```

<p>Then on the page I want to show the submissions I use this;</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-html lang-html prettyprint-override"><code> <p class="linktext"><?php echo file_get_contents("./data/column1.html"); ?></p></code>```

The CSS for my linktext class is this;

.linktext {
    font-family: 'Roboto', serif;
    font-size: 1vw;
    text-align: center;
    margin-top: 0px;
    margin-bottom: 0px;
    color: #FFFFFF;
    padding-left: 2vh;
    padding-right: 2vh;
    padding-bottom: 0.5vh;
    line-height: 1em;
}

@media only screen and (max-width: 500px) {
.linktext {
    font-family: 'Roboto', serif;
    font-size: 4vw;
    text-align: center;
    margin-top: 0px;
    margin-bottom: 0px;
    color: #FFFFFF;
    padding-left: 1vh;
    padding-right: 1vh;
    padding-bottom: 0.5vh;
    line-height: 1em;
}
}```
</div>
</div>
</p>

<p>For some reason the echo works fine for the first result but as soon as the second submission is sent, it won't be displayed correctly.</p>

<p>The file containing the responses looks like this after two submissions;</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-html lang-html prettyprint-override"><code>Job Title 1<br><br> Job Details <br> At: Thursday 30th of May 2019 10:33:47 PM <br><br><hr><br>
Job Title 2<br><br> Job Details <br> At: Thursday 30th of May 2019 10:34:00 PM <br><br><hr><br> </code>```

But shows this;

I don't know why this has decided to not work given in other places, with the same type of form, the styling has worked just fine.

Any help would be appreciated on this because I'm stuck.

答:
I figured it out. Rather than;

<?php echo file_get_contents("./data/column1.html"); ?>
```
</div>
</div>
</p>

<p>I can just use;</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-html lang-html prettyprint-override"><code><div class="linktext"><?php echo file_get_contents("./data/column1.html"); ?></div></code>```

It maintains all styles and will work based on the same CSS for the text class.

Body:
I have a simple form, like this;

        <form action="column1.php" method="post">
        <input type="text" placeholder="URL:" name="url" required="">

        <input type="text" placeholder="Job Title:" name="title" required="">

        <input type="text" placeholder="Job Site & Additional Details" name="details">

        <input type="submit">

        </form>

That form is then handled by column1.php which contains the following PHP;

<?php
$url = $_POST["url"];
$title = $_POST["title"];
$details = $_POST ["details"];
$timestamp =date('l jS \of F Y h:i:s A');
$text = "{$title}

 ".($details)."
 At: {$timestamp}

 \n";
$file = fopen("./data/column1.html","a+ \n");
 fwrite($file, $text);
 fclose($file);
?>

Then on the page I want to show the submissions I use this;

<?php echo file_get_contents("./data/column1.html"); ?>

The CSS for my linktext class is this;

.linktext {
    font-family: 'Roboto', serif;
    font-size: 1vw;
    text-align: center;
    margin-top: 0px;
    margin-bottom: 0px;
    color: #FFFFFF;
    padding-left: 2vh;
    padding-right: 2vh;
    padding-bottom: 0.5vh;
    line-height: 1em;
}

@media only screen and (max-width: 500px) {
.linktext {
    font-family: 'Roboto', serif;
    font-size: 4vw;
    text-align: center;
    margin-top: 0px;
    margin-bottom: 0px;
    color: #FFFFFF;
    padding-left: 1vh;
    padding-right: 1vh;
    padding-bottom: 0.5vh;
    line-height: 1em;
}
}

For some reason the echo works fine for the first result but as soon as the second submission is sent, it won't be displayed correctly.

The file containing the responses looks like this after two submissions;

Job Title 1

 Job Details
 At: Thursday 30th of May 2019 10:33:47 PM

Job Title 2

 Job Details
 At: Thursday 30th of May 2019 10:34:00 PM

But shows this;

I don't know why this has decided to not work given in other places, with the same type of form, the styling has worked just fine.

Any help would be appreciated on this because I'm stuck.

Body:
I figured it out. Rather than;

<p class="linktext"><?php echo file_get_contents("./data/column1.html"); ?></p>

I can just use;

<div class="linktext"><?php echo file_get_contents("./data/column1.html"); ?></div>

It maintains all styles and will work based on the same CSS for the text class.


问:
Differences between and when to use Map vs Record
I am trying to map some Java code which uses Map's to Typescript code.
My initial thought was to use Map's in Typescript but for the interface I was creating this did not work out. Instead I found Records which seemed to emulate Java's Map's perfectly.

My main question is when should I use Typescript's Maps over Records and when should I use Typescripts Records over Maps?

How do they work differently?

```<code>viewMappings: Record<string, String[]>;
viewMappings: Map<String, String[]>;
</code>```

for example

I expect these to work in an interface with my State very similarly but they do not and am looking for documentation of the differences of the two.

答:
Record is defined as

```<code>type Record<K extends keyof any, T> = {
    [P in K]: T;
}
</code>```

While Map is a native JS ES6 data structure. Record is merely a representative way of saying, "this object is going to be used a key, value map of a specific data type". It's a plain object created using {}. The Map object on the other hands has some unique characteristics described here and needs to be instantiated as new Map()

Body:
I am trying to map some Java code which uses Map's to Typescript code.
My initial thought was to use Map's in Typescript but for the interface I was creating this did not work out. Instead I found Records which seemed to emulate Java's Map's perfectly.

My main question is when should I use Typescript's Maps over Records and when should I use Typescripts Records over Maps?

How do they work differently?

viewMappings: Record<string, String[]>;
viewMappings: Map<String, String[]>;

for example

I expect these to work in an interface with my State very similarly but they do not and am looking for documentation of the differences of the two.

Body:
Record is defined as

type Record<K extends keyof any, T> = {
    [P in K]: T;
}

While Map is a native JS ES6 data structure. Record is merely a representative way of saying, "this object is going to be used a key, value map of a specific data type". It's a plain object created using {}. The Map object on the other hands has some unique characteristics described here and needs to be instantiated as new Map()


问:
Powershell to move Excel files based on Initial part of the file name
I have hundreds of excel files like the following in directory called D:\TestARC_Source

```<code>5020190429.dat
5120190429.dat
602019111121.dat
702019050926.dat
etc.
</code>```

I need a script to move them to respective folders based on first two characters of file name. Folders are already created on target directory.

```<code>D:\TestARC_Destination\file_50
D:\TestARC_Destination\file_51
D:\TestARC_Destination\file_60
D:\TestARC_Destination\file_70
</code>```

Files should move to respective folders based on first two characters of file name. For example 5020190429.dat moves to 50_file folder.

I am trying to edit below script but it's not working. I have a very little knowledge in PS script and I'll appreciate if you can help me out.

```<code>$SourceFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Source\"
$targetFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Destination\"

# Find all files matching *.sql in the folder specified
Get-ChildItem -Path $SourceFolder -Filter *.dat | ForEach-Object {

    # Combine the source filename and target directory
    # The source filename has all instances of _ replaced with \
    # Cast the resulting string to a FileInfo object to take advantage of extra methods
    [System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace("_","\"))

    # Create the directory if it doesn't already exits
    if (!(Test-Path) $destination.Directory.FullName)
    {
        New-item -Path $destination.Directory.FullName -ItemType Directory
    }

    # Copy the source to the target directory
    copy-item -Path $_.FullName -Destination $Destination.FullName
}
</code>```

答:
The following should move the files based on your criteria. Please remove the -WhatIf switch if you are satisfied with what will be moved.

```<code>$Source = "D:\TestARC_Source"
$Dest = "D:\TestARC_Destination"

$FilesToMove = Get-ChildItem -Path $Source -File -Recurse -Filter "*.dat" -Include "[0-9][0-9]*"

Foreach ($file in $FilesToMove) {
    Move-Item -Path $file -Destination "$Dest\File_$($file.basename.substring(0,2))” -WhatIf
}
</code>```

Body:
I have hundreds of excel files like the following in directory called D:\TestARC_Source

5020190429.dat
5120190429.dat
602019111121.dat
702019050926.dat
etc.

I need a script to move them to respective folders based on first two characters of file name. Folders are already created on target directory.

D:\TestARC_Destination\file_50
D:\TestARC_Destination\file_51
D:\TestARC_Destination\file_60
D:\TestARC_Destination\file_70

Files should move to respective folders based on first two characters of file name. For example 5020190429.dat moves to 50_file folder.

I am trying to edit below script but it's not working. I have a very little knowledge in PS script and I'll appreciate if you can help me out.

$SourceFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Source\"
$targetFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Destination\"

# Find all files matching *.sql in the folder specified
Get-ChildItem -Path $SourceFolder -Filter *.dat | ForEach-Object {

    # Combine the source filename and target directory
    # The source filename has all instances of _ replaced with \
    # Cast the resulting string to a FileInfo object to take advantage of extra methods
    [System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace("_","\"))

    # Create the directory if it doesn't already exits
    if (!(Test-Path) $destination.Directory.FullName)
    {
        New-item -Path $destination.Directory.FullName -ItemType Directory
    }

    # Copy the source to the target directory
    copy-item -Path $_.FullName -Destination $Destination.FullName
}

Body:
The following should move the files based on your criteria. Please remove the -WhatIf switch if you are satisfied with what will be moved.

$Source = "D:\TestARC_Source"
$Dest = "D:\TestARC_Destination"

$FilesToMove = Get-ChildItem -Path $Source -File -Recurse -Filter "*.dat" -Include "[0-9][0-9]*"

Foreach ($file in $FilesToMove) {
    Move-Item -Path $file -Destination "$Dest\File_$($file.basename.substring(0,2))” -WhatIf
}


问:
mismatched input ')' expecting END
I need to create DMS_EPRPFL entity as shown by this pig script :

```<code>DMS_EPRPFL = FOREACH ORDER_EPSE_ENEE_ENR  GENERATE

GROUP_EPSE_ENEE_ENR::IDT_GCP           AS    IDT_GCP,
GROUP_EPSE_ENEE_ENR::CD_FRM_JUR        AS    CD_FRM_JUR,
GROUP_EPSE_ENEE_ENR::DA_CRE_EPS        AS    DA_CRE_EPS,
GROUP_EPSE_ENEE_ENR::NO_SIREN           AS   NO_SIREN,
GROUP_EPSE_ENEE_ENR::CD_POST            AS   CD_POST,
GROUP_EPSE_ENEE_ENR::CD_OSCE_PAYS_FIS    AS  CD_OSCE_PAYS_FIS,
GROUP_EPSE_ENEE_ENR::CD_NAF              AS  CD_NAF,
GROUP_EPSE_ENEE_ENR::CD_NACE             AS  CD_NACE,
(CASE (GROUP_EPSE_ENEE_ENR::CD_AXE_MCH)
WHEN ('PLIB' OR 'ATPE' OR 'COMM') THEN 'P'
WHEN ('PME') THEN 'E'
WHEN ('AGRI') THEN 'A'
WHEN ('OBNL') THEN 'O'
WHEN ('COLL') THEN 'C'
WHEN ('EFIN') THEN 'B'
WHEN ('NONA' OR 'SCI') THEN 'X')               AS CD_MARCHE,
GROUP_EPSE_ENEE_ENR::CD_AXE_SNIV_MCH           AS CD_AXE_SNIV_MCH,
MIN(GROUP_EPSE_ENEE_ENR::A_PRM_CTR)            AS A_PRM_CTR,
MIN(GROUP_EPSE_ENEE_ENR::A_PRM_CAV)            AS A_PRM_CAV,
MIN(GROUP_EPSE_ENEE_ENR::A_PRPRE)              AS A_PRPRE,
GROUP_EPSE_ENEE_ENR::CD_NOT                    AS CD_NOT;
</code>```

The problem is about CD_MARCHE .In fact I need to generate it according to specific conditions and using the case operator.

When executing the script I have this error :

mismatched input ')' expecting END

in this line

```<code> WHEN ('NONA' OR 'SCI') THEN 'X')               AS CD_MARCHE,
</code>```

I can't find the problem there.

Thanks for your help

答:
From
http://pig.apache.org/docs/latest/basic.html#arithmetic

CASE either takes

```<code>CASE expression [ WHEN value THEN value ]+ [ ELSE value ]? END
</code>```

OR

```<code>CASE [ WHEN condition THEN value ]+ [ ELSE value ]? END
</code>```

In your example, you're using the former but mixing condition (A OR B) where it only accepts value.   Two changes needed.

Add "END" at the end of your case statement and use the latter CASE statement.

Rewrite

```<code>(CASE (field)
    WHEN ( 'PLIB' OR 'ATPE' OR 'COMM' ) THEN 'P'
    WHEN ('PME') THEN 'E'
    ...
    WHEN ('NONA' OR 'SCI') THEN 'X') AS CD_MARCHE,
</code>```

to

```<code>(CASE
    WHEN (field in ('PLIB','ATPE','COMM') ) THEN 'P'
    WHEN (field == 'PME') THEN 'E'
    ...
    WHEN (field in ('NONA','SCI')) THEN 'X' END) AS CD_MARCHE,
</code>```

Title: mismatched input ')' expecting END

Body:
I need to create DMS_EPRPFL entity as shown by this pig script :

DMS_EPRPFL = FOREACH ORDER_EPSE_ENEE_ENR  GENERATE

GROUP_EPSE_ENEE_ENR::IDT_GCP           AS    IDT_GCP,
GROUP_EPSE_ENEE_ENR::CD_FRM_JUR        AS    CD_FRM_JUR,
GROUP_EPSE_ENEE_ENR::DA_CRE_EPS        AS    DA_CRE_EPS,
GROUP_EPSE_ENEE_ENR::NO_SIREN           AS   NO_SIREN,
GROUP_EPSE_ENEE_ENR::CD_POST            AS   CD_POST,
GROUP_EPSE_ENEE_ENR::CD_OSCE_PAYS_FIS    AS  CD_OSCE_PAYS_FIS,
GROUP_EPSE_ENEE_ENR::CD_NAF              AS  CD_NAF,
GROUP_EPSE_ENEE_ENR::CD_NACE             AS  CD_NACE,
(CASE (GROUP_EPSE_ENEE_ENR::CD_AXE_MCH)
WHEN ('PLIB' OR 'ATPE' OR 'COMM') THEN 'P'
WHEN ('PME') THEN 'E'
WHEN ('AGRI') THEN 'A'
WHEN ('OBNL') THEN 'O'
WHEN ('COLL') THEN 'C'
WHEN ('EFIN') THEN 'B'
WHEN ('NONA' OR 'SCI') THEN 'X')               AS CD_MARCHE,
GROUP_EPSE_ENEE_ENR::CD_AXE_SNIV_MCH           AS CD_AXE_SNIV_MCH,
MIN(GROUP_EPSE_ENEE_ENR::A_PRM_CTR)            AS A_PRM_CTR,
MIN(GROUP_EPSE_ENEE_ENR::A_PRM_CAV)            AS A_PRM_CAV,
MIN(GROUP_EPSE_ENEE_ENR::A_PRPRE)              AS A_PRPRE,
GROUP_EPSE_ENEE_ENR::CD_NOT                    AS CD_NOT;

The problem is about CD_MARCHE .In fact I need to generate it according to specific conditions and using the case operator.

When executing the script I have this error :

mismatched input ')' expecting END

in this line

 WHEN ('NONA' OR 'SCI') THEN 'X')               AS CD_MARCHE,

I can't find the problem there.

Thanks for your help

Body:
From
http://pig.apache.org/docs/latest/basic.html#arithmetic

CASE either takes

CASE expression [ WHEN value THEN value ]+ [ ELSE value ]? END

OR

CASE [ WHEN condition THEN value ]+ [ ELSE value ]? END

In your example, you're using the former but mixing condition (A OR B) where it only accepts value.   Two changes needed.

Add "END" at the end of your case statement and use the latter CASE statement.

Rewrite

(CASE (field)
    WHEN ( 'PLIB' OR 'ATPE' OR 'COMM' ) THEN 'P'
    WHEN ('PME') THEN 'E'
    ...
    WHEN ('NONA' OR 'SCI') THEN 'X') AS CD_MARCHE,

to

(CASE
    WHEN (field in ('PLIB','ATPE','COMM') ) THEN 'P'
    WHEN (field == 'PME') THEN 'E'
    ...
    WHEN (field in ('NONA','SCI')) THEN 'X' END) AS CD_MARCHE,


问:
Arithmetic mean in java
Problem statement

Need to find the Arithmetic mean of numbers entered by user.

Constraints

We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.

If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.

We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.

Code

```<code>public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int sum = 0;

    do {
        System.out.println("Value is :" + n);
        count++;
        sum = sum + n;
    }while ( n != -1);

}
</code>```

It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.

For the input of :

```<code>3
9
4
-7
0
2
-1
</code>```

The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8

答: You're reading "n" as input out of the while, then n has always the first value and the loop is infinite.</p>

Title: Arithmetic mean in java

Body:
Problem statement

Need to find the Arithmetic mean of numbers entered by user.

Constraints

We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.

If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.

We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.

Code

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int sum = 0;

    do {
        System.out.println("Value is :" + n);
        count++;
        sum = sum + n;
    }while ( n != -1);

}

It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.

For the input of :

3
9
4
-7
0
2
-1

The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8


问:
How can I better handle commits polluting a "closed" branch in git?
We're new to git at my company, coming to git from Subversion, and over the weekend we ran in to a situation with a branch in our repository where commits were made to the public version of a branch that we didn't want there. We had:

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

And then got the bad commits to put the branch at:

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

C and D should never have been on that branch. The trouble is this branch was "closed" -- this was a released version of our software and there shouldn't have been any new commits to this branch.

In Subversion the only way out of this sort of situation was to commit !D and !C so you end up with:

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

Which gets me back to B but keeps me moving forward on the timeline for the branch so anyone with a remote of the branch who syncs with the master repository would get C and D and then have them undone to end up at a logically similar version of B (but not B -- call it B').

I came across this solution for reverting commits in git which seemed ideal: it would put our public repository back to A -> B. But it meant that any clone of this branch out on anyone's working machine would be very incorrect and everyone would need to re-clone. My fix amounted to:

```<code>git checkout thebranch
git reset --hard <<commit # associated with commit B>>
git push --force
</code>```

I ended up going the route of the above link and it caused quite the stir that:

a) You can throw away commit history at the public repository with git like this, literally re-writing commit reality;

b) Everyone had to re-clone so they wouldn't risk re-injecting C -> D on to the branch (or the new branch of that branch that we wanted to create).

I think I should have done:

```<code>git revert HEAD~2
git commit
git push
</code>```

But this would have left the branch as A -> B -> C -> D -> E and it really shouldn't have C -> D -> E on it because it's supposed to be closed.

I've got three questions:

How could I have handled the clean up better? Use revert instead of reset? What's the best practice here for branch pollution?

Did the push --force of the reverted branch really destroy the history at the public repository? Or did git roll back to B but keep a record of C -> D and that a revert was done back to B at some point by me? It definitely doesn't show the revert in the commit log, but maybe a record of my action is kept some place else?

How do you handle "closed" branches in git such that these changes couldn't have gotten on there in the first place? We did have a tag applied to the repository at commit B and people are supposed to use the branch + tag to get the source for the release, but this is still a scary thing to have changes show up on a branch line that should not have changes on it after commit B. And someone branching from the branch for a patch release could have easily missed the tag and pulled C -> D in to their new branch as well.

答:
You should use tags for releases ("closed branches") and branches for development ("open branches"). This is both an alternative solution to fixing your problem (you could just use the tag for your released code) and a way to prevent this problem in the future.

While you're developing v3.1 you can have your v3.1 branch. Once v3.1 is complete, tag the last commit and rename the branch to your next development branch (v3.2). Remember: Git is not Svn! A branch is only a pointer to a commit. Deleting a branch doesn't delete the commits (but if those commits are not included in another branch, they'll be dangling so you should make a tag before you delete the branch).

If you want to develop a patch to v3.1 (v3.1.1), then you create a branch at the tag v3.1:

```<code>git checkout -b v3.1.1 v3.1
</code>```

This will be clearer to your developers (branches are for development and tags are for releases) and prevent this issue from coming up again.

Did the push --force of the reverted branch really destroy the history at the public repository?

No. If you had created a tag or branch for commit D, then that branch would still be fine. Use git reflog to see recent changes to the head. Those commits should be in there. (Or git fsck.)

For a good discussion of git that doesn't use other version control systems as a basis for understanding, try PeepCode's Git Internals. It's not free, but I think it's a lot better to understand git apart from centralized version control. (The Git Community Book looks like a good free alternative.)

Body:
We're new to git at my company, coming to git from Subversion, and over the weekend we ran in to a situation with a branch in our repository where commits were made to the public version of a branch that we didn't want there. We had:

A -> B

And then got the bad commits to put the branch at:

A -> B -> C -> D

C and D should never have been on that branch. The trouble is this branch was "closed" -- this was a released version of our software and there shouldn't have been any new commits to this branch.

In Subversion the only way out of this sort of situation was to commit !D and !C so you end up with:

A -> B -> C -> D -> !D -> !C

Which gets me back to B but keeps me moving forward on the timeline for the branch so anyone with a remote of the branch who syncs with the master repository would get C and D and then have them undone to end up at a logically similar version of B (but not B -- call it B').

I came across this solution for reverting commits in git which seemed ideal: it would put our public repository back to A -> B. But it meant that any clone of this branch out on anyone's working machine would be very incorrect and everyone would need to re-clone. My fix amounted to:

git checkout thebranch
git reset --hard <<commit # associated with commit B>>
git push --force

I ended up going the route of the above link and it caused quite the stir that:

a) You can throw away commit history at the public repository with git like this, literally re-writing commit reality;

b) Everyone had to re-clone so they wouldn't risk re-injecting C -> D on to the branch (or the new branch of that branch that we wanted to create).

I think I should have done:

git revert HEAD~2
git commit
git push

But this would have left the branch as A -> B -> C -> D -> E and it really shouldn't have C -> D -> E on it because it's supposed to be closed.

I've got three questions:

How could I have handled the clean up better? Use revert instead of reset? What's the best practice here for branch pollution?

Did the push --force of the reverted branch really destroy the history at the public repository? Or did git roll back to B but keep a record of C -> D and that a revert was done back to B at some point by me? It definitely doesn't show the revert in the commit log, but maybe a record of my action is kept some place else?

How do you handle "closed" branches in git such that these changes couldn't have gotten on there in the first place? We did have a tag applied to the repository at commit B and people are supposed to use the branch + tag to get the source for the release, but this is still a scary thing to have changes show up on a branch line that should not have changes on it after commit B. And someone branching from the branch for a patch release could have easily missed the tag and pulled C -> D in to their new branch as well.

Body:
You should use tags for releases ("closed branches") and branches for development ("open branches"). This is both an alternative solution to fixing your problem (you could just use the tag for your released code) and a way to prevent this problem in the future.

While you're developing v3.1 you can have your v3.1 branch. Once v3.1 is complete, tag the last commit and rename the branch to your next development branch (v3.2). Remember: Git is not Svn! A branch is only a pointer to a commit. Deleting a branch doesn't delete the commits (but if those commits are not included in another branch, they'll be dangling so you should make a tag before you delete the branch).

If you want to develop a patch to v3.1 (v3.1.1), then you create a branch at the tag v3.1:

git checkout -b v3.1.1 v3.1

This will be clearer to your developers (branches are for development and tags are for releases) and prevent this issue from coming up again.

Did the push --force of the reverted branch really destroy the history at the public repository?

No. If you had created a tag or branch for commit D, then that branch would still be fine. Use git reflog to see recent changes to the head. Those commits should be in there. (Or git fsck.)

For a good discussion of git that doesn't use other version control systems as a basis for understanding, try PeepCode's Git Internals. It's not free, but I think it's a lot better to understand git apart from centralized version control. (The Git Community Book looks like a good free alternative.)


问:
Not able to reset input field in laravel
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

```<code> <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
</code>```

JS for reset button:

```<code>document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };
</code>```

Reset Button:

```<code><button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
</code>```

答:
So answering my own question, any feedback would be appreciated but this is working.

It turns out that no matter what value="{!! Request::input('app_number') !!}" will always have value as this code gets executed on the server side and unless you make another post request you can not change the value and by using only vanilla JS and without post request this cannot be done.

So, instead of getting values from Request why not just takes the values from user input and save it to local storage and then just grab it and inject into the input field.

I added onkeyup event ion to the input field

```<code><input type="text" name="app_number" class="form-control" onkeyup='saveValue(this);' id="app_number" placeholder="Application Number" required>
</code>```

and JS to store and retrieve input

```<code>document.getElementById("app_number").value = getSavedValue("app_number"); // set the value to this input

function saveValue(e) {
  var id = e.id; // get the sender's id to save it .
  var val = e.value; // get the value.
  localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
      return ""; // You can change this to your defualt value.
  }
  return localStorage.getItem(v);
}
</code>```

and then reset the form as usual

```<code>document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = '';
};
</code>```

Body:
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

 <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>

JS for reset button:

document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };

Reset Button:

<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>

Body:
So answering my own question, any feedback would be appreciated but this is working.

It turns out that no matter what value="{!! Request::input('app_number') !!}" will always have value as this code gets executed on the server side and unless you make another post request you can not change the value and by using only vanilla JS and without post request this cannot be done.

So, instead of getting values from Request why not just takes the values from user input and save it to local storage and then just grab it and inject into the input field.

I added onkeyup event ion to the input field

<input type="text" name="app_number" class="form-control" onkeyup='saveValue(this);' id="app_number" placeholder="Application Number" required>

and JS to store and retrieve input

document.getElementById("app_number").value = getSavedValue("app_number"); // set the value to this input

function saveValue(e) {
  var id = e.id; // get the sender's id to save it .
  var val = e.value; // get the value.
  localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
      return ""; // You can change this to your defualt value.
  }
  return localStorage.getItem(v);
}

and then reset the form as usual

document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = '';
};


问:
Find coordinate of the closest point on polygon in Shapely
Say I have the following Polygon and Point:

```<code>>>> poly = Polygon([(0, 0), (2, 8), (14, 10), (6, 1)])
>>> point = Point(12, 4)
</code>```

I can calculate the point's distance to the polygon...

```<code>>>> dist = point.distance(poly)
>>> print(dist)
2.49136439561
</code>```

...but I would like to know the coordinate of the point on the polygon border where that shortest distance measures to.

My initial approach is to buffer the point by its distance to the polygon, and find the point at which that circle is tangent to the polygon:

```<code>>>> buff = point.buffer(dist)
</code>```

However, I'm not sure how to calculate that point. The two polygon's don't intersect so list(poly.intersection(buff)) will not give me that point.

Am I on the right track with this? Is there a more straightforward method?

答:
While the answer of eguaio does the job, there is a more natural way to get the closest point using shapely.ops.nearest_points function:

```<code>from shapely.geometry import Point, Polygon
from shapely.ops import nearest_points

poly = Polygon([(0, 0), (2, 8), (14, 10), (6, 1)])
point = Point(12, 4)
# The points are returned in the same order as the input geometries:
p1, p2 = nearest_points(poly, point)
print(p1.wkt)
# POINT (10.13793103448276 5.655172413793103)
</code>```

The result is the same as in the other answer:

```<code>from shapely.geometry import LinearRing
pol_ext = LinearRing(poly.exterior.coords)
d = pol_ext.project(point)
p = pol_ext.interpolate(d)
print(p.wkt)
# POINT (10.13793103448276 5.655172413793103)
print(p.equals(p1))
# True
</code>```

Body:
Say I have the following Polygon and Point:

>>> poly = Polygon([(0, 0), (2, 8), (14, 10), (6, 1)])
>>> point = Point(12, 4)

I can calculate the point's distance to the polygon...

>>> dist = point.distance(poly)
>>> print(dist)
2.49136439561

...but I would like to know the coordinate of the point on the polygon border where that shortest distance measures to.

My initial approach is to buffer the point by its distance to the polygon, and find the point at which that circle is tangent to the polygon:

>>> buff = point.buffer(dist)

However, I'm not sure how to calculate that point. The two polygon's don't intersect so list(poly.intersection(buff)) will not give me that point.

Am I on the right track with this? Is there a more straightforward method?

Body:
While the answer of eguaio does the job, there is a more natural way to get the closest point using shapely.ops.nearest_points function:

from shapely.geometry import Point, Polygon
from shapely.ops import nearest_points

poly = Polygon([(0, 0), (2, 8), (14, 10), (6, 1)])
point = Point(12, 4)
# The points are returned in the same order as the input geometries:
p1, p2 = nearest_points(poly, point)
print(p1.wkt)
# POINT (10.13793103448276 5.655172413793103)

The result is the same as in the other answer:

from shapely.geometry import LinearRing
pol_ext = LinearRing(poly.exterior.coords)
d = pol_ext.project(point)
p = pol_ext.interpolate(d)
print(p.wkt)
# POINT (10.13793103448276 5.655172413793103)
print(p.equals(p1))
# True


问:
How to align imageViews which are created dynamically inside a class and not the xml file
My Problem: I want to create a for loop in the onCreate() method to save imageViews dynamically. I am being able to do everything properly it's just that the imageView is displayed at the top left most corner, i.e i am not being able to assign it it's alignment.

My Code:

```<code>RelativeLayout layout = findViewById(R.id.relativeLayout);

    for(int i=0;i<3;i++)
    {
        ImageView image = new ImageView(this);
        image.setMaxHeight(200);
        image.setMaxWidth(200);
        //CODE TO ADD THE ALIGNMENT OF THE IMAGE
        image.setImageResource(R.drawable.red);
        layout.addView(image);
    }
</code>```

答:
The legal values can be found at https://developer.android.com/reference/android/view/View.html#setTextAlignment(int)

But this has no effect on an ImageView.  I'm not sure what you're actually truing to do, so I can't help you.  My best guess is you're trying to arrange views within the parent layout somehow, but to help with that we'd need to know the type of layout the parent is and what you want to do.

Body:
My Problem: I want to create a for loop in the onCreate() method to save imageViews dynamically. I am being able to do everything properly it's just that the imageView is displayed at the top left most corner, i.e i am not being able to assign it it's alignment.

My Code:

RelativeLayout layout = findViewById(R.id.relativeLayout);

    for(int i=0;i<3;i++)
    {
        ImageView image = new ImageView(this);
        image.setMaxHeight(200);
        image.setMaxWidth(200);
        //CODE TO ADD THE ALIGNMENT OF THE IMAGE
        image.setImageResource(R.drawable.red);
        layout.addView(image);
    }


问:
MySQL Trigger update after an insert
What is the right syntax for an update after an insert on a sql trigger?

I am trying:

```<code>    CREATE TRIGGER movimentacoes AFTER INSERT ON
    mov FOR EACH ROW
BEGIN
    UPDATE
        cooperados
    INNER JOIN mov ON mov.id_coop = cooperados.id
    SET
        cooperados.integralizadas = cooperados.integralizadas + mov.valor
    WHERE
        mov.id_coop = cooperados.id
</code>```

I'm building an application with laravel, and this trigger is essential.

答:
Presumably, you intend something like this:

DELIMITER $$

```<code>CREATE TRIGGER movimentacoes AFTER INSERT ON mov
FOR EACH ROW
BEGIN
    UPDATE cooperados c
        SET integralizadas = c.integralizadas + new.valor
    WHERE c.id = new.id_coop;
END;

DELIMITER ;
</code>```

Title: MySQL Trigger update after an insert

Body:
What is the right syntax for an update after an insert on a sql trigger?

I am trying:

    CREATE TRIGGER movimentacoes AFTER INSERT ON
    mov FOR EACH ROW
BEGIN
    UPDATE
        cooperados
    INNER JOIN mov ON mov.id_coop = cooperados.id
    SET
        cooperados.integralizadas = cooperados.integralizadas + mov.valor
    WHERE
        mov.id_coop = cooperados.id

I'm building an application with laravel, and this trigger is essential.

Body:
Presumably, you intend something like this:

DELIMITER $$

CREATE TRIGGER movimentacoes AFTER INSERT ON mov
FOR EACH ROW
BEGIN
    UPDATE cooperados c
        SET integralizadas = c.integralizadas + new.valor
    WHERE c.id = new.id_coop;
END;

DELIMITER ;


问:
JQuery UI click event fires twice on keypress
HTML

```<code><button id="clickMe" tabindex=0>Click Me!</button>
</code>```

JS

```<code>$('#clickMe').button();
$('#clickMe').click(function() {
    alert('hey');
});

$(document).keypress(function (e) {
    var key = e.keyCode ? e.keyCode : e.which;
    //detect when the user has hit enter
    if (key == 13) {
        //click the focused element
        $(document.activeElement).click();
    }
});
</code>```

Why does this alert fire twice when you hit tab to focus the button and enter for the keypress event, but only fires once when you click the button with the mouse?

Demonstration

EDIT:  tab + enter doesn't work at all in IE 10

答:
I know it's an old post but while I was looking for a solution of a nearly identical problem I've found out that the default type of a <button> element is "submit".
This means that if you press Enter anywhere in the <form> containing this button, it will automatically submit.

Actually, if you press enter in any of those two input, the snippet closes. If you define a function to click a button on the Enter keypress event it will trigger twice unless you add a "button"to the button element, because you trigger it both with your function and the automatic submit.

TLDR:
add type="button" to your button element.

$(document).ready(function(){

  $(document).on('click','#submit_type',function(){
    console.log($(this).attr('id'))
  });

  $(document).on('click','#button_type',function(){
    console.log($(this).attr('id'))
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
  <input>
  <button id ="submit_type">Can enter</button>
</form>

<form id="form2">
  <input>
  <button type="button" id="button_type">Cannot enter</button>
</form></code>```

Body:
HTML

<button id="clickMe" tabindex=0>Click Me!</button>

JS

$('#clickMe').button();
$('#clickMe').click(function() {
    alert('hey');
});

$(document).keypress(function (e) {
    var key = e.keyCode ? e.keyCode : e.which;
    //detect when the user has hit enter
    if (key == 13) {
        //click the focused element
        $(document.activeElement).click();
    }
});

Why does this alert fire twice when you hit tab to focus the button and enter for the keypress event, but only fires once when you click the button with the mouse?

Demonstration

EDIT:  tab + enter doesn't work at all in IE 10

Body:
I know it's an old post but while I was looking for a solution of a nearly identical problem I've found out that the default type of a <button> element is "submit".
This means that if you press Enter anywhere in the <form> containing this button, it will automatically submit.

Actually, if you press enter in any of those two input, the snippet closes. If you define a function to click a button on the Enter keypress event it will trigger twice unless you add a "button"to the button element, because you trigger it both with your function and the automatic submit.

TLDR:
add type="button" to your button element.

$(document).ready(function(){

  $(document).on('click','#submit_type',function(){
    console.log($(this).attr('id'))
  });

  $(document).on('click','#button_type',function(){
    console.log($(this).attr('id'))
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
  <input>
  <button id ="submit_type">Can enter</button>
</form>

<form id="form2">
  <input>
  <button type="button" id="button_type">Cannot enter</button>
</form>


问:
Contact Form for my website not working in php
I am trying to make a contact form for my website in php, but it seems something wrong somewhere, which i am unable to locate. Can you please help me to locate the error in the following code will be of great help and suggest further improvement on this. </p>

<p>Will of great help.
Thanks in advance. </p>

```<code><?php
    // Message Vars
    $msg = '';
    $msgClass = '';

    //check for submit
    if (filter_has_var(INPUT_POST, 'submit')) {
        //GET FORM DATA
        $name = htmlspecialchars($_POST['name']);
        $email = htmlspecialchars($_POST['email']);
        $message = htmlspecialchars($_POST['message']);

        // check required fields
        if (!empty($email) && !empty($name) && !empty($message)) {
            // passed
            // check email
            if (filter_var($email, FILTER_VALIDATE_EMAIL)  == false) {
                //failed
                $msg = 'Please use a valid email';
                $msgClass = 'alert-danger';
            } else{
                //passed
                // reciepient email
                $toEmail = 'myemail@gmail.com';
                $subject = 'Contact Request From '.$name;
                $body = '<h2> Contact Request</h2>
                         <h4> Name </h4><p>'.$name.'</p>
                         <h4> Email </h4><p>'.$email.'</p>
                         <h4> Message </h4><p>'.$message.'</p>';

                // email headers
                $headers = "MIME-Version: 1.0"."\r\n";
                $headers .= "Content-Type: text/html;charset=UTF-8" . "\r\n";

                // additional headers
                $headers .= "From:" .$name. "<".$email.">". "\r\n";

                if (mail($toEmail, $subject, $body, $headers)) {
                    // email sent
                    $msg = ' Your email has been sent';
                    $msgClass = 'alert-success';
                }
            }

            # code...
        } else {
            //failed
            $msg = ' Please fill in all fields';
            $msgClass = 'alert-danger';
            // failed

            # code...
        }

        # code...
    }
?>

<!DOCTYPE html>
<html>
<head>
    <title>Contact Us</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container" >
        <?php if ($msg != ''): ?>
            <div class="alert <?php echo $msgClass; ?> "><?php echo $msg; ?></div>
        <?php endif; ?>

        <form method="post"  action="<?php echo $_SERVER['PHP_SELF']; ?>">
            <div class="contact-form" >
                <h1>Contact Us</h1>
                <div class="txtb" >
                    <label>Name</label>
                    <input type="text"
                           name="name"
                           class="form-control"
                           value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
                </div>

                <div class="txtb" >
                    <label>Email</label>
                    <input type="text"
                           name="email"
                           class="form-control"
                           value="<?php echo isset($_POST['email']) ? $email : ''; ?>" >
                </div>

                <div class="txtb" >
                    <label>Message</label>
                    <textarea  name="message" class="form-control"   ><?php echo isset($_POST['message']) ? $message : ''; ?></textarea>
                </div>

                <br>
                <a type="submit" name="submit"  class="btn" >Submit</a>
        </form>
    </div>
</body>
</html>
</code>```

答:
I don't know what type of the error you're seeing but there's a little thing to change

You need to change

```<code> <a type="submit" name="submit"  class="btn" >Submit</a>
</code>```

to

```<code> <input type="submit">
</code>```

OwnerDisplayName: sachin

Body:
I am trying to make a contact form for my website in php, but it seems something wrong somewhere, which i am unable to locate. Can you please help me to locate the error in the following code will be of great help and suggest further improvement on this.

Will of great help.
Thanks in advance.

<?php
    // Message Vars
    $msg = '';
    $msgClass = '';

    //check for submit
    if (filter_has_var(INPUT_POST, 'submit')) {
        //GET FORM DATA
        $name = htmlspecialchars($_POST['name']);
        $email = htmlspecialchars($_POST['email']);
        $message = htmlspecialchars($_POST['message']);

        // check required fields
        if (!empty($email) && !empty($name) && !empty($message)) {
            // passed
            // check email
            if (filter_var($email, FILTER_VALIDATE_EMAIL)  == false) {
                //failed
                $msg = 'Please use a valid email';
                $msgClass = 'alert-danger';
            } else{
                //passed
                // reciepient email
                $toEmail = 'myemail@gmail.com';
                $subject = 'Contact Request From '.$name;
                $body = '
 Contact Request

 Name

'.$name.'

 Email

'.$email.'

 Message

'.$message.'
';

                // email headers
                $headers = "MIME-Version: 1.0"."\r\n";
                $headers .= "Content-Type: text/html;charset=UTF-8" . "\r\n";

                // additional headers
                $headers .= "From:" .$name. "<".$email.">". "\r\n";

                if (mail($toEmail, $subject, $body, $headers)) {
                    // email sent
                    $msg = ' Your email has been sent';
                    $msgClass = 'alert-success';
                }
            }

            # code...
        } else {
            //failed
            $msg = ' Please fill in all fields';
            $msgClass = 'alert-danger';
            // failed

            # code...
        }

        # code...
    }
?>

<!DOCTYPE html>

    <title>Contact Us</title>
    <link rel="stylesheet" href="style.css">

        <?php if ($msg != ''): ?>
            <div class="alert <?php echo $msgClass; ?> "><?php echo $msg; ?>

        <?php endif; ?>

        <form method="post"  action="<?php echo $_SERVER['PHP_SELF']; ?>">

Contact Us

                    Name
                    <input type="text"
                           name="name"
                           class="form-control"
                           value="<?php echo isset($_POST['name']) ? $name : ''; ?>">

                    Email
                    <input type="text"
                           name="email"
                           class="form-control"
                           value="<?php echo isset($_POST['email']) ? $email : ''; ?>" >

                    Message
                    <textarea  name="message" class="form-control"   ><?php echo isset($_POST['message']) ? $message : ''; ?></textarea>

                Submit
        </form>

Body:
I don't know what type of the error you're seeing but there's a little thing to change

You need to change

 <a type="submit" name="submit"  class="btn" >Submit</a>

to

 <input type="submit">


问:
How to load resources from external framework
I have build an external framework, and I am trying to utilize some images which are in the resource directory of the framework. The framework is not being copied within the application but rather just referenced to it. How can I utilize UIImage accordingly from xyz.framework resource folder?

Thanks

答:
Swift 4/5:

```<code>let bundle = Bundle(for: type(of: self))
// let bundle = Bundle(for: ClassOfInterest.self)) // or by pointing to class of interest
let path = bundle.path(forResource: "filename", ofType: "json")!
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
</code>```

This is from inside framework / unit tests, in production code you don't want to force try and force unwrap.

Body:
Swift 4/5:

let bundle = Bundle(for: type(of: self))
// let bundle = Bundle(for: ClassOfInterest.self)) // or by pointing to class of interest
let path = bundle.path(forResource: "filename", ofType: "json")!
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)

This is from inside framework / unit tests, in production code you don't want to force try and force unwrap.


答:
Try this:

```<code>    Scanner sc = new Scanner(System.in);

    int sum = 0;
    int count = 0;
    int n = 0;

    do {
        System.out.println("Enter next number(-1 to exit): ");
        n = sc.nextInt();
        System.out.println("Value is :" + n);

        if(n != -1)
        {
            count++;
            sum = sum + n;
        }

    }while ( n != -1);

    sc.close();
    System.out.println("Mean is: " + (double) sum/count);
}
</code>```

You needed to move your sc.nextInt(); into the loop so that you can keep entering in values.  I also added an if statement so the -1 does not get used in the mean value.

Title: Arithmetic mean in java

Body:
Try this:

    Scanner sc = new Scanner(System.in);

    int sum = 0;
    int count = 0;
    int n = 0;

    do {
        System.out.println("Enter next number(-1 to exit): ");
        n = sc.nextInt();
        System.out.println("Value is :" + n);

        if(n != -1)
        {
            count++;
            sum = sum + n;
        }

    }while ( n != -1);

    sc.close();
    System.out.println("Mean is: " + (double) sum/count);
}

You needed to move your sc.nextInt(); into the loop so that you can keep entering in values.  I also added an if statement so the -1 does not get used in the mean value.


问:
What Java ORM do you prefer, and why?
It's a pretty open ended question.  I'll be starting out a new project and am looking at different ORMs to integrate with database access.

Do you have any favorites?
Are there any you would advise staying clear of?

答:
While I share the concerns regarding Java replacements for free-form SQL queries, I really do think people criticizing ORM are doing so because of a generally poor application design.

True OOD is driven by classes and relationships, and ORM gives you consistent mapping of different relationship types and objects.
If you use an ORM tool and end up coding query expressions in whatever query language the ORM framework supports (including, but not limited to Java expression trees, query methods, OQL etc.), you are definitely doing something wrong, i.e. your class model most likely doesn't support your requirements in the way it should. A clean application design doesn't really need queries on the application level. I've been refactoring many projects people started out using an ORM framework in the same way as they were used to embed SQL string constants in their code, and in the end everyone was suprised about how simple and maintainable the whole application gets once you match up your class model with the usage model. Granted, for things like search functionality etc. you need a query language, but even then queries are so much constrained that creating an even complex VIEW and mapping that to a read-only persistent class is much nicer to maintain and look at than building expressions in some query language in the code of your application. The VIEW approach also leverages database capabilities and, via materialization, can be much better performance-wise than any hand-written SQL in your Java source.
So, I don't see any reason for a non-trivial application NOT to use ORM.

OwnerDisplayName: Mike

ContentLicense: CC BY-SA 2.5

Title: What Java ORM do you prefer, and why?


问:
Styling echarts - Cannot modify title color
Looking to work with the below chart, but cannot get to change the title color to white and the axis and axis numbers to grey (or white). This should go above a dark background. Does anybody knows how to change the title color with echarts ?</p>

```<code><script type="text/javascript">
              // based on prepared DOM, initialize echarts instance
              var myChart = echarts.init(document.getElementById('main'));

              // specify chart configuration item and data
              var option = {
                  title: {
                      text: 'Total memebers of the club',
                      fontColor: 'white',
                      display: true,
                      position: 'bottom'

                  },
                  tooltip: {},
                  legend: {
                      data: ['Total member']
                  },
                  xAxis: {

                      data: ["11/2018", "12/2018", "01/2019", "02/2019", "03/2019", "04/2019"]
                  },
                  yAxis: {},
                  series: [{
                      itemStyle: {normal: {color: 'white'}},
                      name: 'Total',
                      type: 'bar',
                      data: [5, 384, 612, 2344, 4670, 9372]
                  }]
              };

              // use configuration item and data specified to show chart
              myChart.setOption(option);
          </script>
</code>```

答:
Give this a try.  Add it under 'text:' like:</p>

```<code>text: 'Total memebers of the club',
textStyle: {
    color: '#ed2d2e'
    }
</code>```

Body:
Give this a try.  Add it under 'text:' like:

text: 'Total memebers of the club',
textStyle: {
    color: '#ed2d2e'
    }


问:
How to convert a List[List[Long]] to a List[List[Int]]?
What's the best way to convert a List[List[Long]] to a List[List[Int]] in Scala?

For example, given the following list of type List[List[Long]]

```<code>val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
</code>```

how can it be converted to List[List[Int]]?

答:
Try l.map(_.map(_.toInt)) like so

```<code>val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
l.map(_.map(_.toInt))
</code>```

which should give

```<code>res2: List[List[Int]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
</code>```

Body:
What's the best way to convert a List[List[Long]] to a List[List[Int]] in Scala?

For example, given the following list of type List[List[Long]]

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))

how can it be converted to List[List[Int]]?

Body:
Try l.map(_.map(_.toInt)) like so

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
l.map(_.map(_.toInt))

which should give

res2: List[List[Int]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))


问:
Authorizing by different schemes by area using conventions in Razor Pages
My Razor Pages application is structured like this:

Pages

Index.cshtml

Areas

Admin

Pages

Index.cshtml

Api

Pages

Index.cshtml

I want to allow anonymous access to any non-area page (anything in /Pages/). I want to use Windows Authentication for all pages in the Admin area and authorization via a bearer token for all pages in the Api.

I can do this using Authorize attributes directly on the PageModels and specifying the scheme.

//Non-area example
[AllowAnonymous]
public class IndexModel : PageModel
```

<pre class="lang-cs prettyprint-override"><code>//Admin example
[Authorize(AuthenticationSchemes = "Windows")]
public class IndexModel : PageModel
</code>```

//API example
[Authorize(AuthenticationSchemes = "ApiKey")]
public class IndexModel : PageModel
```

<p>Then I can create a base PageModel for each of the 3 areas and inherit all PageModels for each area from the respective base PageModel.</p>

<p>Is there a way to accomplish this same thing using conventions?</p>

<pre class="lang-cs prettyprint-override"><code>services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.???
    })
</code>```

答:
I've solved it. The trick is an AuthorizeFilter can include schemes with a constructor overload.

var authorizeFilter = new AuthorizeFilter(new List<IAuthorizeData> {
    new AuthorizeAttribute()
    {
        AuthenticationSchemes = authenticationSchemes
    }
});
```

<p>Then I had to write my own IPageApplicationModelConvention that will apply at the area level. The default methods work at folder and page levels. I used the source code from Microsoft.AspNetCore.Mvc.RazorPages as a guide.</p>

<pre class="lang-cs prettyprint-override"><code>public class AreaModelConvention : IPageApplicationModelConvention
{
    private readonly string _areaName;
    private readonly Action<PageApplicationModel> _action;

    public AreaModelConvention(string areaName, Action<PageApplicationModel> action)
    {
        _areaName = areaName;
        _action = action;
    }

    public void Apply(PageApplicationModel model)
    {
        if(string.Equals(_areaName, model.AreaName, StringComparison.OrdinalIgnoreCase))
        {
            _action(model);
        }
    }
}
</code>```

I wrote some PageConventionCollectionExtensions which is how this is all done in Microsoft.AspNetCore.Mvc.RazorPages.

public static class PageConventionCollectionExtensions
{
    public static PageConventionCollection RequireAuthenticationSchemesForArea(this PageConventionCollection conventions, string areaName, string authenticationSchemes)
    {
        if (conventions == null)
        {
            throw new ArgumentNullException(nameof(conventions));
        }

        if (string.IsNullOrEmpty(areaName))
        {
            throw new ArgumentException(nameof(areaName));
        }

        var authorizeFilter = new AuthorizeFilter(new List<IAuthorizeData> {
            new AuthorizeAttribute()
            {
                AuthenticationSchemes = authenticationSchemes
            }
        });

        conventions.AddAreaModelConvention(areaName, model => model.Filters.Add(authorizeFilter));
        return conventions;
    }

    public static IPageApplicationModelConvention AddAreaModelConvention(this ICollection<IPageConvention> pageConventions, string areaName, Action<PageApplicationModel> action)
    {
        if (action == null)
        {
            throw new ArgumentNullException(nameof(action));
        }

        var convention = new AreaModelConvention(areaName, action);

        pageConventions.Add(convention);

        return convention;
    }
}
```

<p>Finally I can register it all:</p>

<pre class="lang-cs prettyprint-override"><code>services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AllowAnonymousToNonareas();
        options.Conventions.RequireAuthenticationSchemesForArea("Admin", "Windows");
        options.Conventions.RequireAuthenticationSchemesForArea("Api", "ApiKey");
    })
</code>```

Note: The code for AllowAnonymousToNonareas is not defined here but it is very similar. I created a NonareaModelConvention with this Apply method:

```<code>public void Apply(PageApplicationModel model)
{
    if (model.AreaName == null)
    {
        _action(model);
    }
}
</code>```

and wrote similar extension methods to tie it together.

Remember to turn on both anonymous authentication and windows authentication for the app.

Body:
My Razor Pages application is structured like this:

Pages

Index.cshtml

Areas

Admin

Pages

Index.cshtml

Api

Pages

Index.cshtml

I want to allow anonymous access to any non-area page (anything in /Pages/). I want to use Windows Authentication for all pages in the Admin area and authorization via a bearer token for all pages in the Api.

I can do this using Authorize attributes directly on the PageModels and specifying the scheme.

//Non-area example
[AllowAnonymous]
public class IndexModel : PageModel

//Admin example
[Authorize(AuthenticationSchemes = "Windows")]
public class IndexModel : PageModel

//API example
[Authorize(AuthenticationSchemes = "ApiKey")]
public class IndexModel : PageModel

Then I can create a base PageModel for each of the 3 areas and inherit all PageModels for each area from the respective base PageModel.

Is there a way to accomplish this same thing using conventions?

services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.???
    })

Body:
I've solved it. The trick is an AuthorizeFilter can include schemes with a constructor overload.

var authorizeFilter = new AuthorizeFilter(new List<IAuthorizeData> {
    new AuthorizeAttribute()
    {
        AuthenticationSchemes = authenticationSchemes
    }
});

Then I had to write my own IPageApplicationModelConvention that will apply at the area level. The default methods work at folder and page levels. I used the source code from Microsoft.AspNetCore.Mvc.RazorPages as a guide.

public class AreaModelConvention : IPageApplicationModelConvention
{
    private readonly string _areaName;
    private readonly Action<PageApplicationModel> _action;

    public AreaModelConvention(string areaName, Action<PageApplicationModel> action)
    {
        _areaName = areaName;
        _action = action;
    }

    public void Apply(PageApplicationModel model)
    {
        if(string.Equals(_areaName, model.AreaName, StringComparison.OrdinalIgnoreCase))
        {
            _action(model);
        }
    }
}

I wrote some PageConventionCollectionExtensions which is how this is all done in Microsoft.AspNetCore.Mvc.RazorPages.

public static class PageConventionCollectionExtensions
{
    public static PageConventionCollection RequireAuthenticationSchemesForArea(this PageConventionCollection conventions, string areaName, string authenticationSchemes)
    {
        if (conventions == null)
        {
            throw new ArgumentNullException(nameof(conventions));
        }

        if (string.IsNullOrEmpty(areaName))
        {
            throw new ArgumentException(nameof(areaName));
        }

        var authorizeFilter = new AuthorizeFilter(new List<IAuthorizeData> {
            new AuthorizeAttribute()
            {
                AuthenticationSchemes = authenticationSchemes
            }
        });

        conventions.AddAreaModelConvention(areaName, model => model.Filters.Add(authorizeFilter));
        return conventions;
    }

    public static IPageApplicationModelConvention AddAreaModelConvention(this ICollection<IPageConvention> pageConventions, string areaName, Action<PageApplicationModel> action)
    {
        if (action == null)
        {
            throw new ArgumentNullException(nameof(action));
        }

        var convention = new AreaModelConvention(areaName, action);

        pageConventions.Add(convention);

        return convention;
    }
}

Finally I can register it all:

services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AllowAnonymousToNonareas();
        options.Conventions.RequireAuthenticationSchemesForArea("Admin", "Windows");
        options.Conventions.RequireAuthenticationSchemesForArea("Api", "ApiKey");
    })

Note: The code for AllowAnonymousToNonareas is not defined here but it is very similar. I created a NonareaModelConvention with this Apply method:

public void Apply(PageApplicationModel model)
{
    if (model.AreaName == null)
    {
        _action(model);
    }
}

and wrote similar extension methods to tie it together.

Remember to turn on both anonymous authentication and windows authentication for the app.


答:
Only if you are completely sure that you won't overflow the Int.

```<code>val l1: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
val l2: List[List[Int]] = l1.map(list => list.map(long => long.toInt))
</code>```

(Basically, every time you want to transform a List into another List, use map).

Title: How to convert a List[List[Long]] to a List[List[Int]]?

Body:
Only if you are completely sure that you won't overflow the Int.

val l1: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
val l2: List[List[Int]] = l1.map(list => list.map(long => long.toInt))

(Basically, every time you want to transform a List into another List, use map).


问:
In python-docx how do I delete a table row?
I can't figure out how to delete a table row in python-docx. Specifically, my tables come in with a header row and a row that has a special token stored in the text of the first cell. I search for tables with the token and then fill in a bunch of rows of the table. But how do I delete row 1, which has the token, before adding new rows?
I tried

table.rows[1].Delete()
and
table.rows = table.rows[0:1]

The first one fails with an unrecognized function (the documentation refers to this function in the Microsoft API, but I don't know what that means).
The second one fails because table.rows is read-only, as the documentation says.

So how do I do it?

答:
This functionality is not built-in, which really shocks me. As I search forums I find many people asking for this over the last five years. However, a workaround exists and here it is:

def remove_row(table, row):
    tbl = table._tbl
    tr = row._tr
    tbl.remove(tr)

row = table.rows[n]
remove_row(table, row)
```