When is R's assign() function appropriate?

Question: I often see questions from novice R programmers where they've used assign to create multiple objects, and then run into trouble trying to manipulate those objects for a subsequent task (a recent example).
assign appeals to novice users because it has dynamic properties (programmatically creating variable names, in addition to the variable's values), and seems to mimic some properties of global assignment. Its straightforward name also makes it likely to show up in searches for a variety of problem types.
Of course, more experienced R programmers come to realize that assign creates code that is hard to read, fragile to maintain, and acts via the type of side effects that are otherwise staunchly avoided in the highly functional R language.
Every question I've seen on SO where the OP initially used assign ultimately has a better alternative in the correct use of named vectors, lists, or data frames. The resulting code is easier to follow, more robust to change, and often more performant.
All this is to say, it's easy to find examples of why assign is bad. My question is: in what situations would the use of assign be the appropriate, preferred, or only solution?
Answer: If you were constructing a program that mediated a dialogue with a user wherein the user was asked to input an arbitrary object name (in the specific R sense of an unquoted string that that is listed in a particular namespace), you might consider using assign.
The option to assign to a particular environment may also have value. Notice how it is used in the ecdf function:
ecdf
#----screen output----
function (x)
{
    x <- sort(x)
    n <- length(x)
    if (n < 1)
        stop("'x' must have 1 or more non-missing values")
    vals <- unique(x)
    rval <- approxfun(vals, cumsum(tabulate(match(x, vals)))/n,
        method = "constant", yleft = 0, yright = 1, f = 0, ties = "ordered")
    class(rval) <- c("ecdf", "stepfun", class(rval))
    assign("nobs", n, envir = environment(rval))
    attr(rval, "call") <- sys.call()
    rval
}
<bytecode: 0x7c77cc0>
<environment: namespace:stats>

The ecdf function takes data and returns another function. Most of that function is built with a C call by approxfun, but as a last feature, the ecdf function adds an element to the environment of the returned value (which is yet another function.)
I'm sure you could find other instances where assign is used in the R code of the base and stats packages. Those are arguably "R Core Certified^({TM)}" examples of "proper" uses.
When I followed my own advice I got this from a bash operation:
$ cd '/home/david/Downloads/R-3.5.2/src/library/base/R/'
$ grep -R "assign"
# --- results with a recent download of the R sources -----
userhooks.R:        assign(hookName, new, envir = .userHooksEnv, inherits = FALSE)
datetime.R:    cacheIt <- function(tz) assign(".sys.timezone", tz, baseenv())
autoload.R: assign(".Autoloaded", c(package, .Autoloaded), envir =.AutoloadEnv)
lazyload.R:    ## set <- function (x,  value,  env) .Internal(assign(x,  value,  env,  FALSE))
delay.R:    function(x, value, eval.env=parent.frame(1), assign.env=parent.frame(1))
delay.R:    .Internal(delayedAssign(x, substitute(value), eval.env, assign.env))
assign.R:#  File src/library/base/R/assign.R
assign.R:assign <-
assign.R:    .Internal(assign(x, value, envir, inherits))
# stripped out some occurences of "assighnment"
# stripped out the occurrences of "assign" in the namespace functions
zzz.R:assign("%*%", function(x, y) NULL, envir = .ArgsEnv)
zzz.R:assign("...length", function() NULL, envir = .ArgsEnv)
zzz.R:assign("...elt", function(n) NULL, envir = .ArgsEnv)
zzz.R:assign(".C", function(.NAME, ..., NAOK = FALSE, DUP = TRUE, PACKAGE,
zzz.R:assign(".Fortran",
zzz.R:assign(".Call", function(.NAME, ..., PACKAGE) NULL, envir = .ArgsEnv)
zzz.R:assign(".Call.graphics", function(.NAME, ..., PACKAGE) NULL, envir = .ArgsEnv)
zzz.R:assign(".External", function(.NAME, ..., PACKAGE) NULL, envir = .ArgsEnv)
zzz.R:assign(".External2", function(.NAME, ..., PACKAGE) NULL, envir = .ArgsEnv)
zzz.R:assign(".External.graphics", function(.NAME, ..., PACKAGE) NULL,
zzz.R:assign(".Internal", function(call) NULL, envir = .ArgsEnv)
zzz.R:assign(".Primitive", function(name) NULL, envir = .ArgsEnv)
zzz.R:assign(".isMethodsDispatchOn", function(onOff = NULL) NULL, envir = .ArgsEnv)
zzz.R:assign(".primTrace", function(obj) NULL, envir = .ArgsEnv)
zzz.R:assign(".primUntrace", function(obj) NULL, envir = .ArgsEnv)
zzz.R:assign(".subset", function(x, ...) NULL, envir = .ArgsEnv)
zzz.R:assign(".subset2", function(x, ...) NULL, envir = .ArgsEnv)
zzz.R:assign("UseMethod", function(generic, object) NULL, envir = .ArgsEnv)
zzz.R:assign("as.call", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("attr", function(x, which, exact = FALSE) NULL, envir = .ArgsEnv)
zzz.R:assign("attr<-", function(x, which, value) NULL, envir = .ArgsEnv)
zzz.R:assign("attributes", function(obj) NULL, envir = .ArgsEnv)
zzz.R:assign("attributes<-", function(obj, value) NULL, envir = .ArgsEnv)
zzz.R:assign("baseenv", function() NULL, envir = .ArgsEnv)
zzz.R:assign("browser",
zzz.R:assign("call", function(name, ...) NULL, envir = .ArgsEnv)
zzz.R:assign("class", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("class<-", function(x, value) NULL, envir = .ArgsEnv)
zzz.R:assign(".cache_class", function(class, extends) NULL, envir = .ArgsEnv)
zzz.R:assign("emptyenv", function() NULL, envir = .ArgsEnv)
zzz.R:assign("enc2native", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("enc2utf8", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("environment<-", function(fun, value) NULL, envir = .ArgsEnv)
zzz.R:assign("expression", function(...) NULL, envir = .ArgsEnv)
zzz.R:assign("forceAndCall", function(n, FUN, ...) NULL, envir = .ArgsEnv)
zzz.R:assign("gc.time", function(on = TRUE) NULL, envir = .ArgsEnv)
zzz.R:assign("globalenv", function() NULL, envir = .ArgsEnv)
zzz.R:assign("interactive", function() NULL, envir = .ArgsEnv)
zzz.R:assign("invisible", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.atomic", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.call", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.character", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.complex", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.double", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.environment", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.expression", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.function", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.integer", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.language", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.list", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.logical", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.name", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.null", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.object", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.pairlist", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.raw", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.recursive", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.single", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("is.symbol", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("isS4", function(object) NULL, envir = .ArgsEnv)
zzz.R:assign("list", function(...) NULL, envir = .ArgsEnv)
zzz.R:assign("lazyLoadDBfetch", function(key, file, compressed, hook) NULL,
zzz.R:assign("missing", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("nargs", function() NULL, envir = .ArgsEnv)
zzz.R:assign("nzchar", function(x, keepNA=FALSE) NULL, envir = .ArgsEnv)
zzz.R:assign("oldClass", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("oldClass<-", function(x, value) NULL, envir = .ArgsEnv)
zzz.R:assign("on.exit", function(expr = NULL, add = FALSE, after = TRUE) NULL, envir = .ArgsEnv)
zzz.R:assign("pos.to.env", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("proc.time", function() NULL, envir = .ArgsEnv)
zzz.R:assign("quote", function(expr) NULL, envir = .ArgsEnv)
zzz.R:assign("retracemem", function(x, previous = NULL) NULL, envir = .ArgsEnv)
zzz.R:assign("seq_along", function(along.with) NULL, envir = .ArgsEnv)
zzz.R:assign("seq_len", function(length.out) NULL, envir = .ArgsEnv)
zzz.R:assign("standardGeneric", function(f, fdef) NULL, envir = .ArgsEnv)
zzz.R:assign("storage.mode<-", function(x, value) NULL, envir = .ArgsEnv)
zzz.R:assign("substitute", function(expr, env) NULL, envir = .ArgsEnv)
zzz.R:assign("switch", function(EXPR, ...) NULL, envir = .ArgsEnv)
zzz.R:assign("tracemem", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("unclass", function(x) NULL, envir = .ArgsEnv)
zzz.R:assign("untracemem", function(x) NULL, envir = .ArgsEnv)
zzz.R:     assign(f, fx, envir = env)  # grep fails to include the names of these
zzz.R:        assign(f, fx, envir = env)
zzz.R:        assign(f, fx, envir = env)
zzz.R:        assign(f, fx, envir = env)
zzz.R:        assign(f, fx, envir = env)
zzz.R:    assign("anyNA", fx, envir = env)
zzz.R:assign("!", function(x) UseMethod("!"), envir = .GenericArgsEnv)
zzz.R:assign("as.character", function(x, ...) UseMethod("as.character"),
zzz.R:assign("as.complex", function(x, ...) UseMethod("as.complex"),
zzz.R:assign("as.double", function(x, ...) UseMethod("as.double"),
zzz.R:assign("as.integer", function(x, ...) UseMethod("as.integer"),
zzz.R:assign("as.logical", function(x, ...) UseMethod("as.logical"),
zzz.R:#assign("as.raw", function(x) UseMethod("as.raw"), envir = .GenericArgsEnv)
zzz.R:## assign("c", function(..., recursive = FALSE, use.names = TRUE) UseMethod("c"),
zzz.R:assign("c", function(...) UseMethod("c"),
zzz.R:#assign("dimnames", function(x) UseMethod("dimnames"), envir = .GenericArgsEnv)
zzz.R:assign("dim<-", function(x, value) UseMethod("dim<-"), envir = .GenericArgsEnv)
zzz.R:assign("dimnames<-", function(x, value) UseMethod("dimnames<-"),
zzz.R:assign("length<-", function(x, value) UseMethod("length<-"),
zzz.R:assign("levels<-", function(x, value) UseMethod("levels<-"),
zzz.R:assign("log", function(x, base=exp(1)) UseMethod("log"),
zzz.R:assign("names<-", function(x, value) UseMethod("names<-"),
zzz.R:assign("rep", function(x, ...) UseMethod("rep"), envir = .GenericArgsEnv)
zzz.R:assign("round", function(x, digits=0) UseMethod("round"),
zzz.R:assign("seq.int", function(from, to, by, length.out, along.with, ...)
zzz.R:assign("signif", function(x, digits=6) UseMethod("signif"),
zzz.R:assign("trunc", function(x, ...) UseMethod("trunc"), envir = .GenericArgsEnv)
zzz.R:#assign("xtfrm", function(x) UseMethod("xtfrm"), envir = .GenericArgsEnv)
zzz.R:assign("as.numeric", get("as.double", envir = .GenericArgsEnv),

Comment: its interesting to note that all the examples in `?assign` demonstrate what we could say are bad practice.  Perhaps the help should be rewritten demonstrating some good examples
Comment: The result of a user-entered string is usually a character. If you are trying to create an object with that name (in the R sense of an unquoted value), you need to do something that doesn't use `<-` unless you try to use `eval(parse(text=` and that'e probable even less readable and maintainable.
Comment: Entirely possible that I'm being a little "dynamic" with my terminology. ;)
Comment: Don't agree with your first paragraph: I'd use a list there too. The rest is spot on.
Comment: `ecdf()` is an interesting example. It looks like `assign` is used to place the value of `nobs` into the `rval` environment, `rval` being a dynamic function created from `approxfun`. I'm hard-pressed to think of an alternate way to place a value into a dynamic function, other than refactoring the entire thing to be list-based, which wouldn't be quite the same. So the short answer to "When must you use `assign`?" likely be: "true dynamic programming, which most R users never do directly".
Comment: The other valid use appears to be  constructing other "S3 assignment functions" with "suffixes" of `"...<-"`. Also building "dot functions" and a bunch of `is.*` functions.
Comment: @jdobres It's interesting that you use the term "dynamic programming" since most occurrences of that term in questions on SO that I've seen do apply to the paragraph that you are disagreeing with more so than they apply to the parts you are endorsing . That said, I have always wondered whether "dynamic" had any agreed-upon meaning when applied to programming. It has seemed to be used to indicate a wide variety of paradigms.
Comment: @42- `userinputlist[[objectname]] <- objectvalue`, but I wouldn't even let the user define the object name that is used internally.


variance unchanged under subtracting mean - application in portfolio theory

Question: I'm working through the following passage:

We will be interested in the variance of the portfolio returns given the variances of individual asset's returns. If we have assets with returns $R_1,\ldots,R_n$, held in amounts $X_1,\ldots,X_n$ then we can compute the variance of the portfolio.
  $\newcommand{\myVar}{\operatorname{Var}}$
We proceed by direct computation. We seek the value of
  $$\myVar(R_P) = \myVar\left( \sum_{i=1}^n X_i R_i \right).$$
  We compute
  $$
\begin{align*}
\myVar\left( \sum_{i=1}^n X_i R_i \right)
&= \myVar\left( \sum_{i=1}^n X_i (R_i - \mathbb E(R_i)) \right), \\
&= \mathbb E \left[\left( \sum_{j=1}^n X_j (R_j - E(R_j)) \right)^2\right], \\
&= \mathbb E\left( \sum_{i=1}^n X_i (R_i - \mathbb E(R_i)) \sum_{j=1}^n X_j (R_j - \mathbb E(R_j)) \right), \\
&= \sum_{i,j=1}^n X_i X_j\,\mathbb E(((R_i - \mathbb E(R_i))(R_j - \mathbb E(R_j))).
\end{align*}
$$
  How do we even get the first step?
Comment: is it me or is loading the images taking ages?
Comment: @Lost1 - No, open both image in new tab
Comment: yeah, and it is taking ages to load. might be my computer... i dunno, anyway, i have an answer for you
Answer: The first line is always true. it is a basic property of variances.
Note  $X_i$ are fixed amount assets you wish to hold - i.e.constants
For any random variables $X,Y$, note $Cov(X,Y) = E(X-EX)E(Y-EY)=EX'EY'$, so where $X' = X-EX$ and $Y'=Y-EY$.
Now note $Cov(X',Y') = E(X'-EX')E(Y'-EY')=EX'EY'$, this is because $EX' = EX-E(EX) = 0$ and $EY'=0$
so we have
$Cov(X,Y) = Cov(X-EX, Y-EY)$  (1)
LHS of FIRST LINE = $\sum\limits_{i=1,j=1}^n X_iX_jCov(R_i,R_j)=\sum\limits_{i=1,j=1}^n X_iX_jCov(R_i-ER_i,R_j-ER_j)$ = RHS of FIRST LINE
where the equality in the middle used (1)
Comment: Could you show me which property is for the first line, thank you.


Migrate core data Apps to iCloud

Question: I have an already existing core data apps synchonized by dropbox and I want to migrate on iCloud (with iCloudCoreDataStack).
And have 2 devices ( iPhome and iPad) with the same data inside.
I update the ipad apps to the new apps with icloud, everything work fine and synchonisation works.
Migration code :
<code>// check old if old Db exist

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Livre_de_Cave.sqlite"];

// migrate old persistentStoreCoordinator to icloud and delete it

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {

    NSLog(@"oldURL");

    NSURL* oldStoreURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL];
    [oldStoreURL URLByAppendingPathComponent:@"Livre_de_Cave.sqlite"];
    oldStoreURL =[oldStoreURL URLByAppendingPathComponent:@"Livre_de_Cave.sqlite"];

    NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@YES,
                              NSInferMappingModelAutomaticallyOption:@YES,
                              NSSQLitePragmasOption: @{@"journal_mode": @"DELETE"}
                              };

    NSPersistentStore *store = [self.managedObjectContext.persistentStoreCoordinator  addPersistentStoreWithType:NSSQLiteStoreType

                                                      configuration:nil

                                                                URL:oldStoreURL

                                                            options:options

                                                              error:&error];

 [self.managedObjectContext.persistentStoreCoordinator  migratePersistentStore:store
                                                                         toURL:self.storeURL
                                                                       options:@{ NSPersistentStoreUbiquitousContentNameKey : @"iCloudStore"}
                                                                                withType:NSSQLiteStoreType
                                                                         error:&error];

    //[store removePersistentStore:store error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:oldStoreURL.path error:&error];

} else {

    NSLog(@"newURL");
    [self.managedObjectContext.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                                       configuration:nil
                                                                                URL:self.storeURL
                                                                             options:@{ NSPersistentStoreUbiquitousContentNameKey : @"iCloudStore" }
                                                                               error:&error];

}
</code>
When I update the iphone, all core data entries are duplicates, I under why : I merge and existing store with the icloud store with the same information.
If you have and idea to avoid that ...
Thanks
Answer: Wait for the merge to complete (listening for the Core Data notifications) then check the store to see if the data is already in there.

Migrate core data Apps to iCloud


sorting data from MySQL alphabetically using list & Methods to return sorted list in C#

Question: I'm extracting data from a MySQL database file and load three data items from there into a method called index that extracts Name, surname & Tel Number fields.....main goal is to load all the data in alphabetical order by surname Letter and if two Surnames are matching it should sort them by alphabetical name order.
<code>using Data_Layer;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Business_Logic_Layer
{
    public class BusinessLogic
    {
        public List<PhoneIndex> phoneIndex = new List<PhoneIndex>();

        public void createPhoneIndex()
        {
            string tableName = "customers";

            DataConnection dc = new DataConnection();
            DataSet customers = dc.selectData(tableName);

            foreach (DataRow customer_row in customers.Tables[0].Rows)
            {
                string surname, name, telephone;
                surname = name = telephone = "";

                for (int i = 0; i < customers.Tables[0].Columns.Count; i++)
                {
                    if (customers.Tables[0].Columns[i].ColumnName.StartsWith("contactFirstName"))
                    {
                        name = customer_row.ItemArray[i].ToString();
                    }
                    else if (customers.Tables[0].Columns[i].ColumnName.StartsWith("contactLastName"))
                    {
                        surname = customer_row.ItemArray[i].ToString();
                    }
                    else if (customers.Tables[0].Columns[i].ColumnName.StartsWith("phone"))
                    {
                        telephone = customer_row.ItemArray[i].ToString();
                    }
                }

                // Add the information to the main phoneIndex

                bool added = false;

                PhoneIndexEntry temp_index_entry = new PhoneIndexEntry() { name = name, surname = surname, telephone = telephone };

                for (int i = 0; i < phoneIndex.Count; i++)
                {
                    if (surname.StartsWith(phoneIndex[i].letter))
                    {
                        phoneIndex[i].entries.Add(temp_index_entry);
                        added = true;
                    }
                }

                if (!added)
                {
                    PhoneIndex temp_index = new PhoneIndex() { letter = surname.Substring(0, 1), entries = new List<PhoneIndexEntry>() { temp_index_entry } };
                    phoneIndex.Add(temp_index);
                    added = true;
                }

            }
        } // End of method createPhoneIndex()

        public void sortPhoneIndex()
        {

            // Your code goes here...
            string surname, name;
            surname = name = "";
            List<PhoneIndex> phoneIndex = new List<PhoneIndex>() { };

            PhoneIndexEntry temp_index_entry = new PhoneIndexEntry() { name = name, surname = surname };

            foreach (PhoneIndex index in phoneIndex)//letter, entries sort through letters
            {

                            string[] sortedLetter = new string[1];

                            for (int i = 0; i < phoneIndex.Count - 1; i++)
                            {
                                for (int j = i + 1; j < phoneIndex.Count; j++)
                                {
                                    if (phoneIndex[i].letter.CompareTo(phoneIndex[j].letter) > 0)
                                    {
                                        sortedLetter[0] = phoneIndex[i].letter;
                                        phoneIndex[i].letter = phoneIndex[j].letter;
                                        phoneIndex[j].letter = sortedLetter[0];
                                    }
                                }
                            }
                //if name==name compare surname for sorting
                return;
                        }

                    }//end of foreach

                } // End of method sortPhoneIndex()

        } // End of Class BusinessLogic

        public class PhoneIndex
        {
            public string letter { get; set; }
            public List<PhoneIndexEntry> entries { get; set; }

        } // End of Class PhoneIndex

        public class PhoneIndexEntry
        {
            public string name { get; set; }
            public string surname { get; set; }
            public string telephone { get; set; }

        } // End of Class PhoneIndexEntry

// End of Namespace Business_Logic_Layer
</code>
A =
anthony, adams, 0670510248
B =
bill, adams, 0724677987
bill, crucible, 0687944987
Comment: Are you aware that you can sort data using SQL (ORDER BY)?  Sorting by telephone is somewhat pointless.
Comment: The phone index code works, however the entire sortPhoneIndex method doesn't work and is what i need to work, any help or suggestions would be helpful.
Comment: And if you cannot change your database retrieval logic (that _dc.selectData(tableName);_ hints to a very ugly logic) you can always use the IEnumerable extensions (OrderBy) to order your data very easily
Answer: Assuming that you cannot change the way in which you retrieve your data from the database then this is a job where Linq could help a lot to simplify your code.
<code>// Example data .....
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("surname", typeof(string));
dt.Columns.Add("phone", typeof(string));
dt.Rows.Add("charles", "dickens", "11232");
dt.Rows.Add("mark", "twain", "453446");
dt.Rows.Add("howard", "lovecraft", "875564");
dt.Rows.Add("ernst", "hemingway", "1647567");
dt.Rows.Add("thomas", "mann", "56434");
dt.Rows.Add("isaac", "asimov", "9700");
dt.Rows.Add("aldous", "huxley", "2654");

List<PhoneIndex> phoneIndex = new List<PhoneIndex>();

// Let's enumerate the datatable grouping by first letter in the surname column
var names = dt.AsEnumerable().GroupBy(d => d.Field<string>("surname").Substring(0, 1))
         // foreach group build a sublist with the info from the datarow
         // transformed in a PhoneIndexEntry.
         .Select(g => g.Select(p => new PhoneIndexEntry
         {
             name = p.Field<string>("name"),
             surname = p.Field<string>("surname"),
             telephone = p.Field<string>("phone")

         }));

// Now we have an IEnumerable<IEnumerable> where the first enumerable is a list
// of all distinct first letter from the surname column, while the second
// is an enumerable of PhoneIndexEntry.
// We can loop over the first Enumerable ordering it
// by the first surname's letter and creating a PhoneIndex with all the PhoneIndexEntry for that specific letter
foreach (var entry in names.OrderBy(n => n.First().surname[0].ToString()))
    phoneIndex.Add(new PhoneIndex { letter = entry.First().surname[0].ToString(), entries = entry.OrderBy(s => s.surname).ToList()});
</code>
Side note: It seems that you have a very bad do_it_all method (SelectData) where you pass a table name and you get back all the data from that table.
Surely this is not a good way to query a database and, unless you retrieve very few records, I suggest you to write specific methods for every data extraction or dedicate a bit of time to learn how to use an ORM library.


Send data form using  as button

Question: I want to send data from a form to other php page. Instead of a button in the form I have a  button outside to submit. How can I send the data from the form to the other page? Here is the code:

                <form id="productform" class="form-style-12" action="" method="post">

                </form>

                Ga verder: €0

The
 get filled by products using javascript.
Comment: Basically, what you have is a total disregard for how HTML works, and how javascript should be used. As for the problem you're having, make sure you actually have proper elements in there that has been added by javascript (named inputs, for one), attach an event to the `` when clicked, and serialize the form and use AJAX to push it whereever you need it to go. But seriously, that should be redesigned. First - make the site work without javascript, then add javascript to enhance UX. That there is just a fail before it even began.
Comment: Possible duplicate of [Sending multipart/formdata with jQuery.ajax](http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax)
Comment: set the action attribute of your form to checkout.php and customize the ul to some kind of inputs or get them with js. then submit the form with the outter button with type="submit" as a button attribute.
Answer: A neat solution is to create a  inside the form and style that one.
But you could solve it as you ask:
Submit!

Answer: You can use this

function submitFormData() {
  document.getElementById("yourformid").submit();
}
<button onclick="submitFormdata();">Submit</button>

Send data form using  as button


jQuery dialog is not opening on second click

Question: I am giving the codes in which link inside gridview1 do not work after closing it once

My aspx page code is

    <form id="form1" runat="server">

    <asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" runat="server" AutoGenerateColumns="False"
      DataKeyNames="BusNo"
      DataSourceID="SqlDataSource1">
      <Columns>
        <asp:BoundField DataField="RouteName" HeaderText="RouteName" SortExpression="RouteName" />
        <asp:TemplateField HeaderText="Info">
          <ItemTemplate>
            <div id="divButton" runat="server" class="btn_styling dialog-marker" title="This could also have been a <button> element or maybe an  element...anything really">X

              <asp:GridView ID="GridView2" runat="server"
                AutoGenerateColumns="False"
                DataSourceID="SqlDataSource2">
                <Columns>
                  <asp:BoundField DataField="StopName" HeaderText="StopName" SortExpression="StopName" />

                </Columns>
              </asp:GridView>
              <asp:SqlDataSource ID="SqlDataSource2" runat="server"
                ConnectionString="<%$ ConnectionStrings:constr %>"
                SelectCommand="SELECT StopName from BusStops WHERE (BusNo = @BusNo)">
                <SelectParameters>
                  <asp:Parameter Name="BusNo" />
                </SelectParameters>
              </asp:SqlDataSource>

          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
      <RowStyle BorderColor="Blue" BorderStyle="Solid" BorderWidth="1px" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
      ConnectionString="<%$ ConnectionStrings:constr %>"
      SelectCommand="SELECT BusNo,RouteName from BusRoutes">
    </asp:SqlDataSource>

</form>

and code behind code is

 public void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {

    if (e.Row.RowType == DataControlRowType.DataRow) {
        GridView gv2 = (GridView)e.Row.FindControl("GridView2");
        SqlDataSource sds = (SqlDataSource)e.Row.FindControl("SqlDataSource2");

        sds.SelectParameters["BusNo"].DefaultValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
        gv2.DataBind();
    }
  }

Answer: Try this may work,
$(document).off("click", ".dialog-marker").on("click", ".dialog-marker", function () {
    var d = $(this).next("div").first().dialog(dialogOptions);
    d.dialog("open");
    return false;
});

The .off() method removes event handlers that were attached with .on(). See the discussion of delegated and directly bound events on that page for more information. Calling .off() with no arguments removes all handlers attached to the elements. Specific event handlers can be removed on elements by providing combinations of event names, namespaces, selectors, or handler function names. When multiple filtering arguments are given, all of the arguments provided must match for the event handler to be removed.
You may refer http://api.jquery.com/off/
Answer: Please add  $(".ui-widget-overlay").live("click", function () { inside document.ready . Some thing like this
 $(document).ready(function(){
       $(".ui-widget-overlay").live("click", function () {
          $("div:ui-dialog:visible").dialog("close");
       });
       $(".dialog-marker").on("click", function () {

           var d = $(this).next("div").first().dialog(dialogOptions);
           d.dialog("open");
          return false;
        });

    });

Or simply
make a funtion like this and add a function call on onClick event
function showDialogBox(){
     var d = $(this).next("div").first().dialog(dialogOptions);
        d.dialog("open");
        return false;
}

function closeDialogBox(){
    $(".ui-widget-overlay").live("click", function () {
        $("div:ui-dialog:visible").dialog("close");
    });
}

Comment: Still the link not working after working once.button is not working on second click.


Exit from app when click button in android phonegap?

Question: I am new to phonegap. I have prepared one sample application. My application has 2 pages, the first page has one button, when clicked the second page will open. It is working fine using the following
         function callAnothePage()
         {
            window.location = "test.html";
         }

The second page has one button, when clicked I want to exit from the application. I used the following
       function exitFromApp()
       {
            navigator.app.exitApp();
       }

test.html code,
<!DOCTYPE html>

Login Page

    <input type="submit" onclick="exitFromApp()" value="exit"/>

But it is not working.
Answer: Try this code.
<!DOCTYPE HTML>

    <title>PhoneGap</title>

       <button name="buttonClick" onclick="exitFromApp()">Click Me!</button>

Replace src="cordova-1.5.0.js" with your phonegap js .
Comment: Replace with phonegap-1.4.1.js but not working and i got error like,   " Uncaught TypeError: Cannot call method 'exitApp' of undefined at file:///android_asset/www/test.html:16"
Comment: @user1651572 Please download the latest version of phonegap js . It solved your problem .
Comment: can u please send me url for latest version . I goggled for latest js file i am not able to find....
Comment: can i know what is difference b/w cordova.js and phonegap.js
Comment: @user1651572 before that it phonegap.js now its cordova. Nothing else
Comment: added cordova-2.0.0.js and still i got error like cannot call method exitApp
Comment: @user1651572 take button instead of input type and check agian
Comment: Uncaught TypeError: Cannot call method 'exitApp'
Comment: @user1651572 . Try this navigator.device.exitApp()
Comment: This only minimises the app on Android 8. It doesn't close it fully :S
Comment: As of 2019, iOS ignores all attempts to exit. If it does close it's considered a "crash" since it goes against the developer guidelines.
Answer: There are different ways to close the app, depending on:
if (navigator.app) {
    navigator.app.exitApp();
} else if (navigator.device) {
    navigator.device.exitApp();
} else {
    window.close();
}

Comment: This is a nice way, thanks! Actually, I'd add a typeof check if exitApp is really a function (not sure if this would be present in all cases where navigator.app or navigator.device exist)
Answer: navigator.app.exitApp();

add this line where you want you exit the application.
Answer: @Pradip Kharbuja
In Cordova-2.6.0.js (l. 4032) :
exitApp:function() {
  console.log("Device.exitApp() is deprecated. Use App.exitApp().");
  app.exitApp();
}

Answer: if(navigator.app){
        navigator.app.exitApp();
}else if(navigator.device){
        navigator.device.exitApp();
}

Answer: I used a combination of the above because my app works in the browser as well as on device.  The problem with browser is it won't let you close the window from a script unless your app was opened by a script (like browsersync).
        if (typeof cordova !== 'undefined') {
            if (navigator.app) {
                navigator.app.exitApp();
            }
            else if (navigator.device) {
                navigator.device.exitApp();
            }
        } else {
            window.close();
            $timeout(function () {
                self.showCloseMessage = true;  //since the browser can't be closed (otherwise this line would never run), ask the user to close the window
            });
        }

Answer: sorry i can't reply in comment. just FYI, these codes
if (navigator.app) {
navigator.app.exitApp();
}
else if (navigator.device) {
  navigator.device.exitApp();
}
else {
          window.close();
}

i confirm doesn't work. i use phonegap 6.0.5 and cordova 6.2.0


Vim function to find pattern, replace, and visual mode

Question: So I use Vim to write reports at work, reports are basically a bunch of "common issues" that we write over and over, so they are templated. These templates have placeholder blocks {==BLOCK==} to ensure people modify things as/when needed, so this is an example:
The test revealed that it was possible to access {==sensitive data==},
as shown in the examples below...

That block may need to be modified, or not. So the idea is, I am editing the common issue, and I see there are 3 or 4 blocks like the one in the example, I'd like to press let's say [leader]b and then end up having the template text for the first block selected in visual mode without the {== and ==} that are around it.
I have tried a few things but I didn't get too far, any suggestions?
Thanks!
Comment: Sorry, maybe I didn't express myself properly, but I dont want to replace with a REGEX what is inside, I'd like the function to find the block, get rid of {== and ==} and then leave the template text inside the block as it is, but selected in visual mode
Answer: You could define the following function:
function! VisualSelect()
    call search("==}")
    norm hvT=
endfunction
nnoremap <leader>b :call VisualSelect()<cr>
vnoremap <leader>b Ol<esc>:call VisualSelect()<cr>

This will visually select the contents between {== and ==}. Typing <leader>b repeatedly will select the next occurrence.
Comment: Use `xnoremap` to allow this only in visual mode instead of also picking select mode.
Answer: Most template/snippet expand plugins support this.
With my lh-brackets plugin, you can execute
:SetMarkers {== ==}

and then jump from one placeholder to the next with CTRL+J with vim, or META-DEL with gvim. lh-brackets doesn't take care of loading/expanding templates. mu-template will add this layer.
If instead you choose to use one of the more popular snippet plugin, there will certainly be an option to change the syntax of the placeholders, but I don't know it.
The poor man's solution would look like:
nnoremap <c-j> <c-\><c-n>/{==.*==}<cr>v/==}/e<cr><c-g>
snoremap <c-j> <c-\><c-n>/{==.*==}<cr>v/==}/e<cr><c-g>

but it won't take care of restoring the search pattern, of the cases where the cursor is already within a placeholder, and so on...
EDIT: the version that automatically deletes the placeholder marks is
nnoremap <c-j> <c-\><c-n>/{==.*==}<cr>v/==}/e<cr>s<c-r>=matchstr(@", '{==\zs.*\ze==}')<cr><esc>gv6h<c-g>

the same in snoremap
Comment: Thanks, but using 2 plugins just for this task seems a bit overkill to me!

Regarding "the poor man's solution", the problem is that it doesn't delete the {== and ==} bits, which is part of what I'd like to automate.

Thanks!
Comment: The second part is easy enough to accomplish, once in visual mode, replace with (`s=`) the inner part (with `matchstr` or  `substitute()`), and then reselect (`gv`), fix the end (`6h`) and go to select mode (``).
`nnoremap  /{==.*==}v/==}/es=matchstr(@", '{==\zs.*\ze==}')gv6h`
But actually, the select-mode is more than enough in most use cases as in the end the placeholder must be replaced with something different of the placeholder description.
Answer: I have figured out a way based on what @snap said, I ended up adding the code to a Python plugin to run it through it, as that fits better with what I am trying to do, snippet below:
@neovim.command('VimisEditTemplateBlock')
def urlify(self):
    """Search next codify block and prepare for editing"""
[...]
    self.nvim.command('call search("{==")') # Find beginning of codify block
    self.nvim.command('norm xxx') # Delete {==
    self.nvim.command('norm vf=') # Select the inner text
    self.nvim.command('norm v')
    self.nvim.command('norm xxxgvh') #Delete ==} and leave the inner text selected in Visual Mode

Answer: In short:
nnoremap <leader>b /{==.*==}<cr>xxxvt=<esc>/==}<cr>xxxgv

What it does:
1.) find the pattern
/{==.*==}<cr>

2.) Remove the first "{=="
xxx

3.) Visual select your text until the first = (maybe this could be also optimized for using a regex instead of simple searching for the next =)
vt=

4.) Go to the end sequence
/==}<cr>

5.) Remove it
xxx

6.) Select again your last selection
gv


Find a row in a Julia DataFrame

Question: What's the canonical way of finding a row in a DataFrame in DataFrames.jl?
For instance, given this DataFrame:
│ Row  │ uuid                                 │ name
│      │ String                               │ String
├──────┼──────────────────────────────────────┼──────────────────────────────
│ 1    │ 0efae8bf-39e6-5d65-b05d-c8947f4cee2a │ COSMA_jll
│ 2    │ 17ccb2e5-db19-44b3-b354-4fd16d92c74e │ CitableImage

Given the name "CitableImage", what's the best way to retrive the uuid?
Answer: I would typically use:
filter(:name => ==("CitableImage"), df)

which produces a data frame as you can have more than one matching row.
If you are sure that only one row will match then you can also write:
df[only(findall(==("CitableImage"), df.name)), :]

(the only function checks that you picked only one row)
If you want to get a data frame using indexing you can write:
df[df.name .== "CitableImage", :]

or
df[findall(==("CitableImage"), df.name), :]

Finally we also provide the subset function, but its normal use case is a bit different so here is is more verbose than filter:
subset(df, :name => ByRow(==("CitableImage")))

If you want to do many lookups and want them to be efficient then it is better to do the following:
gdf = groupby(df, :name)

and then do:
gdf[("CitableImage",)]

which will be much faster if you do many such lookups.
Comment: perhaps both should be burninated. I'll ask on meta. Thanks for answering! :-)
Comment: Hi Bogumił! Off-topic for this post (apologies for hijacking this), but I noticed that there is a dataframes.jl tag on Stack Overflow, as well as a julia-dataframes tag. I was wondering, would you consider them synonyms? I would suggest it, but it appears I need a score of 5 in the julia-dataframes tag to suggest it. Interested to hear your thoughts!
Comment: I think it is better to tag questions regarding DataFrames.jl to be tagged `julia` and `dataframe` (two separate tags). The `julia-dataframe` tag is very rarely used, so I think it is not that useful.

Find a row in a Julia DataFrame


Combine two RDDs in pyspark

Question: Assuming that I have the following RDDs:
a = sc.parallelize([1, 2, 5, 3])
b = sc.parallelize(['a','c','d','e'])

How do I combine these 2 RDD to one RDD which would be like this:
[('a', 1), ('c', 2), ('d', 5), ('e', 3)]

Using a.union(b) just combines them in a list. Any idea?
Answer: You probably just want to b.zip(a) both RDDs (note the reversed order since you want to key by b's values).
Just read the python docs carefully:

zip(other)
Zips this RDD with another one, returning key-value pairs with the
  first element in each RDD second element in each RDD, etc. Assumes
  that the two RDDs have the same number of partitions and the same
  number of elements in each partition (e.g. one was made through a map
  on the other).

x = sc.parallelize(range(0,5))
y = sc.parallelize(range(1000, 1005))
x.zip(y).collect()
[(0, 1000), (1, 1001), (2, 1002), (3, 1003), (4, 1004)]

Comment: Depends on the use case. One thing is sure - you need some key on which you want to do the join. Then you can proceed with eg. reduceByKey or join, like in this chapter - https://www.safaribooksonline.com/library/view/learning-spark/9781449359034/ch04.html
Comment: How would you do this if you had two RDD's with different number of elements and partitions?

Combine two RDDs in pyspark


Feature Exposure vs. UI bloating

Question: When developing my web applications, I usually tend to have an icon/button per feature/function and place it in a way that it is easily accessible without distracting the user during his usual work. However, I often have confrontations with part of management because they feel certain buttons should be on multiple places and be as visible as possible.
What is your take on this? Should buttons/functionality within the same context have one place were the user should always look for it (my approach), or should buttons be duplicated to all places were the user might need them (management's approach).
Examples:
 - Put another edit button right beside the tabs of a config-screen to get to the edit-mode to the app because the edit option is inside a toolbar-menu and not visible right away
 - Put a save button above and below a textarea because the user could either be finishing typing (lower save is close) or finishing reading the preview (upper save is close)
Our reasoning behind the debate:
my approach:
 + slick design
 + unused icons stay hidden
 + structure
 - user's without prior exposure to the software might need to look up the features/search
management's approach
 + functions are visible where they are needed
 - redundant UI-components for the very same function
 - disorganized look and feel
 - UI bloat
I reckon that the reasoning seems biased, but that's why I am asking. What approach results in a better UI?
Answer: Duplicating actions isn't always bad in my opinion. Especially not if they are not exactly the same from the users perspective.
I think in the end, there is not one way to follow for everything. It is not do-not-duplicate versus duplicate-as-much-as-possible. Look at the case at hand and decide what the user might think here, what is their usual pattern, what would they do if it was not an application but a paper thing, how would they think. And based on that, decide where you want to provide what kind of actions.

Going into your first example:

Put another edit button right beside the tabs of a config-screen to get to the edit-mode to the app because the edit option is inside a toolbar-menu and not visible right away

I think this is what you say:

If so, then the two actions have different meanings for the user. The first 'edit-mode' puts them in an editorial/redactional modus (also inside their own minds) and makes everything editable. The second 'change these settings' only does that with this page.

Your second example:

Put a save button above and below a textarea because the user could either be finishing typing (lower save is close) or finishing reading the preview (upper save is close)

I had a similar situation lately:

In this case the first save button provides a quick way to make changes; an [ edit - change something - save ] is easily done and the user doesn't have to scroll down the whole form. And when the user does need to set the advanced options they can just follow the form and save at the bottom.
(One can argue to put the advanced settings under a link above the first save button and let it fold out when clicking the link. This is not always wanted though.)
Comment: Well, it seems like the UI-debate can't be boiled down by ideologies then. Lessons learned.
Answer: Who says redundancy is always bad?  It's common to have menus, toolbars, and keyboard shortcuts that all do the same thing.  If the duplicates don't each add something (i.e. they really are completely redundant), then it's time to remove something, but it might not be the bits you first think.
In Gmail, reply is available above and below a message, because the user is likely to have scrolled either to the top or bottom of the page, making it hard to find a button at the other end.  This problem doesn't exist for desktop apps, so they wouldn't have a good reason to include a button in both locations.
The trick is to stay balanced and avoid putting everything everywhere.  The principle of grouping related functionality helps in both directions -- don't hide stuff out of the way if it really is related to localized functionality, but don't throw stuff into the middle of the main UI unless it is useful for doing the task the user is there to do.  The latter case covers options and settings that the user will set once and forget about -- don't put an Options button in their way if they're only going to click it once.
Figure out what the most common use cases are for each part of your app, and optimize the UI for those use cases.  It's ok if this adds a little redundancy.
Answer: Many web applications have Save / Submit buttons both above and below the content  (especially shopping carts).
As long as the buttons look identical and are aligned with each-other, there's nothing wrong with that.
Contextual buttons (such as an edit button for a row) should be associated with their rows; it would probably be better to put an edit button in the row (perhaps on hover) than in a toolbar (unless you support multi-selection)
Comment: Shopping carts are a category of their own, they are aiming at closing the sale. Redundancy is a proven device to achieve just that. The objective of a shopping cart is a completely different one than that of a web app.
Comment: @bobsoap: I've seen this in non-shopping carts too.
Answer: Microsoft's Ribbon provides the user the ability to add various commands to the "Quick Access" toolbar. You could extend that idea and just add those commands initially, while allowing the user to remove the ones they don't want.
Answer: I've seen many websites with a floating bar or widget, staying in sight regardless of the scrolling. Couldn't such a bar not be used to keep the "Edit", "Save" or other commands in sight? This would obviously only work when the page as a whole would be saved, I guess.
Answer: Well, what do the actual users say about it? And how do they respond to both implementations when put to a user test? I think those are deciding factors. I think applications should be mainly easy to use, so avoiding UI bloat is not a goal in itself, but a means to keep it usable. If the extra button helps users (by making a much-used function more easily accessible) more than it hinders them (by presenting them with a confusing interface) I think it should be done.
(And note that most GUIs already have redundancy in them. Certain options are listed in the menu items at the top, the toolbar, the context menu and have a keyboard shortcut.)
I think that if the edit-mode is used much, it deserves a direct button.

Feature Exposure vs. UI bloating


How to check if the Worksheet exists in the Excel file

Question: I have an Excel file which contains more than 20 sheet. I am writing a module in Matlab where I need to check if a particular worksheet say for example 'SalaryData' is present in the Excel file.
I am not able to use xlsinfo I think, this function is not available in the Matlab version I am currently using.
I intend to use actxserver to check the existence of the worksheet. What I am currently doing is something like :
SheetExist=1;
try
  sheet = get(Excel.Worksheets,'Item',sheetname);
catch
  disp('File Does not exist');
  SheetExist=0;
end

I think there is a much better and a easier way to check.
Thanks
Comment: Possible duplicate of: http://stackoverflow.com/questions/6040164/excel-vba-if-worksheetwsname-exists
Comment: I don't know matlab, but that looks about right to me.
Comment: @Steve Robillard: no, no duplicate, this question is for matlab, not VBA
Answer: You can use the xlsfinfo function:
[~, sheets] = xlsfinfo(filename);
ismember(sheetname,sheets);

Notice that the sheetname is case sensitive by using the ismember function! If you want case insensitivity, use a loop and strcmpi.
EDIT: just noticed your remark about xlsinfo :p
Are you sure it is not available? You mention xlsinfo is not available, but the actual function is called xlsfinfo! notice the 'f' between 'xls' and 'info'
Comment: Wonderful, I just missed an 'f' in ´xlsfinfo´. I just dropped an f word.. quiet literally.. :) Thank you
Answer: Will this help?
SheetExist=1;
Set ws = Sheets("sheet_name")
If ws Is Nothing Then SheetExist=0

Comment: Thanks a lot for your time. Is it VBA code ? What I am trying is very similar. I am looking at a function similar to `exist()` in matlab.


Cast Django's intcomma string to Decimal

Question: I'm trying to export some records from database with Django but when exported the type of amount field is represented as string and not decimal.

My code

from django.contrib.humanize.templatetags.humanize import intcomma
import django_excel as excel

def download(request):
    records = []
    now = datetime.datetime.now()

    for reservation in Reservation.objects.sifted(request):
        record['Amount (EUR)'] = intcomma(reservation.amount)
        records.append(record)

    return excel.make_response_from_records(
        records,
        'xls',
        file_name="export_reservations_{}".format(now.strftime('%d_%m_%Y').replace(".",","))
    )

Model

amount = DecimalField(max_digits=6,
                          decimal_places=2,
                          null=True,
                          default="0.00",
                          verbose_name='Amount')

This produces something like 12.12 which is the correct format but it's string.
If i do Decimal(intcomma(reservation.amount)), I get decimal type, but the format is 12 with floating points.
How can I get decimal with correct format(xx.xx) in the export?
Answer: Does it really need to be a decimal? Why not just:
record['Amount (EUR)'] = round(reservation.amount, 2)

Comment: Hm, do you maybe know how would i get `12,12` instead of `12.12`
Comment: As a string, or as a numeric type?
Comment: as numeric tyoe
Comment: None that I'm aware of.
Comment: ah your answer actually worked, it was my mistake! thanks :)


Representations of finite groups over different algebraically closed fields

Question: Let $G$ be a finite group, $K_1,K_2$ are two algebraically closed field and $(\text{char}K_i,|G|)=1$. What's the relationship between irreducible representations over $K_i$? ($i=1,2$)
The number of irreducible representations are the same ($=$number of conjugacy classes of $G$). Does there exist a bijection between irreducible representations over $K_i$ which preserves dimesnion and is functorial respect to $G$ ? Meanwhile, can we put other restrictions such that such bijection is unique?
Answer: Let $R=\mathbb{Z}[\frac{1}{|G|},\mu_m]$ where $m=\exp G$ is the exponent of $G$ and $\mu_m$ is the set of the $m$th roots of unity. The idempotents in the group algebra $\mathbb{C}[G]$ (corresponding to projections onto isotypical components, and are the identity elements of the summands in the Artin-Wedderburn decomposition) are in fact elements of $R[G]$, as they are given by $e_{\small V}=\frac{1}{|G|}\sum_{g\in G}\chi_{\small V}(g^{-1})g$.
By fixing (onto) quotient maps $R\to K_1$ and $R\to K_2$ we get corresponding idempotents in the group algebras $K_1[G]$ and $K_2[G]$ corresponding to the irreps over those fields. This induces a bijection (which should be functorial in some sense?) but it depends on the original choice of quotient maps from $R$ which are all related by automorphisms of $K_1$ and $K_2$.


Include @ as key in json

Question: Can the @ symbol be utilized as part of writing a Python object to json ? I'm attempting to use :
import json

print(json.dumps(dict(@test=test)))

expected output is {"@test":"test"}
But below error is thrown :
File "<ipython-input-38-7b37241c4d92>", line 3
    def __init__(self , @id):
                        ^
SyntaxError: invalid syntax

Comment: Your problem has nothing to do with json. But if you use the `dict()` constructor then the keys have to be valid Python identifiers. If they are not, construct your dict using `{ }`.
Comment: Are you coming from the ruby world? Because in python you can define variables directly..
Comment: Where have you seen that `@whatever` is valid Python syntax for an identifier ??? Also, your traceback doesn't even match your code snippet...
Answer: print(json.dumps({"@test": "test"}))

For further explanation see: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Include @ as key in json


Understanding the identity theorem for analytic functions

Question: Can you help me understand the identity theorem?
The question is: does it exist an analytic function $f$ such that: $$f(\frac{1}{n})=f(\frac{-1}{n})=\frac{1}{n^2}$$
or
$$f(\frac{1}{n})=f(\frac{-1}{n})=\frac{1}{n^3}$$
for $D=\{z: |z|<2\}$.
Limited point of our set is in D. But how to prove that function is analytic?
Answer: For the first question, take $f(z) = z^2$.
For the second, first focus on the positive values of $n$. Let $g(z) = z^3$. Then $f(z) = g(z)$ for $z=\frac1n$, and the identity theorem forces $f(z) = z^3$ everywhere on $D$, but this contradicts $f(-\frac1n) = \frac1{n^3}$, so there can be no such function.


Definitions of supremum

Question: This question is for me to better understand the beginning of a real analysis course.
We are provided with two definitions of supremum as follows:
Def 1 : Let $S$ be a set in $\mathbb{R}$ be bounded above, then $m$ is called the least upper bound (supremum) if $m \ge s\space, \forall s\in S $ and if $m'$ is some other upper bound, then $m < m'$
Def 2: Let $S$ be a set in $\mathbb{R}$ be bounded above, then $m$ is a supremum if for some arbitrary $\epsilon>0$ $\exists s \in S, m-\epsilon < s$
I understand how both statements are true, however, would it be possible to prove the Def 2 based on Def 1?
Any hint is appreciated!
Comment: @rannoudanames "When we take the ϵϵ we intend that it can be infinitly small," No no no. No such thing as "infinitely small" in the real numbers. Arbitrarily small is how we express it. Huge difference.
Comment: There are no infinitely small real numbers. The idea of replacing the vague idea of "infinitely small" with the precise idea of *arbitrarily small* is the key breakthrough in the modern formalization of the real numbers. Note that $\epsilon$ is always a positive real number.
Comment: $ \epsilon := m' - m $
Comment: how would that work? When we take the $\epsilon$ we intend that it can be infinitly small, implying that $m- \epsilon$ leaves no space for any m' between m and all of s in S. How would your argument using $\epsilon := m'-m$ go? Would we assume $m'$ some arbitrary upper bound making $\epsilon$ also arbitrary?
Comment: I'm sorry now I can see it isn't true - consider the set $ S := \{ 1, 2 \} $ and $\epsilon = 1/2$ .
Comment: @user4894 mind elaborating on that point if you dont mind?
Comment: Thank you! here is some more: http://math.stackexchange.com/questions/2109339/infinitely-small-vs-arbitrarily-small
Comment: Your def 2 was wrong, there only exists some $s \in S$ with $s > m - \epsilon$, not for all $s \in S$
Comment: It is clearer to say "for all $\epsilon>0$" instead of "for some arbitrary $\epsilon>0$".
Answer: Suppose $m$ is a supremum by definition 1. Suppose $\exists$ $\epsilon>0$ such that $m-\epsilon\geq s$ $\forall s\in S$, then $m'=m-\epsilon$ is another upper bound so it must be $m<m'=m-\epsilon$ which is impossible. So we must have $\forall \epsilon>0$, $m-\epsilon <s$ $\exists s\in S$.
This proves definition 2 in terms of definition 1.
Comment: Also let me add that definition 2 implies definition 1. If $m$ is a supremum by definition 2 then $m\geq s$ $\forall s\in S$. Now suppose $m'$ is another upper bound and $m'0$. Take $0<\epsilon <m-m'$ so by def 2 $\exists s\in S$ s.t. $m'<m-\epsilon<s$ so $m'$ is not an upper bound, so we get again a contradiction.
Comment: I see you are doing a proof by contradiction, and it makes sense to me. m cannot be inferior to some number smaller than m.
Comment: makes sense! (hypothetical +1)

Definitions of supremum


Optimize Django generated SQL query

Question: I have the these models:
class Person(models.Model):
    firstname = models.CharField(max_length=20)
    lastname = models.CharField(max_length=20, blank=True, null=True)

class relation(models.Model):
    parent = models.ForeignKey(Person,on_delete=models.PROTECT, related_name='children')
    rel = models.CharField(max_length=1)
    child = models.ForeignKey(Person, on_delete=models.PROTECT, related_name='parents')

    class Meta:
        unique_together = (('parent', 'child'),)

where relation model represent the relation from parent to child. If I want to get all brothers of a person I would use this query:
tid = 198
brothers = relation.objects.filter(~Q(child = tid), parent__children__child = tid).values('child__firstname', 'child__lastname')

The above query generates this SQL query:
SELECT "eftapp_person"."firstname", "eftapp_person"."lastname" FROM "eftapp_relation" INNER JOIN "eftapp_person" ON ("eftapp_relation"."child_id" = "eftapp_person"."id") INNER JOIN "eftapp_person" T3 ON ("eftapp_relation"."parent_id" = T3."id") INNER JOIN "eftapp_relation" T4 ON (T3."id" = T4."parent_id") WHERE (NOT ("eftapp_relation"."child_id" = 198) AND T4."child_id" = 198)

I added to my models an unmanaged model pointing to relation table, the intent was to optimize the generated SQL query.
class relcalc(models.Model):
pp = models.OneToOneField(relation, on_delete=models.PROTECT, db_column='parent_id', to_field='parent', related_name='pcn')
cc = models.OneToOneField(relation, on_delete=models.PROTECT, db_column='child_id', to_field='child', related_name='cps')
r = models.CharField(max_length=1, db_column='rel')

class Meta:
    db_table = 'eftapp_relation'
    managed = False

To query get brothers of a person:
brothers = relation.objects.filter(~Q(child = tid), pcn__cc = tid).values('child__firstname', 'child__lastname')

and the generated SQL query is:
SELECT "eftapp_person"."firstname", "eftapp_person"."lastname" FROM "eftapp_relation" INNER JOIN "eftapp_person" ON ("eftapp_relation"."child_id" = "eftapp_person"."id") INNER JOIN "eftapp_relation" T3 ON ("eftapp_relation"."parent_id" = T3."parent_id") WHERE (NOT ("eftapp_relation"."child_id" = 198) AND T3."child_id" = 198)

You can see that the later SQL query is 1 table less than the previous query.
This tactic works perfectly in python shell but if I run Django server I get the following errors:
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 442, in check
    raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:
eftapp.relcalc.cc: (fields.E311) 'relation.child' must be unique because it is referenced by a foreign key.
    HINT: Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints.
eftapp.relcalc.pp: (fields.E311) 'relation.parent' must be unique because it is referenced by a foreign key.
    HINT: Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints.

System check identified 2 issues (0 silenced).

Any ideas on how to get an optimized query without generating errors in Django server?
Answer: After further research; I found that using the raw() manager is the best way to get the optimum query, this method takes a raw SQL query and returns  RawQuerySet instance with object instances.
brothers = Person.objects.raw("SELECT eftapp_person.id, eftapp_person.firstname, eftapp_person.lastname\
        FROM eftapp_relation INNER JOIN eftapp_person ON (eftapp_relation.child_id = eftapp_person.id)\
            INNER JOIN eftapp_relation T2 ON (eftapp_relation.parent_id = T2.parent_id)\
        WHERE (eftapp_relation.child_id <> %s AND T2.child_id = %s)",[tid,tid])

Optimize Django generated SQL query


Problem with Icewind Dale Gold mirrored sprites

Question: I am currently playing Icewind Dale Gold, an outstanding D&D based dungeon crawler. It works with almost no problems on my Pentium 4 2.93GHz Prescott, 1.5GB RAM DDR2 and Radeon HD4650 1GB PciE, running Windows XP SP3 and DirectX 9.0c.
However, there is only one minor issue that I was not able to fix no matter what - it is the Mirrored Sprites option, accessible from games setup, under Graphics tab. Basically, it makes characters' sprites animation being mirrored, i.e. when character is facing right and hold his shield in his right hands, then after turning and facing left the shield is immediately swapped to his left hand, being a mirror reflection of his previous stance. In the old days it allowed to save some memory and increase game performance. Nowadays I am not able to turn this option off - it is always active.
I noticed this happens in almost every game based on Infinity engine I tried in the past years (Icewind Dale 2, Baldur's Gate Gold). I also used different hardware specs (Radeon 9550 AGP, Pentium 4 2GHz Northwood, Celeron D 3.2GHz, Athlon 2400XP+, DualCore E5200), with no results.
Do you by any chance know if it is a known bug and is there is any solution for this?
Just note I use localized, Polish versions of these games - could this problem be version-specific?
Thank you in advance.
Comment: I could swear I have seen a similar question, can't find now where..
Comment: Hope there was one and it was answered :)
Comment: What happens if you force it off in the icewind.ini? Not sure what the setting is called (I don't have an installed version currently), but it should be there somewhere.
Comment: Yes it is there - Sprite Mirror=0. That is what I have, so it seems it is saved correctly when exiting setup, but does not work. I can try to change it to 1 to see what happens though.
Comment: I never noticed this on my more modern PCs. Now I'll have to load it and see.
Comment: Ok, I modified the icewind.ini file manually, changing Sprite Mirror to 1 and 0, no changes at all. I also turned the OpenGL 3D acceleration to off and switched do 16 bit, so I can access three additional gfx options (software mirrored copying, etc.), but these also did not change antything. My copy is on a single magazine DVD with two another full games - could it be half of the sprites animations were removed to save space on DVD?
Comment: You didn't do a minimum install by chance? Where that extra sprites did not get installed forcing you to use mirrored sprites.
Comment: I generally always select the full/maximum installation option when I install a game, though I can't really remember if I had any choice with my copy of Icewind Dale. I was about to reinstall the game anyway, so I will ensure and let you know. Thanks for comment.
Answer: I've had some serious problems with IceWind Dale 1 and 2 on modern systems. After some heavy experimenting, someone told me to disable 2D DirectX acceleration in dxdiag, and that solved the problems.
Try it out.


C# standalone application with java backend webservice

Question: I am new to C# (still learning). My problem statement is that i have to build a C# plugin for excel. The backend of the application is spring based Restful service implemented using Restlet.
Can i leverage the same service and make calls from the proposed C# standalone app (the excel plugin)? if so can someone point me to some sample c# client webservice code?
Thanks a bunch!
Answer: yes, you can.
Just add a Service Reference
And then with a using statement you can connect and make calls.
Make sure you also Don't use using to wrap your calls.  Use a helper class, and even then wrap it in a try/catch
Comment: thanks for your comment. I am using only a C# client to make the calls is it still relevant? will i be using WCF? Sorry since i am new i do not know.
Comment: @Shah A service reference is a service reference.  If it's a webservice you're connecting to, then it's a webservice you need to wire up in your application.  I missed the part about restful when I wrote this, but I don't think rest services are much different.


Run nginx and node js in same container

Question: Hi I am trying to run node js and nginx as a proxy server. I can make them work if they are both in different container running simultaneously. But when trying to pack and run them both in same container it fails somehow.
Here is the dockerfile I am using to build that.
FROM nginx
#install node 14.19.1
RUN apt update
RUN apt install wget -y
RUN apt install xz-utils -y
RUN wget https://nodejs.org/download/release/v14.19.1/node-v14.19.1-linux-x64.tar.xz
RUN tar -xvf node-v14.19.1-linux-x64.tar.xz
RUN cp -r node-v14.19.1-linux-x64/bin /usr/
RUN cp -r node-v14.19.1-linux-x64/include /usr/
RUN cp -r node-v14.19.1-linux-x64/lib /usr/
RUN cp -r node-v14.19.1-linux-x64/share /usr/
RUN export PATH=/usr/node-v14.19.1-linux-x64/bin:$PATH
#nginx conf
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf
#run node js server
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "node", "server.js" ]

And this one is using node js image
FROM node:14.19.1
WORKDIR /usr/src/app
#install and configure nginx
RUN apt update
RUN apt install nginx -y
#COPY myserver.config /etc/nginx/sites-available
#RUN ln -s /etc/nginx/sites-available/myserver.config /etc/nginx/sites-enabled/
#RUN nginx -t
#RUN service nginx restart
#RUN ufw allow 'Nginx Full'
#install and run node server
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 80
CMD [ "node", "server.js" ]

This is the nginx.conf file that I am trying to run nginx through I know the localhost:3000 does not seem working. Can you please suggest me an alternative to make this work. Thanks
server{
    listen 80;
    server_name pnext;
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass 0.0.0.0:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        # location /overview {
        #     proxy_pass http://127.0.0.1:3000$request_uri;
        #     proxy_redirect off;
        # }
    }
}

Comment: Running two processes in one container usually isn't recommended.  You say you have a working setup with two separate containers, which would be a best practice; can you keep using that existing setup?
Comment: @DavidMaze Yes that is the optimal approach, but as of now we are running these container in an EC2 environment where we have all the access to underlying hardware and architecture. But now we are planning to migrate this thing to ECS running on far-gate. Running two different container and the one running node js will be auto scaled by AWS then we would be required to setup two load balancer one in front of nginx and other in front of node js service. I just want to remove at least one load balancer layer from the infrastructure. If you have any solution to this one without running in same
Comment: container please tell me.
Answer: You could use nginx as a sidecar in ECS container if you are using ECS as you mentioned in the comment.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Just change your CMD line to the following:
CMD nginx -g 'pid /tmp/nginx.pid;' & node server.js

Run nginx and node js in same container


Different ABTwo-Digit Numbers Question

Question: I have seen a question as;
If $\overline{AB}$ is a two-digit number
and
$\overline{AB}-10B-A=A^3 - B^3$
How many different AB two-digit numbers can be written?
Thank you.
Comment: Are you thinking of "$AB$" as the concatenation of two digits, or as the product of two numbers? (The edit suggests the former.)
Comment: I am also not sure about that point. The question is exactly like i expressed. The solution says that 10 different numbers can be written however i just found only "30" when i supposed AB is two-digit number.
Comment: If "$AB$" means $10A+B$ with $1\le A\le 9$ and $0\le B\le 9$, then you simply have $9(A-B)=A^3-B^3$.
Answer: $$
\begin{align}
&10A+B-10B-A=A^3-B^3\\
\Rightarrow\  &\frac{(A^2+B^2+AB)(A-B)}{A-B}=9\\
\Rightarrow\  &A^2+B^2+AB=9\ or\ A=B \\
\end{align}
$$
The solution if $A\ne B$ is $\overline{AB}=30$ i.e. $A=3,B=0$.
For $A=B$, there are $9$ solutions i.e. $11,22,...,99$.
Hence there are $10$ solutions.
Answer: $\overline{AB}-10B-A=A^3-B^3\\(10A+B)-10B-A=A^3-B^3\\9(A-B)=(A-B)(A^2+B^2+AB)\\SO\\$
$$\begin{cases}A=B & \rightarrow A=B=1,2,3,4,...9\\A^2+B^2+AB=9 & \begin{cases}A=1 & B^2+1B=9-1\\A=2 & B^2+2B=9-4 \rightarrow \\A=3 & B^2+3B=9-9 \rightarrow B=0\end{cases}  \end{cases}
\\\overline{AB}=11,22,33,...,99,30$$
Comment: Brilliant. Thank you.

Different ABTwo-Digit Numbers Question


Filtering an array of objects that contain arrays

Question: This is a smaller version of the array i have but it has the same structure
with const arr below, i want to create 2 new arrays with unique values that are sorted in ascending order

const arr = [{
    tags: ['f', 'b', 'd'],
    weight: 7,
    something: 'sdfsdf'
  },
  {
    tags: ['a', 'b', 'c', 'd', 'e'],
    weight: 6,
    something: 'frddd'
  },
  {
    tags: ['f', 'c', 'e', 'a'],
    weight: 7,
    something: 'ththh'
  },
  {
    tags: ['a', 'c', 'g', 'e'],
    weight: 5,
    something: 'ghjghj'
  }
];

const finalTags = [];
const finalWeight = [];

// TODO:  find a better way to do this
arr.forEach(v => {
  if (finalWeight.indexOf(v.weight) === -1) finalWeight.push(v.weight);
  v.tags.forEach(val => {
    if (finalTags.indexOf(val) === -1) finalTags.push(val);
  });
});

// Ascending order
finalTags.sort();
finalWeight.sort();

what i have above works, but seems a bit messy and was wandering if there was a better/tidier way of doing this
Comment: Might this be better off on https://codereview.stackexchange.com/?
Answer: You can use Array.prototype.reduce() combined with Set in order to get an object with the sorted arrays {tags: [], weights: []}:

const arr = [{tags: ['f', 'b', 'd'],weight: 7,something: 'sdfsdf'},{tags: ['a', 'b', 'c', 'd', 'e'],weight: 6,something: 'frddd'},{tags: ['f', 'c', 'e', 'a'],weight: 7,something: 'ththh'},{tags: ['a', 'c', 'g', 'e'],weight: 5,something: 'ghjghj'}];
const obj = arr.reduce((a, {tags, weight}) => {
  a.tags = [...new Set(a.tags.concat(tags))];
  a.weights = [...new Set(a.weights.concat(weight))];
  return a;
}, {tags: [], weights: []});

// final result i want
console.log('finalTags:', obj.tags.sort()); // ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
console.log('finalWeight:', obj.weights.sort()); // [5, 6, 7];
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comment: I will vote you up because you had a similar idea to mine and was first. However, it will be nice to see some explanation too.
Comment: Thank you for your comment @Shidersz. I have added a better description and you also have my up..
Comment: much nicer than my version, thanks for all your answers
Answer: One solution is to use Array.reduce() to create two sets, one with the tags and other with the weights. After this you can transform the sets to arrays and use Array.sort() on they:

const arr = [
  {
    tags: ['f', 'b', 'd'],
    weight: 7,
    something: 'sdfsdf'
  },
  {
    tags: ['a', 'b', 'c', 'd', 'e'],
    weight: 6,
    something: 'frddd'
  },
  {
    tags: ['f', 'c', 'e', 'a'],
    weight: 7,
    something: 'ththh'
  },
  {
    tags: ['a', 'c', 'g', 'e'],
    weight: 5,
    something: 'ghjghj'
  }
];

let res = arr.reduce((acc, {tags, weight}) =>
{
    acc.tags = new Set([...acc.tags, ...tags]);
    acc.weights.add(weight);
    return acc;
}, {tags: new Set(), weights: new Set()});

let sortedWeigths = [...res.weights].sort();
let sortedTags = [...res.tags].sort((a, b) => a.localeCompare(b));
console.log("weights: ", sortedWeigths, "tags: ", sortedTags);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Answer: You could use the following code. This basically splits arr up into finalTags and finalWeights.
.flat() flattens the array ([1, [2, [3]]] would become [1, 2, 3])
finalTags.filter((item, index) => finalTags.indexOf(item) >= index).sort(); remove's the duplicates.

const arr = [{
    tags: ['f', 'b', 'd'],
    weight: 7,
    something: 'sdfsdf'
  },
  {
    tags: ['a', 'b', 'c', 'd', 'e'],
    weight: 6,
    something: 'frddd'
  },
  {
    tags: ['f', 'c', 'e', 'a'],
    weight: 7,
    something: 'ththh'
  },
  {
    tags: ['a', 'c', 'g', 'e'],
    weight: 5,
    something: 'ghjghj'
  }
];

let finalTags = arr.map(e => e.tags);
finalTags = finalTags.flat();
finalTags = finalTags.filter((item, index) => finalTags.indexOf(item) >= index).sort();

let finalWeight = arr.map(e => e.weight);
finalWeight = finalWeight.filter((item, index) => finalWeight.indexOf(item) >= index).sort();

console.log(finalTags);
console.log(finalWeight);

Sources:
Removing duplicates: https://gomakethings.com/removing-duplicates-from-an-array-with-vanilla-javascript/


Easy ISO customizing tool for Ubuntu?

Question: I am searching for a way to create a custom ISOs for (K)Ubuntu desktop to provision physical machines (like laptops), esp. with lower RAM, through PXE / Netboot. Goal is a mostly completely unattended install.
I had some issues with default ISOs (too large, ISO download fails with "no space left") as well as with "netboot" images which seem to not have been there for quite a while, now coming back (their kernels may lack drivers, esp. for network cards). Even if the latter could be hacked around, still it would be better to generate an own ISO.
Question 1: Is there a tool for ISO customization for Ubuntu,like mksusecd for SUSE distributions?
Ideally, such tool would allow exclusion of some groups of packages (office, browsers, desktop environments...) through a cmd one-liner, repacking the ISO as desired.
Question 2: Apart from specialized tools: if I follow the "normal" procedure under LiveCDCustomization - Community Help Wiki (which seems quite a tedious task) - is there an easy approach to exclude such package groups without breaking things?
Maybe someone even has a script to automate this?
P.S.:
I am aware of this and similar answers, but unfortunately everything I could find was quite dated with no active development...
Comment: Does this answer your question? [How to use Cubic to create a custom Ubuntu live CD image?](https://askubuntu.com/questions/741753/how-to-use-cubic-to-create-a-custom-ubuntu-live-cd-image)
Comment: Take a look here: https://launchpad.net/~cubic-wizard/+archive/ubuntu/release
Answer:
Question 1: Is there a tool for ISO customization for Ubuntu,like mksusecd for SUSE distributions?

Cubic is the most popular. But all are 3rd party and need you to trust its creator. Most also start from a desktop ISO.
I would suggest to do it yourself and start from a server version using autoinstall (link has a examples). It is small and supports yaml. Biggest advantages:  it is re-usable on newer Ubuntu's plus it is not 3rd party.
From the Ubuntu discource:

Introduction
Since version 20.04, the server installer supports automated installation mode (autoinstallation for short). You might also know this feature as unattended, hands-off, or preseeded installation.
Autoinstallation lets you answer all those configuration questions ahead of time with an autoinstall config, and lets the installation process run without any interaction.

Quick start
Documentation
AutoInstall generator (converts a preseed file to an autoinstall yaml)

Up to this part you can make it as generic as possible and you can then add all the packages you want to make a desktop. What desktop is up to you but these packages do not need to be part of the ISO and can be fetched on-line making the ISO rather small. You just add, for instance, ubuntu-deskop for a total desktop or if you want you could add Ubuntu minimal, or if you are really brave add packages yourself to build your own desktop (without anything you would consider clutter :) )

Easy ISO customizing tool for Ubuntu?


Submit form if condition is true

Question: I have this form:
<form action="http://targatesite.com" target="_blank" method="post" name="xyz" id="abc">
      <input type="hidden" name="email" value="user_email" />
      <input type="submit" name="sbmt" id="sbmt" value="user_value" class="user_class"/>
</form>

Suppose there is a variable VAR. The form can be submitted only when the value of VAR is 1.
In detail On click on submit it will firstly check the value of VAR and if it returns true from will submitted and redirect to page given in action. And if it returns False it will show a message that Please check value of VAR
Imp VAR is not the field of form. We are getting this value from database.
Comment: One more amendment in question If VAR=1 the form should be successfully submitted. And if not it should show error that "check the value of VAR. "
Answer: Add onSubmit="return submit();"
<form action="http://targatesite.com" target="_blank" method="post" name="xyz" id="abc"> <input type="hidden" name="email" value="user_email" />
    <input type="submit" name="sbmt" id="sbmt" value="user_value" class="user_class" onSubmit="return submit();"/>
    </form>

Try this Script :
 function submit(){
            if(var==1){
                return true;
           }
           else{
               alert("Please check value of VAR")
               return false;
           }
    }

Comment: One more amendment in question If VAR=1 the form should be successfully submitted. And if not it should show error that "check the value of VAR. "
Answer: $('#abc').on('submit', function(){
     if(VAR == 1){
        return true;
     }
   alert('Please check value of VAR');
   return false;
});

This will work. The only thing you need to check is that VAR is in the scope of this function.
Comment: One more amendment in question If VAR=1 the form should be successfully submitted. And if not it should show error that "check the value of VAR. "
Answer: try this
var MYVAR=true;
$('#abc').submit(function(){
     if(MYVAR){
        return true;
     }
   alert('check the value of VAR');
   return false;
});

Comment: One more amendment in question If VAR=1 the form should be successfully submitted. And if not it should show error that "check the value of VAR. "
Answer: Yes you can check VAR variable value from database,
when you have to submit form, you can code like this
if($_POST['sbmt']){
 $query = 'SELECT var FROM tablename';
 // here you can check var value
 if(VAR==1){
  //submit your form
 } else {
  $error_msg = 'Please check value of VAR';
 }
}

print this $error_msg whenever you want to show.
Comment: I did. It means the value of VAR comes from database, nothing more. How can you prevent submit with php?

Submit form if condition is true


Owner of mounted folder changes when it is actually mounted

Question: I have a folder /media/user/drive_name that is set in fstab to automount an NTFS drive /dev/sdc2 /media/user/drive_name ntfs auto
The problem is that when the drive is mounted, it and all of it's contents still owned by root. Even if I try to chown it or anything inside, it still remains under root.
When I unmount, it goes back to being owned by my user. Even if I mount it from nautilus under my user, it still becomes owned as root.
I want the folders inside to be owned by me. How can I do it?
Answer: If you give the command apropos ntfs you will find there's a man page man mount.ntfs describing the command and driver which will be used when you mount a filesystem of type ntfs.
If you just want all files to appear as if they belong to you, just change the /etc/fstab entry field auto to auto,permissions, or if this doesnt work when mounting via nautilus you can also add ,uid=1000 where 1000 is whatever number the id command shows for your login.
If you want to preserve more finely detailed interoperability with microsoft see the man page for how to map different ntfs user "sids" to Ubuntu ids.
Comment: Is there a way to mount the drive from nautilus and have it under my user?
Comment: I dont see a way at the moment, but I dont understand how nautilus sends the request to udisksd. You can do by hand what I imagine nautilus should do, and it works ok. eg `udisksctl mount --block-device /dev/sdb1` for a disc partition sdb1


Disabling or changing language for spell checking on Skype

Question: Skype is drawing red lines under non-English words I type. How to disable it, or change the spell checking language? Apparently, the spell checker is not a part of Skype itself.
Using Ubuntu 16.04 with Gnome, Skype 188.8.131.52.
Comment: I'm using Xubuntu 16.04 LTS with Xfce '.12 and Skype 188.8.131.52. I made it by changing all Skype interface language. You can do that in *File/View profile* menu... And in the popup you can change the language .
Answer: Disclaimer: This is an old question but I haven't found a solution before fiddling it by myself. Hopefully it can reach more people given the annoyance.
Removing Skype's ability to write dictionaries to disk isn't fatal.
cd ~/.config/skypeforlinux/dictionaries
rm *
sudo chattr +i .

Using chmod(1) wouldn't remove Skype's ability to remove and recreate the dictionary directory. Note that chattr(1) is Linux-specific and for FreeBSD you'd use chflags schg and so on.
Furthermore please note that Skype ignores spellchecking preferences from KDE.
On some installations, the path is ~/.config/skypeforlinux/Dictionaries or even both variants might exist.


How exactly Deferred functions are useful in Go and what alternative is available in other languages?

Question: I know it's to deferred a process. I also read examples like it's good to use when dealing with File and other resources. My question is, is it something not being handled in other languages like Python etc? If yes how Go provides some distinctive feature?
Say there are two functions f1 and f2 and I want to call f2 when f1 is done. I can do something like:
def f1():
  done = False
  print('I am doing extensive work')
  done = True
  return done

def f2():
  print('here we go')

if f1():
  f2()

Is defer doing same thing by minimizing coding efforts?
Answer: defer as the name suggests, will delay execution of the deferred function until the calling function body exits, no matter the exit point and conditions. Thus , your function f1 deffering f2 will make sure that f2 is called even if something inside f1 fails with an exception. I think of it as the finally clause from a try/catch block.
In python, the closest thing i can think of that's like defer are context managers . Notice how i say closest and not identical, since their purposes overlap a bit , but only a bit
Answer: To understand defer, you need to understand the alternative.
In complex code dealing with many resources you end up doing things like this (pseudo code):
mtx.Lock()
file1, err := os.Open(...)
if err != nil {
    mtx.Unlock()
    return err
}
conn, err := net.Dial(...)
if err != nil {
    file1.Close()
    mtx.Unlock()
    return err
}
file2, err := os.Open(...)
if err != nil {
    conn.Close()
    file1.Close()
    mtx.Unlock()
    return err
}
do_things()
file2.Close()
conn.Close()
file1.Close()
mtx.Unlock()
return nil

This gets verbose fast. Also, it's error-prone in the long term since someone editing code and maybe moving the opening of the network connection to before opening file1 might not correctly update all the error handling paths.
In C, a common idiom here is to collect all the cleanup of resources at the end of the function and do something like this:
    ret = ERROR;
    lock(mtx);
    fd1 = open(...);
    if (fd1 == -1)
        goto err1;
    conn = net_conn(...);
    if (conn == -1)
        goto err2;
    fd2 = open(...);
    if (fd2 == -1)
        goto err3;
    do_things();

    ret = 0;
    close(fd2);
err3:
    close(conn);
err2:
    close(fd1);
err1:
    unlock(mtx);
    return ret;

This is not pretty either and it's quite easy to get this wrong too.
As a comparison doing the same thing with defer we get:
mtx.Lock()
defer mtx.Unlock()
file1, err := os.Open(...)
if err != nil {
    return err
}
defer file1.Close()
conn, err := net.Dial(...)
if err != nil {
    return err
}
defer conn.Close()
file2, err := os.Open(...)
if err != nil {
    return err
}
defer file2.Close()
.... do things ...
return nil

It's clear, concise, anyone who knows Go will understand what happens and it's very hard to get wrong or break in the future.
Answer: Go's defer statement is just another approach, it has its pros and cons (not necessarily is the best). Other languages do offer alternatives to handle proper resource closes. For example Java offers Exceptions and try-catch blocks.
Quoting from Go FAQ: Why does Go not have exceptions?

We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code. It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional.
Go takes a different approach. For plain error handling, Go's multi-value returns make it easy to report an error without overloading the return value. A canonical error type, coupled with Go's other features, makes error handling pleasant but quite different from that in other languages.
Go also has a couple of built-in functions to signal and recover from truly exceptional conditions. The recovery mechanism is executed only as part of a function's state being torn down after an error, which is sufficient to handle catastrophe but requires no extra control structures and, when used well, can result in clean error-handling code.
See the Defer, Panic, and Recover article for details.

The advantage of using defer compared to Java's try-catch for example is that the code  that handles the closing or disposing of an opened resource is right next to the code that opened it.
For example:
f, err := os.Open("file.txt")
if err != nil {
    log.Printf("Failed to open file: %v", err)
    return
}
defer f.Close()

// f is open you may read from it
...

If other languages where disposing of resources is moved to another code block, it is harder to follow where and if you actually took care of disposing it.


List Activity not starting

Question: private ListView listView;
private List<String> userNames,desc,lat,lon,image, placeNames;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_places_list);
    setTitle("Places List");

    listView=(ListView) findViewById(R.id.placesListView);
    userNames=new ArrayList<String>();
    placeNames = new ArrayList<String>();
    desc=new ArrayList();image=new ArrayList();
    lat=new ArrayList();lon=new ArrayList();

    userNames=getIntent().getStringArrayListExtra("userNames");
    placeNames=getIntent().getStringArrayListExtra("placeNames");
    desc=getIntent().getStringArrayListExtra("desc");
    image=getIntent().getStringArrayListExtra("image");
    lat=getIntent().getStringArrayListExtra("lat");
    lon=getIntent().getStringArrayListExtra("lon");

    final ArrayAdapter arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,userNames);
    listView.setAdapter(arrayAdapter);

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object referencejava.util.List.size()' on a null object reference
How to avoid the exception?
Comment: The List 'userNames' is null somehow, check that !!
Answer: I think when you are trying to set userNames in adapter then it will occur just because you are getting userNames list as null so first check and then set like below
if(userNames!=null){
final ArrayAdapter arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,userNames);
    listView.setAdapter(arrayAdapter);
}

Answer: Now the app is not crashing , but list isn't displaying.
I am able to display values in invoking activity.
    `enter code here`
if(userNames.size()>0)
{
    Log.i("OOOOOOO",userNames.get(0)+"'"+userNames.get(1));
}
Intent intent=new Intent(ViewActivity.this,PlacesListActivity.class);        intent.putStringArrayListExtra("userNames",userNames);intent.putStringArrayListExtra("placeNames",placeNames);
                intent.putStringArrayListExtra("desc",desc);intent.putStringArrayListExtra("image",image);
                intent.putStringArrayListExtra("lat",lat);intent.putStringArrayListExtra("lon",lon);
                startActivity(new Intent(ViewActivity.this,PlacesListActivity.class));

Comment: If I include the same log statement                            .................................................................................................................if(placeNames.size()>0){{
  Log.i("OOOOOOO",placeNames.get(0)+"'"+placeNames.get(1));}.......................in the List activity,  the exception is repeated
Comment: Instead of `startActivity(new Intent(ViewActivity.this,PlacesListActivity.class));` change to `startActivity(intent);`.
Comment: Debug and make sure all arrayList has data in `ViewActivity` class.

List Activity not starting


Redirect URI of an Azure Active Directory App Registration when backend on other server

Question: I'm about to deploy an Angular HTML frontend as an Azure App Service. Within the app settings, there is the option to enable Azure Active Directory authentication. If enabled, when I navigate to https://my-awesome-project.azurewebsites.net, I'm redirected to a MS login screen where I can enter my AAD credentials. However, for this to work I need my app to be registered with AAD.
While following this guide is only three steps, I still have one question:
Since in my scenario the HTML frontend (Azure App Serivce) and the Node.js backend API are on separate servers, the Redirect URI of my app registration should point to an HTTP endpoint of my backend server, right?
Lots of tutorials I have seen say to put your app's web URL into the Redirect URI field. But in this case, how would my HTML/js frontend know what to do with it?
After all, Microsoft says that "We'll return the authentication response to this [Redirect] URL after successfully authenticating the user ..."
Cheers
Answer: You need to understand how the authentication works.If you are using Azure Active Directory for authentication then any application that you require to get authenticated needs to get registered with AAD (Azure Active Directory). In your case both front and backend needs to be registered with AAD and your backend needs to have trust on the frontend application and that you configure in Azure.  https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-auth-aad
Your frontend needs to control the flow and after authentication you get redirect to frontend and it should receive token from AAD and you will have to use that token in authorization header to access the backend APIs. For this kind of flow you can use AADL (AAD library https://github.com/AzureAD/azure-activedirectory-library-for-js) that can take care of this and generally a better choice which this kind of authentication flow.
Another point why do you need to use Azure App service for Angular/HTML when it's a static front end ? You can look into Azure Static hosting site which would save you heaps of cost.  https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-static-website
More resources
https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-angularjs-spa
Comment: But nonetheless, would the redirect URI be a backend server's endpoint?

++++ Thanks for the hint with hosting @ azure storage, seems to be sufficient in my case.  The backend API server however is isolated within a VNet with no outside/public access. The App Service had this VNet integration feature which basically created a VPN tunnel behind the scenes to connect to it. I don't find this option with Storage :/
Comment: The redirection is on the end which can carry the token and run the flow. If you point the redirection to backend server the frontend wouldn't know about anything and can't control the flow. The authentication comes to frontend and it would carry the token with every request. Since you mention your backend is sitting behind the firewall , have a look at Azure Relay for communication.  https://learn.microsoft.com/en-us/azure/service-bus-relay/relay-what-is-it


How to cover seams in plywood walls?

Question: I'm putting up a plywood wall in my garage workshop and have some unsightly seams; 1/8" or less gaps except around floor where I plan on installing baseboard anyway.  I've had to cut smaller segments of plywood to work around some workbenches installed by the previous owner so there's vertical and horizontal seams, if that matters.  I plan on painting the wall when finished but wondering what would be best to use to fill in/cover the seams before painting.
Comment: Why not painters' caulk?
Comment: It's a garage shop, not the Louvre. And you're painting it, so painters caulk is not only the obvious solution, it's the right solution. That's already two steps closer to the Louvre than your average garage shop. Feel free to grain-fill the plywood and use umpteen coats of primer and sanding it back to obtain a flawless surface before the final coat of paint, then you can be 3 steps closer... Or you could skip all that and start screwing things to it and use it.
Comment: My garage has plywood walls throughout; the builder added thin strips of 1-1/2" to cover all the seams. I think they're nailed in, but they might just be glued, too. They look nice, but they also make it annoying when I want to put something flush against the wall.
Comment: If you're opposed to covering it with a thin piece of something like screen molding, then I think caulk is going to be the best option.  You want some elasticity for a little movement (bondo might crack easily).
Comment: The previous owner of my house used drywall mud over the seams in the plywood wall in the garage.  It definitely cracked, so don't do that.  I vote for painters caulk or something flexible.  Run a finger over it to remove the bead if you want it to look smooth.
Comment: Painter's caulk is an option, I suppose, I just don't know if there's any caveats to that or if there is a better solution like Bondo or something.  Some of the seams are flush but I guess if the caulk sits on top instead of filling the gap then it might not be a problem.

I don't want to cover with trim/veneer for that same issue of hanging things on the wall.  This being a workshop, I want places to hang tools and not have trim getting in the way.
Answer: The overwhelming consensus here seems to be standard painter's caulk so marking this as answered.  Thanks to all that responded.
Answer: The most astheticaly(sp) pleasing way to cover gaps in a plywood wall with flush results is to glue up a veneer on the gaps.  caulking, silicone, anything else will be ugly, dirty, and eventually fall out.

How to cover seams in plywood walls?