text:
Q: Pass a data.frame column name to a function I'm trying to write a function to accept a data.frame (x) and a column from it. The function performs some calculations on x and later returns another data.frame. I'm stuck on the best-practices method to pass the column name to the function.
The two minimal examples fun1 and fun2 below produce the desired result, being able to perform operations on x$column, using max() as an example. However, both rely on the seemingly (at least to me) inelegant

*

*call to substitute() and possibly eval()

*the need to pass the column name as a character vector.

fun1 <- function(x, column){
  do.call("max", list(substitute(x[a], list(a = column))))
}

fun2 <- function(x, column){
  max(eval((substitute(x[a], list(a = column)))))
}

df <- data.frame(B = rnorm(10))
fun1(df, "B")
fun2(df, "B")

I would like to be able to call the function as fun(df, B), for example. Other options I have considered but have not tried:

*

*Pass column as an integer of the column number. I think this would avoid substitute(). Ideally, the function could accept either.

*with(x, get(column)), but, even if it works, I think this would still require substitute

*Make use of formula() and match.call(), neither of which I have much experience with.

Subquestion: Is do.call() preferred over eval()?

A: Personally I think that passing the column as a string is pretty ugly. I like to do something like:
get.max <- function(column,data=NULL){
    column<-eval(substitute(column),data, parent.frame())
    max(column)
}

which will yield:
> get.max(mpg,mtcars)
[1] 33.9
> get.max(c(1,2,3,4,5))
[1] 5

Notice how the specification of a data.frame is optional. you can even work with functions of your columns:
> get.max(1/mpg,mtcars)
[1] 0.09615385

A: Another way is to use tidy evaluation approach. It is pretty straightforward to pass columns of a data frame either as strings or bare column names. See more about tidyeval here.
library(rlang)
library(tidyverse)

set.seed(123)
df <- data.frame(B = rnorm(10), D = rnorm(10))

Use column names as strings
fun3 <- function(x, ...) {
  # capture strings and create variables
  dots <- ensyms(...)
  # unquote to evaluate inside dplyr verbs
  summarise_at(x, vars(!!!dots), list(~ max(., na.rm = TRUE)))
}

fun3(df, "B")
#>          B
#> 1 1.715065

fun3(df, "B", "D")
#>          B        D
#> 1 1.715065 1.786913

Use bare column names
fun4 <- function(x, ...) {
  # capture expressions and create quosures
  dots <- enquos(...)
  # unquote to evaluate inside dplyr verbs
  summarise_at(x, vars(!!!dots), list(~ max(., na.rm = TRUE)))
}

fun4(df, B)
#>          B
#> 1 1.715065

fun4(df, B, D)
#>          B        D
#> 1 1.715065 1.786913
#>

Created on 2019-03-01 by the reprex package (v0.2.1.9000)

A: This answer will cover many of the same elements as existing answers, but this issue (passing column names to functions) comes up often enough that I wanted there to be an answer that covered things a little more comprehensively.
Suppose we have a very simple data frame:
dat <- data.frame(x = 1:4,
                  y = 5:8)

and we'd like to write a function that creates a new column z that is the sum of columns x and y.
A very common stumbling block here is that a natural (but incorrect) attempt often looks like this:
foo <- function(df,col_name,col1,col2){
      df$col_name <- df$col1 + df$col2
      df
}

#Call foo() like this:
foo(dat,z,x,y)

The problem here is that df$col1 doesn't evaluate the expression col1. It simply looks for a column in df literally called col1. This behavior is described in ?Extract under the section "Recursive (list-like) Objects".
The simplest, and most often recommended solution is simply switch from $ to [[ and pass the function arguments as strings:
new_column1 <- function(df,col_name,col1,col2){
    #Create new column col_name as sum of col1 and col2
    df[[col_name]] <- df[[col1]] + df[[col2]]
    df
}

> new_column1(dat,"z","x","y")
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12

This is often considered "best practice" since it is the method that is hardest to screw up. Passing the column names as strings is about as unambiguous as you can get.
The following two options are more advanced. Many popular packages make use of these kinds of techniques, but using them well requires more care and skill, as they can introduce subtle complexities and unanticipated points of failure. This section of Hadley's Advanced R book is an excellent reference for some of these issues.
If you really want to save the user from typing all those quotes, one option might be to convert bare, unquoted column names to strings using deparse(substitute()):
new_column2 <- function(df,col_name,col1,col2){
    col_name <- deparse(substitute(col_name))
    col1 <- deparse(substitute(col1))
    col2 <- deparse(substitute(col2))

    df[[col_name]] <- df[[col1]] + df[[col2]]
    df
}

> new_column2(dat,z,x,y)
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12

This is, frankly, a bit silly probably, since we're really doing the same thing as in new_column1, just with a bunch of extra work to convert bare names to strings.
Finally, if we want to get really fancy, we might decide that rather than passing in the names of two columns to add, we'd like to be more flexible and allow for other combinations of two variables. In that case we'd likely resort to using eval() on an expression involving the two columns:
new_column3 <- function(df,col_name,expr){
    col_name <- deparse(substitute(col_name))
    df[[col_name]] <- eval(substitute(expr),df,parent.frame())
    df
}

Just for fun, I'm still using deparse(substitute()) for the name of the new column. Here, all of the following will work:
> new_column3(dat,z,x+y)
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12
> new_column3(dat,z,x-y)
  x y  z
1 1 5 -4
2 2 6 -4
3 3 7 -4
4 4 8 -4
> new_column3(dat,z,x*y)
  x y  z
1 1 5  5
2 2 6 12
3 3 7 21
4 4 8 32

So the short answer is basically: pass data.frame column names as strings and use [[ to select single columns. Only start delving into eval, substitute, etc. if you really know what you're doing.

A: You can just use the column name directly:
df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
  max(x[,column])
}
fun1(df, "B")
fun1(df, c("B","A"))

There's no need to use substitute, eval, etc.
You can even pass the desired function as a parameter:
fun1 <- function(x, column, fn) {
  fn(x[,column])
}
fun1(df, "B", max)

Alternatively, using [[ also works for selecting a single column at a time:
df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
  max(x[[column]])
}
fun1(df, "B")

A: With dplyr it's now also possible to access a specific column of a dataframe  by simply using double curly braces {{...}} around the desired column name within the function body, e.g. for col_name:
library(tidyverse)

fun <- function(df, col_name){
   df %>%
     filter({{col_name}} == "test_string")
}

A: As an extra thought, if is needed to pass the column name unquoted to the custom function, perhaps match.call() could be useful as well in this case, as an alternative to deparse(substitute()):
df <- data.frame(A = 1:10, B = 2:11)

fun <- function(x, column){
  arg <- match.call()
  max(x[[arg$column]])
}

fun(df, A)
#> [1] 10

fun(df, B)
#> [1] 11

If there is a typo in the column name, then would be safer to stop with an error:
fun <- function(x, column) max(x[[match.call()$column]])
fun(df, typo)
#> Warning in max(x[[match.call()$column]]): no non-missing arguments to max;
#> returning -Inf
#> [1] -Inf

# Stop with error in case of typo
fun <- function(x, column){
  arg <- match.call()
  if (is.null(x[[arg$column]])) stop("Wrong column name")
  max(x[[arg$column]])
}

fun(df, typo)
#> Error in fun(df, typo): Wrong column name
fun(df, A)
#> [1] 10

Created on 2019-01-11 by the reprex package (v0.2.1)
I do not think I would use this approach since there is extra typing and complexity than just passing the quoted column name as pointed in the above answers, but well, is an approach.

A: Tung's answer and mgrund's answer presented tidy evaluation. In this answer I'll show how we can use these concepts to do something similar to joran's answer (specifically his function new_column3). The objective to this is to make it easier to see the differences between base evaluation and tidy one, and also to see the different syntaxes that can be used in tidy evaluation. You will need rlang and dplyr for this.
Using base evaluation tools (joran's answer):
new_column3 <- function(df,col_name,expr){
  col_name <- deparse(substitute(col_name))
  df[[col_name]] <- eval(substitute(expr),df,parent.frame())
  df
}

In the first line, substitute is making us evaluate col_name as an expression, more specifically a symbol (also sometimes called a name), not an object. rlang's substitutes can be:

*

*ensym - turns it into a symbol;

*enexpr - turns it into a expression;

*enquo - turns it into a quosure, an expression that also points the environment where R should look for the variables to evaluate it.

Most of the time, you want to have that pointer to the environment. When you don't specifically need it, having it rarely causes problems. Thus, most of the time you can use enquo. In this case, you can use ensym to make the code easier to read, as it makes it clearer what col_name is.
Also in the first line, deparse is turning the expression/symbol into a string. You could also use as.character or rlang::as_string.
In the second line, the substitute is turning expr into a 'full' expression (not a symbol), so ensym is not an option anymore.
Also in the second line, we can now change eval to rlang::eval_tidy. Eval would still work with enexpr, but not with a quosure. When you have a quosure, you don't need to pass the environment to the evaluation function (as joran did with parent.frame()).
One combination of the substitutions suggested above might be:
new_column3 <- function(df,col_name,expr){
  col_name <- as_string(ensym(col_name))
  df[[col_name]] <- eval_tidy(enquo(expr), df)
  df
}

We can also use the dplyr operators, which allow for data-masking (evaluating a column in a data frame as a variable, calling it by its name). We can change the method of transforming the symbol to character + subsetting df using [[ with mutate:
new_column3 <- function(df,col_name,expr){
  col_name <- ensym(col_name)
  df %>% mutate(!!col_name := eval_tidy(enquo(expr), df))
}

To avoid the new column to be named "col_name", we anxious-evaluate it (as opposed to lazy-evaluate, the default of R) with the bang-bang !! operator. Because we made an operation to the left hand side, we can't use 'normal' =, and must use the new syntax :=.
The common operation of turning a column name into a symbol, then anxious-evaluating it with bang-bang has a shortcut: the curly-curly {{ operator:
new_column3 <- function(df,col_name,expr){
  df %>% mutate({{col_name}} := eval_tidy(enquo(expr), df))
}

I'm not an expert in evaluation in R and might have done an over simplification, or used a wrong term, so please correct me in the comments. I hope to have helped in comparing the different tools used in the answers to this question.

A: If you are trying to build this function within an R package or simply want to reduce complexity, you can do the following:
test_func <- function(df, column) {
  if (column %in% colnames(df)) {
    return(max(df[, column, with=FALSE]))
  } else {
    stop(cat(column, "not in data.frame columns."))
  }
}

The argument with=FALSE "disables the ability to refer to columns as if they are variables, thereby restoring the "data.frame mode" (per CRAN documentation). The if statement is a quick way to catch if the column name provided is within the data.frame. Could also use tryCatch error handling here.


text:
Q: Google Script - onEdit(e) not triggering I have a google sheet with some script running behind it.  I've had to separate some of the tabs out to individual workbooks, and have been updating the script accordingly.  One of the functions I had was an onEdit(e) trigger, that was no longer running in the new workbook.  As part of my testing, I've simplified it to just:
function onEdit(e) {
  Logger.log("TEST");
}

No matter the changes I make in the sheet this is attached to, the Logger.log never writes.
I've done some research, especially into the simple trigger restrictions, and one of those relates to openByURL, which I am using elsewhere in the script.
var otherBook = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/etcetc/edit');

Even though the onEdit(e) doesn't directly relate, is the presence of the openByUrl within the script what is preventing the onEdit(e) from running?  If so, are there ways to get around that, so that I can trigger actions based on an edit, but also be able to pull data from an alternate workbook?

A: I inserted the following into a new script and the onEdit(e) worked without an issue. To call functions from onEdit that are restricted for simple triggers, install the trigger instead and set it to fire on spreadsheet edit.

function onEdit(e) {
  Logger.log("TEST2");
}

function test() {
  var otherBook = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/etcetc/edit');
}

A: Regarding the Logger, can you try:
Logger.log(["TEST"]); instead of Logger.log("TEST");
Your login line does not work for me either but works with the brackets.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React toastify toast appears 4 times with every single call I recently started using react-toastify and everything worked fine until I noticed this odd behavior.
Here is my code:
this.adderrorNotification('Error: Please try again!')
adderrorNotification(message){
 toast.error(message, {
   onClose: () => console.log('called when I close')
 });
}

Up on toast onClose I see the log message 4 times.
and up on manual close click the toast re-appears 4 times.
Why is this happening ? Any help Thanks

A: Answering my own question:
Cause: Initialized the toast in all my components which was causing the issue. (Sidebar, Navbar, Main component, Footer) which is making that render 4 times.
Solution: Removing the toast initialization in all components and initialized it in the index.js solved my issue.


text:
Q: How to change Gtk3 StackSwitcher Controls' Alignment I'd like to use a Gtk3 Stack Switcher as my layout container and was just wondering if it is,by any means,possible to change the control buttons' alignment to say VERTICAL because by default they are shown in a  row and they are horizontally aligned
PS:I want to change the alignment of the controls themselves not the contents of the stack

A: Yes, it is possible. Gtk.StackSwitcher implements the Gtk.Orientable interface and inherits from Gtk.Box
If using glade, there is a combobox in the widget General attributes tab which allows choosing the orientation.
You can also do it programmatically, using the Gtk.Orientable method set_orientation:
...
stack_switcher = Gtk.StackSwitcher()
stack_switcher.set_stack(stack)
stack_switcher.set_orientation(Gtk.Orientation.VERTICAL)
...

Let's take the Python Gtk+ 3 Stack and StackSwitcher tutorial example and change the stack switcher orientation:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class StackWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Stack Demo")
        self.set_border_width(10)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(vbox)

        stack = Gtk.Stack()
        stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)
        stack.set_transition_duration(1000)

        checkbutton = Gtk.CheckButton("Click me!")
        stack.add_titled(checkbutton, "check", "Check Button")

        label = Gtk.Label()
        label.set_markup("<big>A fancy label</big>")
        stack.add_titled(label, "label", "A label")

        stack_switcher = Gtk.StackSwitcher()
        stack_switcher.set_stack(stack)
        stack_switcher.set_orientation(Gtk.Orientation.VERTICAL)
        vbox.pack_start(stack_switcher, True, True, 0)
        vbox.pack_start(stack, True, True, 0)

win = StackWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

The expected result is:

a vertical Gtk.StackSwitcher.

A: @Jose Fonte,thanks bro....i took your advice and tried to use it,After a while though,I descovered something else that was way easier to fix my problem.A Gtk.StackSideBar.So i ended up using that as this is exactly what i was after


text:
Q: What are the benefits of contributing to open source projects? A year ago I was a big fan of .NET. I was developing custom applications on demand and it was not hard to understand how you can live by doing this kind of job - the customer asks you to make a custom application, you arrange the price, do the job and earn money.
Now I hear more and more people talking about open source projects and collective intelligence which seems a great concept to contribute something to the innovation. But of course as a full-time employee it is hard to find time to work for free and I don't understand what are other benefits of contributing to open source projects beside personal satisfaction.
I would be very thankful if you could explain how the contribution to the open source project could be paid off.
Thanks.

A: As far as employability is concern? Street cred.
Peer-interviewers often take (varying degrees of) stock in a fellow programmer's contribution to open source projects, especially if you're at a junior level.  It shows self-motivation, proactive-ness, ability to work in distributed teams, proof that you've actually used some sort of version control, etc.

A: One other reason: Suppose you use version 1.4 of an open source product and want a feature added to it. You add it on your own copy and do not contribute back to the open source version. When version 1.5 is released with a lot of other goodies that you would love to have, you will again need to patch up 1.5 with your required feature. If you had contributed back and it went into the open source version, you will not have this maintenance problem.

A: For me to work as in open source projects has the following advantages:

*

*Make you learn more

*Shows to the world your development skills

*Make you a reference in a specific subject or for a group of people

*Give a good impression about you that you work with development because you love it. Love enough to spend your free time on a free project

*It can become a product in the future or with a "key module" or plugins that a user must pay for it

*One more time: make you learn more, specially if you are doing a project without relation with your "daily job"

A: For personal use, many people want to contribute to the open source because they use so much themselves. And the only way they can use open source is if people contribute to it. Also if people want a feature added, they can help others by giving it away.
For many companies, creating open source software means they can benefit largely from additions made by other people, while still getting the software they need.
Also there is the great amount of personal experience, and a good item on your CV that helps.
However, in the end, most open source projects are run/created by people that do it make the software they work on better, to help others.

A: Contributing to open source shows that you like software development, not just the salary - that can make you more interesting to a prospective employer.

A: Here's my reasons:
Why I spend so much time working on an Opensource project
And my views about the differences between paid jobs and working on open source projects might also be interesting here.

A: You might also ask, what are the benefits of giving or volunteering for a charity?
In terms of getting paid, some companies employ people to work on open source projects, full time.  But the vast majority of minor contributions will see no direct monetary payback, apart from knowing that the software has been improved for everyone using it.  Of course, things such as reputation can be built, you learn more skills and potential employers can see your work, but these in themselves will not necessary equal a monetary payback.
If you write you own software and open-source is you can still sell it, and sell support services for it (e.g. helplines, support, paper manuals, custom programming)  This is a common business model for open source companies.

A: There are a few benefits to working on open source projects. I'll be brief here and allow you to work out the detail as you go.

*

*Experience. You'll get to use some stuff you probably won't get to use in your day job.

*Fun. It will be a project you've chosen, so you can enjoy it a bit more.

*Freedom. There will probably be less rules about what you can use and how funky you can make things (within reason)

*You Need It! You'll probably choose a product that you have some need for but you want to contribute to the features.

Just because something is open source, doesn't mean it isn't "commercially viable". For example, you might charge for the service of installing, configuring and guiding a client who uses the application and the fact that the software is open source is a big selling point. You don't make money from license fees, you make money from consultancy.

A: Help to improve code
You can get all updates to you software. You can find out pitfalls and defects in your code if someone else edited some functionality in your code.
Added functionality
Any one can add functionality to your software. By this you will be aware of what all things you missed in the design and can contribute to your future software development.

A: You might like to try reading The Cathedral and the Bazaar, by Eric S Raymond (a big open source contributor). It's a very good overview of the history of the open source movement, how it works and where it might be going, written in an informal and approachable style. I'm pretty familiar with the ins and outs of open source (my husband's last two jobs have been in open source based companies) but I still learnt a lot from it.

A: *

*you will be listed as contributors in the project website (if any) and this is great because you can tell your clients that you are the contributor of that open source product. It would add value to you.

*it would be good for your portofolio/resume if you are involved in open source project in the past / present.

*for fun. you help eagerly to make a better software for yourself and others. it also fun to see your open source project grows and being used by many companies.

*experience that you would have for being work together as team. also you can learn from others how to code.


text:
Q: Bounds for $\frac{\sigma(q^k)}{2\sigma(q^{k-1})}$ in terms of $q$ and $k$ If $q$ is a prime number and $k$ is a positive integer, does the following double-sided inequality hold?

$$\frac{q}{2} + \frac{q - 1}{2q^k} < \frac{\sigma(q^k)}{2\sigma(q^{k-1})} \leq \frac{q}{2} + \frac{1}{2q^{k-1}}$$

Here, $\sigma(x)$ is the classical sum of divisors of the positive integer $x$.
MY ATTEMPT
Since $\sigma(q^k) = q^k + \sigma(q^{k-1})$, then we have
$$\frac{\sigma(q^k)}{2\sigma(q^{k-1})}=\frac{q^k + \sigma(q^{k-1})}{2\sigma(q^{k-1})}=\frac{q}{2}\cdot\frac{q^{k-1}}{\sigma(q^{k-1})}+\frac{1}{2}=\frac{q}{2}\cdot\frac{1}{I(q^{k-1})}+\frac{1}{2},$$
where $I(x)=\sigma(x)/x$ is the abundancy index of $x$.
I also know that
$$1 \leq I(q^{k-1}) < \frac{q}{q-1}.$$
Alas, this is where I get stuck.

A: We have $\dfrac{\sigma(q^k)}{\sigma(q^{k-1})}=\dfrac{q^{k+1}-1}{q^k-1}=q+\color{blue}{\dfrac{q-1}{q^k-1}}$ and $$\frac{q-1}{q^k}<\color{blue}{\dfrac{q-1}{q^k-1}}\leqslant\frac{q-1}{q^k-q^{k-1}}=\frac{1}{q^{k-1}}.$$


text:
Q: How to see, what's *really* going on in a query execution? In SQL Server 2008, I would like to examine what is really going on behind the scenes when a query is executed. Can I somehow see the following?

*

*The number of (and maybe even the content of) the log records "produced" by a query.

*When the contents of the log is actually applied to the real data structures. For example:

*

*when are new rows actually added to the (clustering) index structure?

*and did the update/insertion imply a B-tree re-organization (and if so, how large part of that B-tree (how many pages) were affected in that)? Hmm, maybe I should have posted a separate question about this...

*Number of buffer misses/hits for each accessed table.

*The contents of the buffer (which, or how many, pages from the table are currently in the buffer)?

BTW: I considered splitting this question up in multiple smaller questions, but I guess they are somewhat quite related.

A: Here is a simple demo script to start your journey into learning about the SQL Server Internals.  To see the individual actions of a query go to Paul Randal's SQLSkills Blog.
Other posts on this blog will cover topics like DBCC PAGE which will allow you to see the contents of the PAGE and DBCC IND which will show you the allocation maps for tables/indexes.  I recommend reading a copy of Microsoft SQL Server 2008 Internals which covers all of these topics in detail.
Transaction Log Records Demo Script
For the two Selects the misses are shown as the physical reads and read-ahead reads, these are the reads from disk into the buffer pool.  The query engine then uses these pages and this is the logical reads.  So for the io stats on the warm select it has no physical reads or read-ahead reads so all the pages required where already in the the buffer pool.
/* -- Cleanup Script
USE master
DROP DATABASE ExampleDB
*/
SET NOCOUNT ON
SET STATISTICS IO OFF
GO
CREATE DATABASE ExampleDB
GO
USE ExampleDB
GO
-- Force a CHECKPOINT to CLEAR the Transaction Log
CHECKPOINT
GO
-- Show Empty Transaction Log
SELECT * FROM fn_dblog(NULL,NULL)
GO
-- CREATE SIMPLE TABLE
CREATE TABLE NewTable
(
    A   int identity NOT NULL PRIMARY KEY,
    B   char(8000) NOT NULL DEFAULT ('')
)
GO
-- Show Transaction Log With CREATE TABLE records
SELECT * FROM fn_dblog(NULL,NULL)
GO
-- Force a CHECKPOINT to CLEAR the Transaction Log
CHECKPOINT
GO
PRINT 'INSERT Start'
GO
INSERT  NewTable
VALUES (DEFAULT)
GO 1000
PRINT 'INSERT End'
GO
-- Show Transaction Log With INSERT records
SELECT * FROM fn_dblog(NULL,NULL)
GO
-- Turn On IO Statistics (these appear in the messages tab)
SET STATISTICS IO ON
GO
-- Force a CHECKPOINT to CLEAR the Transaction Log and modified buffer pages
CHECKPOINT
GO
-- DROP CLEAN BUFFERS to empty cache
DBCC DROPCLEANBUFFERS
GO
PRINT 'SELECT Start Cold Cache'
GO
SELECT * FROM NewTable
GO
PRINT 'SELECT End Cold Cache'
GO
PRINT 'SELECT Start Warm Cache'
GO
SELECT * FROM NewTable
GO
PRINT 'SELECT End Warm Cache'
GO
-- Force a CHECKPOINT to CLEAR the Transaction Log
CHECKPOINT
GO
DROP TABLE NewTable
-- Show Transaction Log With DROP TABLE records
SELECT * FROM fn_dblog(NULL,NULL)
GO

For the contents of the buffer pool the starting point is this DMV
SELECT      *
FROM        sys.dm_os_buffer_descriptors

A: You have the options of SQL Profiler and viewing a stored procedure execution plan.


text:
Q: FileSystemObject: Retrieving folder name from UNC path I don't know how to get the name of a folder in a UNC path with the FileSystemObject object. For example:
From "\\Server\FolderA" I would like to be able to get "FolderA". The method I was hoping would work is "GetBaseName" but it doesn't seem to work when the "IsRootFolder" property is True.
The following procedure:
Public Sub GetUNCFolderName()

    Const stPathA As String = "\\Server\FolderA"
    Const stPathB As String = "\\Server\FolderA\FolderB"

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Debug.Print "---------"
    Debug.Print "Path A: " & stPathA
    Debug.Print "GetAbsolutePathName: " & fso.GetAbsolutePathName(stPathA)
    Debug.Print "GetBaseName        : " & fso.GetBaseName(stPathA)
    Debug.Print "IsRootFolder       : " & fso.GetFolder(stPathA).IsRootFolder

    Debug.Print "---------"
    Debug.Print "Path B: " & stPathB
    Debug.Print "GetAbsolutePathName: " & fso.GetAbsolutePathName(stPathB)
    Debug.Print "GetBaseName        : " & fso.GetBaseName(stPathB)
    Debug.Print "IsRootFolder       : " & fso.GetFolder(stPathB).IsRootFolder

End Sub

Returns this result:
---------
Path A: \\Server\FolderA
GetAbsolutePathName: \\Server\FolderA
GetBaseName        :
IsRootFolder       : True
---------
Path B: \\Server\FolderA\FolderB
GetAbsolutePathName: \\Server\FolderA\FolderB
GetBaseName        : FolderB
IsRootFolder       : False

As you can see "fso.GetBaseName(stPathA)" returns an empty string and "fso.GetBaseName(stPathB)" does not.
I appreciate any ideas you can give me.

A: It's probably not the best solution but I haven't been able to find one using only the FileSystemObject object. At least it's a lap that saves the problem. My solution goes through adding an if statement: If (fso.GetDrive(fso.GetDriveName(PathA)).DriveType = Network) And fso.GetFolder(PathA).IsRootFolder Then
Public Sub GetUNCFolderName()

    Dim PathA As String, PathB As String
    PathA = "\\Server\FolderA"
    PathB = "\\Server\FolderA\FolderB"
    Const Network = 3

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    If (fso.GetDrive(fso.GetDriveName(PathA)).DriveType = Network) And fso.GetFolder(PathA).IsRootFolder Then
        If VBA.Right$(PathA, 1) = "\" Then PathA = VBA.Left$(PathA, Len(PathA) - 1)
        Debug.Print "PathA-1: " & VBA.Mid$(PathA, InStrRev(PathA, "\") + 1)
    Else
        Debug.Print "PathA-2: " & fso.GetBaseName(PathA)
    End If

    If (fso.GetDrive(fso.GetDriveName(PathB)).DriveType = Network) And fso.GetFolder(PathB).IsRootFolder Then
        If VBA.Right$(PathB, 1) = "\" Then PathB = VBA.Left$(PathB, Len(PathB) - 1)
        Debug.Print "PathB-1: " & VBA.Mid$(PathB, InStrRev(PathB, "\") + 1)
    Else
        Debug.Print "PathB-2: " & fso.GetBaseName(PathB)
    End If

End Sub

Returns
PathA-1: FolderA
PathB-2: FolderB


text:
Q: Limit of products in $L^p(\mathbb R^d)$ Fix $1 \leq p < \infty$. If $f_n \to f$ in $L^p(\mathbb R^d)$, $g_n \to g$ pointwise, and $\| g_n \|_{\infty} \leq M < \infty$ for all $n$, prove that $f_ng_n \to fg$ in $L^p(\mathbb{R}^d)$.
Clearly, what I want to do is bound $\|f_ng_n - fg \|_p$. My problem is how. I tried to split this difference using the Minkowski inequality, but then I get a lower bound, so that doesn't really help me. What should I bound this from above with? Another approach I was playing around with was to write $\| f_ng_n - fg \|_p \leq \|f_nM - fM \|_p = M\|f_n - f\|_p$, and proceed from there, but I'm not sure if this is actually accurate, and in particular how to justify it if it is accurate. Any help will be appreciated!

A: Not exactly, you need to separate like: $f_ng_n-fg=(f_n g_n-fg_n)+(fg_n-fg)$, for the first part, take $g_n$ out with the sup norm then $f_n \to f$ in $L_p$. For the second part, use dominated convergence theorem, when $g_n$ approaches $g$, $|fg_n-fg|<2M|f|$ which is the bound function.


text:
Q: ActionScript: Can I start learning ActionScript directly from As3 I need to learn ActionScript. I have no basic knowledge on ActionScript. Can I directly start learning ActionScript3 or I have to start with ActionScript1. please guide me along with some tutorials.
Thanks.....

A: ActionScript 1 and ActionScript 2 are rather unrelated and obsolete languages for Flash Player. If you're targeting Flash Player >= 9 (I suppose so) the knowledge of AS1 and AS2 can confuse you.
So you can learn AS3 from scratch without any knowledge of AS1 and AS2. It is the most preferable way for now.

A: You can learn AS3 directly.
this is a good website that I have used for tutorials
http://www.republicofcode.com/tutorials/flash/

A: Sure you can. There are a number of tutorials/books on AS3. Please google for them. AS3 Cookbook and Programming AS3 from Adobe are two good resources on AS3.

A: it's actually better to start with learning ActionScript 3.0 since it's quite different than ActionScript 2.0 in many aspects not knowing it you won't have to unlearn all that has changed.
they are practically different languages.


text:
Q: Square root of the second derivative operator Let $p>1$ and $X=L^p(a,b)$ be the space of $L^p$-integrable functions on $(a,b)$ and consider the operator
$A f = f''$ with domain $D(A)=W^{2,p}(a,b)\cap W^{1,p}_0(a,b)$. Now, my question is : can we say that the square root $(-A)^\frac{1}{2}$ coincides with the first derivative on $(a,b)$?


text:
Q: Dev Express Grid control auto filter customization How can I customize Dev Express Grid control's (win forms) auto filter text.
For example, how can I change "equals" text to "MyEqualsText"

A: Are you trying to localize the text? If so, this is the official way to do it.

A:  ASPxGridView1.Columns[i].Caption="New Name";


text:
Q: How can we remove a "\" backslash character from a string in java? I've been trying to figure out how we can remove a special character along with its preceding letters within a string.
Let's suppose, there a string with "ABC\n000111". In this case we have to remove the "ABC\" character from the string. So, the result would be n000111.
Can someone help me find the efficient way of doing this?

A: The Java string literal "ABC\n000111" doesn't contain a backslash: \n is a special character sequence, meaning a single character for a (unix) newline.
If you want to replace \n with n, you can do so:
System.out.println("ABC\n000111".replace('\n', 'n'));

If you want to replace everything up to and including the \n with n, you can do so:
System.out.println("ABC\n000111".replaceAll("^.*\n", "n"));


text:
Q: How to find if a text exists on page using selenium If the text exists then click on xyz else click on abc.
I'm using the below if statement:
if(driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/table/tbody/tr[6]/td[2]")).isDisplayed())
{
    driver.findElement(By.linkText("logout")).getAttribute("href");
} else {
    driver.findElement(By.xpath("/html/body/div/div/div/a[2]")).click();
}

Script fails with the following error message:
Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div/div/div/div/div/div/table/tbody/tr[6]/td[2]"}

A: Try this code:
The below code used to check the text presence in the entire web page.
if(driver.getPageSource().contains("your Text"))
{
    //Click xyz
}

else
{
    //Click abc
}

If you want to check the text on a particular web element
if(driver.findElement(By.id("Locator ID")).getText().equalsIgnoreCase("Yor Text"))
{
    //Click xyz
}

else
{
    //Click abc
}

A: First of all, XPaths of this type and byLinkText are really bad locators and will fail frequently. The locators should be descriptive, unique, and unlikely to change. Priority is to use:

*

*ID

*Class

*CSS (better performence than XPath)

*XPath
Then you can use getText() on the element rather than on the entire page (getPageSource()) which is more specific. try catch is also a good practice for isDisplayed() as @Robbie stated, or better yet use FluentWait to find the element:
// Waiting 10 seconds for an element to be present on the page, checking
// for its presence once every 1 second.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(10, SECONDS)
    .pollingEvery(1, SECONDS)
    .ignoring(StaleElementReferenceException.class)
    .ignoring(NoSuchElementException.class)
    .ignoring(ElementNotVisibleException.class)

Then use like so:
wait.until(x -> {
     WebElement webElement = driverServices.getDriver().findElement(By.id("someId"));
     return webElement.getText();
  });

wait.until(x -> {
     WebElement webElement = driverServices.getDriver().findElement(By.id("someOtherId"));
     return webElement.getAttribute("href");
  });

A: Here we can use try ,except function using python web driver. see below the code
webtable=driver.find_element_by_xpath("xpath value")
print webtable.text
try:
   xyz=driver.find_element_by_xpath(("xpath value")
   xyz.click()

except:
   abc=driver.find_element_by_xpath(("xpath value")
   abc.click()

A: You need to wrap the "IsDisplayed" in a try catch.  "IsDisplayed" can only be called if the element exists.
You may want to override the Implicit Time Out as well, else the try/catch will take a long time.

A: Try this below code:-
Assert.assertTrue(driver.getPageSource().contains(textOnThePage));


text:
Q: are anaconda prompt and command prompt same? I have recently installed anaconda and I have found that it comes with anaconda prompt. when I tried to install pip on my windows from its command prompt, it gave a fatal error
C:\Users\Windows 10>C:/Python38/Scripts/pip
Fatal error in launcher: Unable to create process using '"c:\program files\python38\python.exe"  "C:\Python38\Scripts\pip.exe" '

So I tried to install pip using anaconda prompt and to my surprise, it got installed. I still don't know why my window's command prompt didn't work but more than that, can I use anaconda prompt for future use. Are the same? command prompt and anaconda prompt?


text:
Q: TimePicker won't render in design frame of xml I'm trying to use a TimePicker to get a time from the user but for some reason the xml won't render in the design screen and I'm given this error:
Couldn't resolve resource @layout/time_header_label Failed to parse file /Users/Jake/Library/Android/sdk/platforms/android-21/data/res/layout/time_picker_holo.xml
Has anyone else ran into this? Any ideas? I've checked and made sure that all of my build tools were up to date and even downloaded SDK 20 and 19.
Also I have gone to the directory that it references time_picker_holo.xml is indeed there.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:isScrollContainer="true" >

<!--
        <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".AlarmDetailsActivity" >
-->

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context=".AlarmDetailsActivity" >

    <TimePicker
        android:id="@+id/alarm_details_time_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:id="@+id/alarm_details_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/alarm_details_time_picker"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:ems="10"
        android:hint="@string/details_alarm_name" />

    <View
        android:id="@+id/divider2"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_name" />
    <Switch
        android:id="@+id/alarm_details_repeat_weekly"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/divider2"
        android:text="Repeat Weekly"/>

    <View
        android:id="@+id/divider1"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_repeat_weekly" />

    <Switch
        android:id="@+id/alarm_details_repeat_sunday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/divider1"
        android:text="@string/details_sunday"/>

    <Switch
        android:id="@+id/alarm_details_repeat_monday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/alarm_details_repeat_sunday"
        android:text="@string/details_monday"/>

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/alarm_details_repeat_tuesday"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_monday"
        android:layout_below="@+id/alarm_details_repeat_monday"
        android:checked="true"
        android:text="@string/details_tuesday"
        />

    <Switch
        android:id="@+id/alarm_details_repeat_wednesday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_tuesday"
        android:layout_below="@+id/alarm_details_repeat_tuesday"
        android:checked="true"
        android:text="@string/details_wednesday"

        />

    <Switch
        android:id="@+id/alarm_details_repeat_thursday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_wednesday"
        android:layout_below="@+id/alarm_details_repeat_wednesday"
        android:checked="true"
        android:text="@string/details_thursday"/>

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/alarm_details_repeat_friday"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_thursday"
        android:layout_below="@+id/alarm_details_repeat_thursday"
        android:checked="true"
        android:text="@string/details_friday"
        />

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/alarm_details_repeat_saturday"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_friday"
        android:layout_below="@+id/alarm_details_repeat_friday"
        android:checked="true"
        android:text="@string/details_saturday"
        />

    <View
        android:id="@+id/divider4"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_repeat_saturday" />

    <LinearLayout
        android:id="@+id/alarm_ringtone_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/divider4"
        android:background="@drawable/view_touch_selector"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/alarm_label_tone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:text="@string/details_alarm_tone"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/alarm_label_tone_selection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:text="@string/details_alarm_tone_default"
            android:textSize="14sp" />
    </LinearLayout>

    <View
        android:id="@+id/divider3"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_ringtone_container" />
</RelativeLayout>

A: Other people also have this issue: See here
As the link suggests, a workaround is to lower your rendering api to 19.This stackoverflow answer shows how to do it.

A: As specify in this link it is solved in api 22. Try to update your androidManifest.xml file after install Android 5.1.1 (Api 22) with the sdk manager


text:
Q: How to convert special characters into html entities? I want to convert, in python, special characters like "%$!&@á é ©" and not only '<&">' as all the documentation and references I've found so far shows. cgi.escape doesn't solve the problem.
For example, the string "á ê ĩ &" should be converted to "á ê ĩ &".
Does anyboy know how to solve it?
I'm using python 2.6.

A: You could build your own loop using the dictionaries you can find in http://docs.python.org/library/htmllib.html#module-htmlentitydefs
The one you're looking for is htmlentitydefs.codepoint2name

A: I found a built in solution searching for the htmlentitydefs.codepoint2name that @Ruben Vermeersch said in his answer. The solution was found here: http://bytes.com/topic/python/answers/594350-convert-unicode-chars-html-entities
Here's the function:
def htmlescape(text):
    text = (text).decode('utf-8')

    from htmlentitydefs import codepoint2name
    d = dict((unichr(code), u'&%s;' % name) for code,name in codepoint2name.iteritems() if code!=38) # exclude "&"
    if u"&" in text:
        text = text.replace(u"&", u"&")
    for key, value in d.iteritems():
        if key in text:
            text = text.replace(key, value)
    return text

Thank you all for helping! ;)


text:
Q: Xcode 5 How to go to Repositories window? In previous XCode versions(4) I was able to click on Xcode and it would have
Source Control -> Repositories
Now they have moved Source Control as a new drop down menu but it does not have Repositories part where I could check my SVN and see all other projects.
Is there a way to open Repositories window?

A: Create New Project  then check Source Control

then Menu Bar -> Source Control

New Accounts preferences pane for managing Apple IDs, repositories, and continuous integration servers New Features in Xcode 5

A: With XCode 5, all repository management must be done by project.
Under the Source Control menu, choose the master working copy, then the Configure <project>... submenu. You will get to a dialog with three tabs. The second tab, Remotes, allows to add an existing remote to your project or create a new one.
For example, I usually create an empty GIT repository at my remote server, then I create the XCode project con local GIT repository, add the ssh://<server>/<project> remote address to the above project configuration, and then, the firs time I push the project, XCode connects to the remote repository, verifies that it is empty, and offers to push to the repository, creating it.


text:
Q: Order by in Linq with Web Api 2.0 I have a controller which retrieves the orders from db, the controllers receives 4 query strings: _page,_perPage,_sortDir and _sortField, my problem is in the sort direction, ASC or DESC dunno why but linq seems to ignore the order I give it to.
First I order by the orderId cause I cannot use the skip method without ordering it, then when I try to order it I cannot do it. What am I doing wrong? Thanks.
My controller:
public async Task<HttpResponseMessage> GetOrder(int _page, int _perPage,string _sortDir,string _sortField) {

            var order = await db.Order.Select(x => new {
                OrderId = x.OrderId,
                UserId = x.UserId,
                orderStatusCode = x.orderStatusCode
                ---------------
                More Code Not Important
                --------------

                }
            }).OrderBy(x => x.OrderId).Skip((_page - 1) * _perPage).Take(_perPage).ToListAsync();
            switch (_sortDir) {
                case "ASC":
                    order.OrderBy(x=>_sortField);
                    break;
                case "DESC":
                    order.OrderByDescending(x => _sortField);
                    break;
                default:
                    order.OrderBy(x=>x.OrderId);
                    break;
            }
            var response = Request.CreateResponse(HttpStatusCode.OK, order);
            response.Headers.Add("X-Total-Count", db.User.Count().ToString());
            return response;
        }

A: The problem (on the surface) is that you're not assigning the re-ordered list anywhere.  OrderBy() doesn't change the list itself, it returns a new IEnumerable that is ordered.  Quickest fix, in your switch-case, change each order.OrderBy(...); to order = order.OrderBy(...);
There may be deeper issues with this question and with this code.  The most obvious being: usually, with a request for alternate ordering in a paged scenario, there is an expectation that the paging is related to the ordering.  However, you have the paging filter with a default ordering, then you order the results.  Note I'm not aware of your actual requirements, but in most cases this will generate serious confusion and user error.


text:
Q: curl command fails with a timeout I'm trying to run the following command on my ubuntu box:
 curl https://install.meteor.com/ | sh

It times out.
I tried to ping the address but it just sits there.
I also tried to ping google.com but again, it just sits there.
I don't think it's a DNS issue... here's the output from the ping:
 me@mydev:/var/www/wtracks$ ping google.com
 PING google.com (74.125.226.134) 56(84) bytes of data.
 ^C
 --- google.com ping statistics ---
 1 packets transmitted, 0 received, 100% packet loss, time 0ms

 me@mydev:/var/www/wtracks$ ping 74.125.226.134
 PING 74.125.226.134 (74.125.226.134) 56(84) bytes of data.

What I've tried so far:
I've opened up my proxy settings in chrome (which is what I'm using right now to surf...) and made sure that I ran the following command in the command line where I'm trying to run curl:
 export http_proxy="http://myproxyservername.net:8080"

Then i retried the ping and curl but neither work.
Any other suggestions?
Thanks.

A: you are tying to use a http_proxy environment variable with HTTPS url https://install.meteor.com/ .
To set your HTTPS proxy use HTTPS_PROXY environment variable  (all upper case)
from manual for curl

Curl reads and understands the following environment variables:
    http_proxy, HTTPS_PROXY, FTP_PROXY


text:
Q: Как написать макрос в ubuntu? У меня имеется 3 .cpp файла, я бы хотел иметь макрос, который отдельно делает сборку каждого файла.
Например, main1.cpp, main2.cpp, main3.cpp  После вызова макроса я бы хотел иметь 3 разных исполняемых файла. Что для этого нужно?


text:
Q: How to create a directory with a slash '/' in its name For example, I want to create a folder named "AC/DC". What should I do?
Dir.mkdir("AC/DC")

will give an error message like this
in `mkdir': No such file or directory @ dir_s_mkdir - AC/DC (Errno::ENOENT)

A: Have you considered using an alternative UNICODE character instead of a standard forward slash?
Perhaps you could use:
'FULLWIDTH SOLIDUS' (U+FF0F)
http://www.fileformat.info/info/unicode/char/ff0f/index.htm
Dir.mkdir("AC/DC")

or
'DIVISION SLASH' (U+2215)
http://www.fileformat.info/info/unicode/char/2215/index.htm
Dir.mkdir("AC∕DC")


text:
Q: making 2 JsonObjectRequests using volley I am using Volley library to handle internet requests.
The problem is I need to make two requests. The first one needed to retrieve an id and then using that id to make the second request and retrieve final data. I don't know how to do it, I used AsyncTask but it didn't work for me.
When I add the second request after the onResponse of the first request, I got this error :
E/Volley: [2365] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException
                                           java.lang.NullPointerException
                                               at java.util.HashMap.putAll(HashMap.java:521)
                                               at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:92)
                                               at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
                                               at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)

A: sounds like you need to create and add the second request only after onResponse is called for the first one, should be too much of an issue


text:
Q: Python 2.7 optparse not reading 2nd flag Can someone help me out here? I'm not sure what I'm doing wrong but I can't seem to get my second option to be read from the command line.
from optparse import OptionParser

parser=OptionParser()
parser.add_option("-s", action="store", type="string", dest="scenario")
parser.add_option("-l", action="store", type="string", dest="logger")
(options, args)=parser.parse_args()

print options.scenario
print options.logger
print options

Print Results
>>python test.py -sfoo -lbar
foo
None
{'logger': None, 'scenario': 'foo'}

Additionally, I cannot put a space in between the flag and argument -sfoo is ok but -s foo is not. It's pretty annoying. Can anyone see what I am doing wrong? Thanks in advance.

A: As @user3757614 suggests in his comment, use argparse instead.
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-s', '--scenario', required=True, dest="scenario")
parser.add_argument('-l', '--logger', required=True, dest="logger")

args = parser.parse_args()

print args
print args.scenario
print args.logger

And in the command line:
$ python test.py -s test1 -l test2
Namespace(logger='test2', scenario='test1')
test1
test2


text:
Q: ASP.Net 403 error when adding new razor .cshtml file type I am working in an environment in which are views are requested via a JQuery viewLoader GET request. I'm trying to port all .html to Razor (.cshtml) and I consistently get 403 errors from the client side when I change the extension on the src property to .cshtml. Note I am doing this because if I keep the request as .html I get a 404 (I thought the cshtml would serve itself as html?) :
var cartContainerScript = <script id='CartContainerTemplate' type='text/html' src='./Views/Home/Carts/ED.cshtml' ></script>

$("body").append(cartContainerScript);
cartTemplate = $("script[id=" + 'CartContainerTemplate' + "]");

   cartContainer.viewloader({
        logLevel: "debug",
        scripts: cartTemplate,
        success: function (resolution) {
               //Do good stuff
        },
        error: function (failedResolution) {
            // 403 occurs @ jquery-1.8.3.min.js:2 -> GET http://application.company.com/Views/Home/Carts/ED.cshtml 403 (Forbidden)
        }
    });

I tried adding a *.cshtml entry in the last line of the below HTTP routing in my Views/Web.config file with no luck:
<httpHandlers>
  <add path="*.aspx;*.ascx" verb="*" type="System.Web.HttpNotFoundHandler"/>
  <remove path="*.view.html" verb="*"  />
  <remove path="Carts\*.html" verb="*"  />
  <remove path="Carts\*.cshtml" verb="*"  />
</httpHandlers>

Is there anyway to serve up the Razor files as html after compilation? Perhaps I am missing something in my web.config?
Thanks for looking!

A: In my case, I have to change <modules> to <modules runAllManagedModulesForAllRequests="true">
<system.webServer>
    ...
    <modules> => <modules runAllManagedModulesForAllRequests="true">
    ...
</system.webServer>

This Web.config is at the root directory, not the one in Views directory.
But still, without IIS settings and Web.Config details, it's hard to tell what would cause this issue.


text:
Q: Android push notification from php server The scenario is I just want to send push notification from from php server to Android device what is exactly done by GCM AND FCM but I don't want to use these services and I want to try this using php web sockets , is it possible? And how to implement this ? Thanks

A: your best bet for php is php Ratchet.
Ratchet is a loosely coupled PHP library providing developers with tools to create real time, bi-directional applications between clients and servers over WebSockets.
Here is a great tutorial to get you started.
https://blog.samuelattard.com/the-tutorial-for-php-websockets-that-i-wish-had-existed/

A: There are many tools out there for websockets in php like Ratchet and Wrench.
But there are many features that FCM does provide and not built in these libraries, So check your requirements.


text:
Q: Disable StringBuilder optimisation in javac When using normal string concatenation in Java, javac will optimise this where it can to use StringBuilder instead (or StringBuffer before Java 5.)
In my case, it'd be incredibly helpful to switch all this off, and just have string concatenation use the bog standard "append" method on String instead. Is this optimisation fully "baked in" to javac, or is there a way to disable it at all?

A: I'm not a javac expert but it seems to be hardcoded in javac in the Gen.java file from line 1793.

A: Take alook at this link its eclipse related but if your using eclipse you may find some configration related to optimizing options like unused local variables and co, hope you will find something helpful.
Alternatively this assembler may help you It takes ASCII descriptions of Java classes, written in a simple assembler-like syntax using the Java Virtual Machine instruction set. It converts them into binary Java class files, suitable for loading by a Java runtime system.


text:
Q: Java: Why am I getting "';' expected" for an if statment the if in the constructor is supposed to check if the input is legal... the compiler does not seem to agree with me, it gives me "';' expected" after the if statment, and I dont get why please help.
public class RGBColor
{
    private int _red,_green,_blue;
    private final int _MAX_INTENSITY = 255,_MIN_INTENSITY = 0;
    /**
     * Constructor for objects of class RGBColor
     */
    public RGBColor()
    {
        _red = 0;
        _green = 0;
        _blue = 0;
    }

    public RGBColor(int red, int green,int blue)
    {

        If ((_red < _MIN_INTENSITY) || (_red > _MAX_INTENSITY) || (_green < _MIN_INTENSITY) || (_green > _MAX_INTENSITY) || (_blue < _MIN_INTENSITY) || (_blue > _MAX_INTENSITY)) \\<<I get the error here
        {
            _red=0;
            _green=0;
            _blue=0;
        }
        else
        {
            _red = red;
            _green = green;
            _blue = blue;
        }
}
}

A: Your "If" has a capital "I" so the compiler thinks you're declaring a type.


text:
Q: How to calculate the center of an n-cube (hypercube) given the minimum values and maximum values in each dimension? I am working with a box-embedding-based method in machine learning, and for a particular problem, I have two objects that are represented as two $n$-cubes in $n$-dimension ($n$ might be $16, 32, 64, ...,$ so the method should be general for an arbitrary $n$). Now I need to compute some heuristics distance between these cubes. Currently, I have the minimum and maximum values on each dimension of each cube. I think that one possible start for me is to calculate the distance between the centers of the cubes. However, I am not sure what the way to proceed is, as I found no reference for calculating the centers of the cubes.

A: As @jjagmath replied, we can think about finding the center in the case of $n = 2$ by finding the average of the coordinates in the two dimensions. Then we use the same idea for higher dimensions.


text:
Q: 3 Array Within a array and find duplicates in those arrays I have 3 arrays within a array
Arr = [[arr1],[arr2],[arr3]]

Now I have to find the duplicates in these arrays ([arr1],[arr2],[arr3])
and store the duplicate values in another array.
Arr2 = [ Duplicate values of arr 1,2,,3 ]

how to do it in JavaScript?

A: This is one of many other solutions you can do
const a = [
[1,1,2,1,3],
[2,1,4,4,5],
[3,1,4,5,1]
];

// flat the two dimensions array to one dimension array
const transformedArray = a.flat();

const unifiedArray = [];
const countDuplicates = [];

// create a new array containing unique values
// you can use the Set(..) object for this too
transformedArray.forEach(elem => {
    if(!unifiedArray.includes(elem)) {
    unifiedArray.push(elem);
  }
});

// start counting
unifiedArray.forEach(elem => {
    const countElem = transformedArray.filter(el => el === elem).length;
  countDuplicates.push({
    element: elem,
    count: countElem
  });
});

// test values
console.log(transformedArray);
console.log(countDuplicates);

A: At first I though to concatenate the arrays into 1 big one, but I assume you want the duplicates that appear in all arrays so:

var arr1 = [1, 2, 3, 4]
var arr2 = [1, 2, 4, 8]
var arr3 = [2, 4, 6, 8]
var duplicates = [];
arr1.forEach(function(item) {
  // you could change the && to || if you want
  if ((arr2.indexOf(item) > -1) && (arr3.indexOf(item) > -1)) {
    duplicates.push(item)
  }
})

console.log("" + duplicates)

A: this is simple solution of your question

const arr1 = [2, 3, 4, 5, 6, 7, 8];
const arr2 = [1, 2, 3, 9];
const arr3 = [11, 2, 3, 12, 13];

const duplicates = arr1.filter((i) => arr2.includes(i) && arr3.includes(i));

console.log(duplicates);


text:
Q: error setting up nginx provisioning on vagrant with virtualbox on Ubuntu I have installed Vagrant and Virtualbox on Ubuntu 16.04 LTS, with apt-get repositories fully updated. I have port forwarding set up for 'guest:80 host:8080', and a bootstrap.sh file requiring Vagrant to install nginx, start the service and create a symlink to /var/www.
Despite having verified that nginx can be installed through the apt-get command, and the all the files exist, I continue to receive, 404 errors relating to the files to be downloaded, file not found errors, and an error claiming that the service nginx does not exist. I have included all relevant outputs and code below.
The output from vagrant for the command,
vagrant up --provision

is as follows:
    Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hashicorp/precise64' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 80 (guest) => 8080 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default:
    default: Guest Additions Version: 4.2.0
    default: VirtualBox Version: 5.1
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => /home/thucydides/website-files
==> default: Running provisioner: shell...
    default: Running: /tmp/vagrant-shell20161213-8723-c2l7wt.sh
==> default: stdin: is not a tty
==> default: Reading package lists...
==> default: Building dependency tree...
==> default: Reading state information...
==> default: The following extra packages will be installed:
==> default:   libgd2-noxpm libjpeg-turbo8 libjpeg8 libxslt1.1 nginx-common nginx-full
==> default: Suggested packages:
==> default:   libgd-tools
==> default: The following NEW packages will be installed:
==> default:   libgd2-noxpm libjpeg-turbo8 libjpeg8 libxslt1.1 nginx nginx-common
==> default:   nginx-full
==> default: 0 upgraded, 7 newly installed, 0 to remove and 66 not upgraded.
==> default: Need to get 276 kB/882 kB of archives.
==> default: After this operation, 2,686 kB of additional disk space will be used.
==> default: Err http://us.archive.ubuntu.com/ubuntu/ precise-updates/main libjpeg-turbo8 amd64 1.1.90+svn733-0ubuntu4.1
==> default:   404  Not Found [IP: 91.189.91.23 80]
==> default: Err http://us.archive.ubuntu.com/ubuntu/ precise-updates/main libxslt1.1 amd64 1.1.26-8ubuntu1.1
==> default:   404  Not Found [IP: 91.189.91.23 80]
==> default: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/libj/libjpeg-turbo/libjpeg-turbo8_1.1.90+svn733-0ubuntu4.1_amd64.deb  404  Not Found [IP: 91.189.91.23 80]
==> default: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/libx/libxslt/libxslt1.1_1.1.26-8ubuntu1.1_amd64.deb  404  Not Found [IP: 91.189.91.23 80]
==> default: E
==> default: :
==> default: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?
==> default: nginx: unrecognized service
==> default: cp:
==> default: cannot create regular file `/etc/nginx/sites-available/default'
==> default: : No such file or directory
==> default: chmod:
==> default: cannot access `/etc/nginx/sites-available/default'
==> default: : No such file or directory
==> default: ln:
==> default: failed to create symbolic link `/etc/nginx/sites-enabled/default'
==> default: : No such file or directory
==> default: nginx: unrecognized service

the code for bootstrap.sh:
#!/usr/bin/env bash

#nginx
sudo apt-get -y install nginx
sudo service nginx start

#set up nginx server
sudo cp /vagrant/.provision/nginx/nginx.conf /etc/nginx/sites-available/default
sudo chmod 644 /etc/nginx/sites-available/default
sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default
sudo service nginx restart

#clean /var/www
sudo rm -Rf /var/www

#symlink /var/www => /vagrant
ln -s /vagrant /var/www

Any assistance you could provide here would be greatly appreciated. Thank you.

A: you should update the repo before running the install with apt-get update
#!/usr/bin/env bash

#nginx
sudo apt-get update
sudo apt-get -y install nginx
sudo service nginx start

#set up nginx server
sudo cp /vagrant/.provision/nginx/nginx.conf /etc/nginx/sites-available/default
sudo chmod 644 /etc/nginx/sites-available/default
sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default
sudo service nginx restart

#clean /var/www
sudo rm -Rf /var/www

#symlink /var/www => /vagrant
ln -s /vagrant /var/www

note you did not specify how you're running the provisioning from Vagrantfile but if you have something as
config.vm.provision "shell", path: "bootstrap.sh"

then the script runs as root and you dont need the sudo part in your script


text:
Q: How to run iterations asynchronously in shell script I have a few .csv files like below.

*

*xyz0900@1#-1637746436.csv

*xxx0900@1#-1637746436.csv

*zzz0900@2#-1637746439.csv

*yyy0900@1#-1637746436.csv

*sss0900@2#-1637746439.csv

I have written a script to perform below tasks:

*

*Get the large file based on the pattern which we have passed as a argument to the script.

*Merge all other files which are having same pattern and create a new file

*Remove duplicate header from new file.

*Move new file to the destination based on the parameter passed as a argument.

Example: I am passing "1637746436@home/dest1,1637746436@home/dest2" as
  a second argument to the script. Below script will fetch the
  pattern(1637746436). Get the bigger file and merge all other
  files(having same pattern) with it. New file will be get created and same will be moved to the destination(home/dest1).

The below script will perform the pattern matching and execution sequentially.
How to make 'for loop iteration' should be executed parallelly? I mean pattern matching of "1637746436@home/dest1,1637746436@home/dest2" should be performed simultaneously(not one after another).
Please help on this.
$merge.sh /home/dummy/17 "1637746436@home/dest1,1637746439@home/dest2"

 #!/bin/bash
 current=`pwd`
 source=$1
 destination=$2
 echo "$destination" | tr "," "\n" > $current/out.txt
 cat out.txt | cut -d "@" -f1 > $current/pattern.txt

 for var in `cat pattern.txt`
 do
 getBiggerfile=$(ls -Sl $source/*$var.csv | head -1)
 cd $source
 getFileName=$(echo $getBiggerfile | cut -d " " -f9-)
 newFileName=$(echo $getFileName | cut -d "@" -f1)
 cat *$var.csv >> $getFileName
 header=$(head -n 1 $getFileName)
(printf "%s\n" "$header";
 grep -vFxe "$header" $getFileName
 ) > $newFileName.csv
 rm -rf *$var.csv
 cd $current

 for var1 in `cat out.txt`
 do
 target=`echo $var1 | cut -d "@" -f2`
 id=$(echo $var1 | cut -c-10)
 if [ $id = $var ]
 then
 mv $newFileName.csv $target
 fi
 done
done

A: The cleanest would be to make the internals of the loop a function, and call the function inside the loop, putting it in the background (child processes), then wait for the background (child) processes to finish:
function do_the_thing(){
    source="$1"
    current="$2"
    var="$3"
    getBiggerfile=$(ls -Sl $source/*$var.csv | head -1)
    cd $source
    getFileName=$(echo $getBiggerfile | cut -d " " -f9-)
    newFileName=$(echo $getFileName | cut -d "@" -f1)
    cat *$var.csv >> $getFileName
    header=$(head -n 1 $getFileName)
    (printf "%s\n" "$header";
       grep -vFxe "$header" $getFileName
    ) > $newFileName.csv
    rm -rf *$var.csv
    cd $current

    for var1 in `cat out.txt`
    do
        target=`echo $var1 | cut -d "@" -f2`
        id=$(echo $var1 | cut -c-10)
        if [ $id = $var ]
        then
            mv $newFileName.csv $target
        fi
    done
}

for var in `cat pattern.txt`
do
    do_the_thing "$source" "$current" "$var" &
done

wait


text:
Q: Django Admin: How do I serialize data and store it in a model so that it can be restored by the user? So what I have so far is a model called Registration and a model called Deleted Registration. I overrode the deleted_selected admin action for Registration so that instead of deleting the query, it would make Deleted Registrations. The thing is, it only saves the most important parts. Registrations have a few foreign keys and one-to-one fields.  Apparently just saving the most important data isn't good enough and we want to serialize all the data in the selected registration models and store it with the deleted registration. This way, when you select a few deleted registrations, you can click on Restore deleted registrations
I'll reiterate what I want so it's a little but more clear: I want to be able to "delete" registrations, where a new deleted registration is created. This way, they can view deleted registrations and, if need be, restore them.
Here is the registration model:
class Registration(models.Model):

    objects = RegistrationManager()

    # Used to identify this object securely in urls without giving the actual primary key
    uuid = models.UUIDField(default=uuid.uuid4, editable=False)

    sibs_event = models.ForeignKey("EventInstance", null=True, blank=True)

    date_registered = models.DateTimeField(auto_now_add=True)

    # sibs event for this registration
    sibs_weekend = models.ForeignKey(SibsWeekend, null=False)

    payment_delegation = models.OneToOneField("PaymentDelegation", null=True, blank=True, related_name="registration", on_delete=models.SET_NULL)

Here is the deleted registration model:
class DeletedRegistration(models.Model):
    """
    Just in case of bugs with purging registrants, store
    important registrant information in this model.
    """
    registrant_name = models.CharField(max_length=100)
    registrant_email = models.EmailField(null=True, blank=True)
    registrant_phone_num = models.CharField(max_length=13, null=True, blank=True)
    delegate_name = models.CharField(max_length=100, null=True, blank=True)
    delegate_email = models.EmailField(null=True, blank=True)
    num_of_participants = models.PositiveSmallIntegerField(null=True, default=1)
    special_event = models.CharField(max_length=100, null=True)

Here is the overridden delete_selected for registrations:
def delete_selected(modeladmin, request, queryset):
        """
        This overrides the defult deleted_selected because we want to gather the data from the registration and create a
        DeletedRegistration object before we delete it.
        """
        for registration in queryset:
            reg = registration.get_registrant()

            if registration.payment_delegation:
                delegate_name = registration.payment_delegation.name
                delegate_email = registration.payment_delegation.email
            else:
                delegate_name = None
                delegate_email = None

            registration_to_delete = DeletedRegistration.objects.create(
                registrant_name = reg.full_name(),
                registrant_email = reg.email,
                registrant_phone_num = reg.phone,
                delegate_name = delegate_name,
                delegate_email = delegate_email,
                # Filtering out people (with True) who couldn't participate in events because we are only interested in the people
                # we had to reserve space and prepare materials for.
                num_of_participants = registration.get_num_party_members(True),
                special_event = registration.sibs_event,
            )
            registration.delete()

I appreciate your help! I just don't know what to do from here; I've been searching online for the ways I can do it but I cant wrap my mind around it. I want to save the serialized registration data as a field in deleted registration so that way I can have an admin action take that field and create a new registration from it.


text:
Q: how can i do a function when radio button is not checked i wrote the below code to check if radio button is not checked do another function .but the code does not work here is my snippet :

$('.multiway').change(function(){
   if ($('.multiway').is(':checked')){
       $("#cityadd").removeClass("multiflight");
    $("#cityadd").addClass("multiflight-checked");
   }
   else{
     if ($('.multiway').not(':checked')){
 $("#cityadd").removeClass("multiflight-checked");
    $("#cityadd").addClass("multiflight");
 }}
});
<!doctype html>

<meta charset="utf-8">

 1 <input type="radio"  class="multiway" name="ways">
    2 <input type="radio"  name="ways">

HELLOO

A: You need to bind the event to the ways input, instead of to the specific buton:
$('input[name="ways"]').change(function(){
   if ($('.multiway').is(':checked')){
       $("#cityadd").removeClass("multiflight");
       $("#cityadd").addClass("multiflight-checked");
   }
   else{
    if ($('.multiway').not(':checked')) {
        $("#cityadd").removeClass("multiflight-checked");
        $("#cityadd").addClass("multiflight");
    }
   }
});

https://jsfiddle.net/6xhcfc56/1/
But you can make things more short and elegant, by adding a value attribute to the form and question it:
HTML:
<input type="radio"  class="multiway" name="ways" value="0">1
<input type="radio"  name="ways" value="1">2

JS:
$('input[name="ways"]').change(function(){
  var val = $(this).val();
  if(val == 0)
    $('#cityadd').removeClass('multiflight')
  else
    $('#cityadd').addClass('multiflight')
});

https://jsfiddle.net/f15LnedL/2/

A:  $('.multiway').change(function(){
     if ($(this).prop('checked')){
    $("#cityadd").removeClass("multiflight");
    $("#cityadd").addClass("multiflight-checked"); }
else{
    $("#cityadd").removeClass("multiflight-checked");
    $("#cityadd").addClass("multiflight");
    }
     });


text:
Q: bbPress sidebar not showing in child theme Twenty Fourteen I followed the instructions here:
https://codex.bbpress.org/layout-and-functionality-examples-you-can-use/#26-creating-a-bbpress-specific-sidebar
This is my code from the child theme:
sidebar.php - https://dpaste.de/pRuO

function.php - https://dpaste.de/8uCg

this is the widget dashboard - https://i.imgur.com/k6KdacU.png

here is the sidebar.php child theme code:

    <?php
        $description = get_bloginfo( 'description', 'display' );
        if ( ! empty ( $description ) ) :
    ?>

<?php echo esc_html( $description ); ?>

    <?php endif; ?>

    <?php if ( has_nav_menu( 'secondary' ) ) : ?>

        <?php wp_nav_menu( array( 'theme_location' => 'secondary' ) ); ?>

    <?php endif; ?>

    <?php if ( is_active_sidebar( 'sidebar-1' ) && !is_bbpress() ) : ?>
    lalala

        <?php dynamic_sidebar( 'sidebar-1' ); ?>

    <?php elseif ( is_active_sidebar( 'bbp-sidebar' ) && is_bbpress() ) : ?>
    mamama

        <?php dynamic_sidebar( 'bbp-sidebar' ); ?>

    <?php else : ?>
    hahaha
    <?php endif; ?>

It is executing the "lalala" condition in my domain.com/forum page.
I am using a child theme for Twenty Fourteen.
How can I enable the forum bbpress sidebar (on the right and not replace the original sidebar)? Here is my forum website http://harta.net/forum if you need to check it
UPDATE:
the condition below are both false, why is that ?
is_active_sidebar( 'bbp-sidebar' ) = false
is_bbpress() = fase


text:
Q: variable modified ''at file scope I have a program where I get the error:
variable modified 'artikel'at file scope
char artikel[ARTNAME];

I think I have to add a #define, but I don't understand exactly which one.
Here is my Code:
#include <stdio.h>
#include <string.h>

const int ARTNAME = 100;

typedef struct artikel {
    char artikel[ARTNAME];
    int anzahl;
} artikel;

int main()
{
}

A:
I have a program where I get the error: variable modified 'artikel'at file scope char artikel[ARTNAME];

I don't think you have copied the diagnostic accurately.  It is surely complaining about struct artikel being variably modified.
That is closely related to the issue covered in Variably modified array at file scope in C.  Specifically, const qualification notwithstanding, ARTNAME is not a "constant expression" in C, so the type of array artikel.artikel and therefore also of the whole struct artikel are "variably modified".  Objects with variably modified types cannot be declared at file scope.

I think I have to add a #define, but I don't understand exactly which one.

The quickest solution would probably be to change this ...

    const int ARTNAME = 100;

... to:
#define ARTNAME 100


text:
Q: Ubuntu 18.04 does not wake up from the lock screen I have recently installed a fresh copy of ubuntu 18.04 on a dell alienware 15 R4. Unfortunately, whenever I let the screen go black on the lock screen (or just lock my computer), there is no way of waking it up again. I have thus far resorted to cutting the power.
Based on other people experiencing similar (?) problems, I've looked through kern.log, which showed absolutely nothing (the last entries before the forced shutdown were from discord, which seems to be spamming entries the entire time it is active).
Also, based on another answer I've disabled USB suspension, which did not make any difference. Neither did enabling "USB wake support" in the BIOS.
Does anyone got a clue what on earth is going on here?

A: I had the same problem on Dell XPS desktop with Nvidia Geforce GTX 1060 running latest Ubuntu 18.04.
After I switched from using X.Org X Server video driver to NVIDIA proprietary driver the problem went away.
Maybe try changing your video driver ?


text:
Q: Insert Checkbox Array into Multiple MySQL table Columns with PHP I am pretty stumped, I thought this would work for sure. I want to insert multiple checkbox values (if selected) into different columns of one table.  I was attempting to do this with a for loop and keeping the naming convention consistent so I could utilize the for loop with the checkbox array. Here is php code:

$connection = new mysqli("localhost","root","","employee_db");
if(isset($_POST['check'])){
    $check = $_POST['check'];
    if($check){
        print_r($check);
    }else{
        echo "nothing checked";
    }

    for($i=0;$i<sizeof($check);$i++){
        $query = "INSERT INTO  `checklist_test` (`$check[$i]`) VALUE (`\"$check[$i]\"`)";
        $result = mysqli_query($connection,$query);
        if(!$result){
            die("NOPE <br>" . mysqli_error($connection));
        }else{
            echo "yup";
        }
    }
}

And here is the HTML
<form action="" method="post>
  <input type="checkbox" name="check[]" value="check1">Check1
  <input type="checkbox" name="check[]" value="check2">Check2
  <input type="checkbox" name="check[]" value="check3">Check3
  <input type="submit" value="submit">
</form>

The MySQL Columns are "id, check1, check2, check3" so SQL should look like:
INSERT INTO `checklist_test` (`id`, `check1`, `check2`, `check3`)
VALUES (NULL, 'test', 'test', 'test');

Appreciater outside P.O.V. that I need thanks!

A: If you the execute the query inside the loop, you would be executing x number of queries (or inserting x number of rows) rather than inserting into x number of columns.  There is really no need to use a loop here since you have a set number of columns.
Use echo statements to print out the queries to see what you are running and you'll see why this isn't working.
You also should never put user input directly into a MySQL query.  Read up on SQL injections.


text:
Q: Mouseover range/distance Is there anyway to change default mouseover range? Simple example, I have a map with a bunch o tracks which are 1-2 px wide and are clickable. To click a track and display info you need to click very precisely which can be very annoying. Is there any way to change that tolerance? Just to show what I mean here's my example.
Thanks in advance.
http://members.upcpoczta.pl/w.racek/mapa.html

A: I'm afraid there is not much you can do about that except for upping the weight on your polylines. It's just the way SVG works, precise. What you also can do, to make selecting a polyline less irritating, is dropping the dasharray. It leads to irregular behaviour on hover because the gaps between the lines don't respond to the mouseover. When hovering you'll think you're on the line but you're not, that can also be very frustrating. See this testcase on Plunker and you'll understand: http://plnkr.co/edit/7WPTWN?p=preview
L.polyline([[0, -180],[0, 180]], {
    'dashArray': [10, 50]
})

There is a solution however it's very hacky and performancewise i wouldn't recommend it. For each polyline, add another line, with exactly the same coordinates, make it transparent and set the weight to 10 or more. Hook the mouseovers on the transparent line and use their handlers to change the style of the visible line. Code example:
var visibleLine = L.polyline([[0, -180],[0, 180]], {
    'weight': 2,
    'opacity': 1,
    'dashArray': 3
}).addTo(map);

var transparentLine = L.polyline([[0, -180],[0, 180]], {
    'weight': 10,
    'opacity': 0
})
.on('mouseover', function (e) {
    visibleLine.setStyle({
        'color': 'red',
        'weight': 4,
        'dashArray': 0
    });
})
.on('mouseout', function (e) {
    visibleLine.setStyle({
        color: 'blue',
        'weight': 2,
        'dashArray': 3
    });
})
.addTo(map);

Here's a working example on Plunker: http://plnkr.co/edit/jChoQ0?p=preview


text:
Q: Create list of vectors using rep() I want to create a list which is eight times the vector c(2,6), i.e. a list of 8 vectors.

*

*WRONG: object = as.list(rep(c(2,6),8)) results instead in a list of 16 single numbers: 2 6 2 6 2 6 2 6 ...

*I tried drop=0 but that didn't help, and I can't get lapply to work.

(My context:
I have a function in which a subfunction will call a numbered list object.
The number will be in a loop and therefore change, and the number and loop size is dependent on user values so I don't know what it'll be. If the user doesn't enter a list of vector values for one of the variables, I need to set a default.
The subfunction is expecting e.g. c(2,6)
The subfunction is currently looping 8 times so I need a list which is eight times c(2,6).

A: rep(list(c(2,6)),8) is the answer - thanks to Nicola in comments.


text:
Q: What's the easiest way to parse a string like this into an array without double quotes? Is there a one-liner or something? The string would be in the form of
["abc", "cde", "efg", ... "foo"]

For example:
["CD", "IN", "NN"]

Another example:
["NNS","CC","NNS","IN","JJ","NN",",","NN"]

So the element can be a comma as well.

A: If the string is standard JSON, use Json.NET:
const string json = @"[""Hello"",""World""]";
var jsonObject = JsonConvert.DeserializeObject<dynamic>(json);

foreach (string s in jsonObject)
{
    Console.WriteLine(s);
}

If the string in your question is guaranteed to be a simple JSON array of strings, then the other answers would be a better solution; simply change dynamic to string[], IEnumerable<string> or JArray, depending on your needs.

A: See http://james.newtonking.com/json - there is also a Nuget package for this, which is the first result (for me, anyway) when you search "json".
string json; // Your string.
string[] jsonAsArray = JsonConvert.DeserializeObject<string[]>(json);

A: A one liner? Assuming you're using json.NET, your json is just a string array so the following will do it for you;
string[] myJson = JsonConvert.DeserializeObject<string[]>(jsonString);

A: myString.TrimStart("[\"").TrimEnd("\"]").Split(new string[] { "\",\"", "\" ,\"" }, StringSplitOptions.None);


text:
Q: Angular RxJs - Crud Operations public ngOnInit() {
  this.getUsers();
}

public getUsers() {
  this.userService.getUsers(this.listId).pipe(take(1)).subscribe(data => {
    if (data.result.length) {
      this.users = data.result;
    } else {
      const user = new UserModel();
      this.users = [user];
    }
    this.setupForm();
  });

}

public deleteUser(userId: number) {
  this.userService.delete(this.listId, userId)
    .subscribe(() => this.getUsers())
}

How would you recommand me, when I'm deleting an user from a table, to get back all the users? Is ok to call this.getUsers() method in .subscribe()? Or should I try to call it in .pipe()

A: It depends, if you want to get fresh data from the API every time you delete then you can use switchMap operator from import { filter, map, switchMap } from 'rxjs/operators';
Here is an example of how to use it:
public deleteUser(userId: number): void {
    this.userService
      .delete(this.listId, userId)
      .pipe(switchMap(() => this.userService.getUsers(this.listId)))
      .subscribe((res) => (this.users = res));
  }

Second solution would be removing the delete item from a list of users using javascript splice function:
    public deleteUser(userId: number): void {
            this.userService
              .delete(this.listId, userId)
              .subscribe((res) => {
            const index = this.users.findIndex(u => u.userId === userId);
            if (index > -1) {
                   this.users.aplice(index, 1)
            }
            });
          }

A: I usually create an observable for getting data that updates whenever there's a CRUD operation. Here is a schematic example:
edit$ = this.editClick$
  .pipe(
     switchMapTo(this.latestFormValue$),
     switchMap(formValue => this.api.edit(formValue))
  )

delete$ = this.deleteClick$
  .pipe(
    switchMap(id => this.api.delete(id))
  )

getData$ = merge(this.edit$, this.delete$)
  .pipe(
    switchMap(() => this.api.getData(this.param))
  )

I will also say avoiding imperative and stateful code has been very helpful in reducing complexity and bugs. I only use state in components for the simplest things, such as a component with a single internal variable and one or two actions.
But even seemingly simple things like a breadcrumbs component that has inputs for navigation links have had race conditions that I had to fix by making it more reactive (in that case I got the inputs from route.params instead of the Inputs).
I would also avoid having any sort of body for subscribe. That is what the different operators are there for, and the operators make it clearer what you are intending as well as forcing you to think more reactively. If you really want to make users a state variable (I would recommend making it an observable and subscribing with AsyncPipe), then you should set it in a tap operator to make it obvious that you're introducing a side effect to the observable.
And in fact, if you set it up the way I've shown above and use AsyncPipe, you will not have to subscribe to any of those observables. AsyncPipe will subscribe to getData$ and getData$ will in turn subscribe to edit$ and delete$.


text:
Q: Java - creating a method in BlueJ I have an issue with the following exercise (I'm using BlueJ):
They asked me to make the following method in the class House without making any change to the class Circle

*

*name : getPositionsTwoSuns

*return value : the String described below
description of the string : returns the string of the form "x=12, y=7" from the coordinates of aXPosition and aYPosition of each suns of the picture ;
To separate the positions of the two suns, we can use "|" for example.

Here is a copy of the class House :
public class House
{
private Square    aWall;
private Square    aWindow;
private Triangle aRoof ;
private Circle   aSun;
private Circle   aSun2;

/**
 * Constructor for objects of class House
 */
public House()
{
    this.aWall= new Square();
    this.aWall.changeSize( 100 );
    this.aWindow= new Square();
    this.aWindow.changeColour( "black" );
    this.aRoof= new Triangle();
    this.aRoof.changeSize( 140, 50 );
    this.aSun= new Circle();
    this.aSun.changeColour( "yellow" );
    this.aSun.changeSize( 60 );
    this.aSun2= new Circle();
    this.aSun2.changeColour( "green" );
    this.aSun2.changeSize( 60 );
    this.aWall.MakeVisible();
    this.aWindow.MakeVisible();
    this.aRoof.MakeVisible();
    this.aSun.MakeVisible();
    this.aSun2.MakeVisible();

} // Picture()

/**
 * New function
 */
public String getPositionsTwoSuns()
{
    return "x=aSun.aXPosition y=aSun.aYPosition | x=aSun2.aXPosition y=aSun2.aYPosition";
}

/**
 * Draw this picture.
 */
public void draw()
{
    this.aWall.MakeVisible();
    this.aWindow.MakeVisible();
    this.aRoof.MakeVisible();
    this.aSun.MakeVisible();
    this.aSun2.MakeVisible();
} // draw()
} // House

Here is the Circle class :
import java.awt.geom.Ellipse2D;
public class Circle
{
private int     aDiameter;
private int     aXPosition;
private int     aYPosition;
private String  aColour;
private boolean aIsVisible;

/**
 * Makes a new Circle
 */
public Circle()
{
    this.aDiameter=  30;
    this.aXPosition= 20;
    this.aYPosition= 60;
    this.aColour=   "blue";
    this.aIsVisible= false;
} // Circle()

/**
 * Makes a new circle with the default values
 */
public Circle( final int pDiameter, final int pXPosition, final int pYPosition, final String pColour )
{
    this.aDiameter=  pDiameter;
    this.aXPosition= pXPosition;
    this.aYPosition= pYPosition;
    this.aColour=   pColour;
    this.aIsVisible= false;
} // Circle()

/**
 * Make the Circle visible.
 */
public void MakeVisible()
{
    this.aIsVisible= true;
    this.draw();
} // MakeVisible()
/**
 * New function
 */
public int getPosition()
{
    return 1000*aXPosition+aYPosition;
}
}

I unsuccessfully tried to make the method but once it's compiled, and after creating a new object called house1, the method returns me this :
"x=aSun.aXPosition y=aSun.aYPosition | x=aSun2.aXPosition y=aSun2.aYPosition";

Any help would be appreciated

A: You can use private for all the methods as well as variables and then call the method by creating an object. An object in Java can be created like Circle run = new Circle(); and then call all the private methods like:
run.Circle();
run.MakeVisible();
The object must have the class name and the syntax will be like:
ClassName ObjectName = new ClassName();
and for calling the method the syntax is: Objectname.MethodName();
Make sure the object name are correct for method calling also.
Same object can be used for calling multiple methods. You have to call methods for all methods with the object and it must be placed in:
public static void main()
{
//object creation and all your method calls here
}

Or more specifically the code in main will be like

public static void main()
{
    Circle run = new Circle();
    run.Circle();
    run.MakeVisible();
}

To prevent confusion it is better to change the method name from Circle to another name as the class also has the same name.