text:
Q: Creating a new row that is the difference of one row from a scalar value Assuming I have the following toy model, the dataset is called Answer:
Country    year     Y       Ex1       Ex2
A          2015    lala     5         5
A          2016    Popo     2         2
B          2015    baba     15        60
B          2016    nono     9         20

I want to find the mean of the value 2016 and 2015 across the board, for all numerical variables. Once I have the mean, I want new rows for both 2015 and 2016, highlighting the difference between the original value and the mean.
In this instance, Country A: mean(Ex1) = 3.5, mean(Ex2) = 3.5
My final dataset should look like:
Country    year     Y       Ex1       Ex2     demeanEx1    demeanEx2
A          2015    lala     5         5          .            .
A          2016    Popo     2         2          .            .
A          2015    lala     .         .          1.5         1.5
A          2016    Popo     .         .         -1.5        -1.5
B          2015    baba     15        60         .            .
B          2016    nono     9         20         .            .
B          2015    baba     .         .          3            20
B          2016    nono     .         .         -3           -20

If anyone is wondering, I am trying to implement fixed-effects manually, by creating demeaned values for my variables. I have 90 variables in my current dataset; finding means for all variables manually will be a long task.
I tried using the demeanlist command under lfe package, but R keeps aborting every time I try running it.
I know fixed effects can be run with plm package, using model = within, but I am trying to implement it manually.

A: We can do this with tidyverse.  After grouping by 'Country', transmute_at to create the 'demean' columns by subtracting the values of 'Ex' columns from their mean, then bind the data with the original data (bind_rows), arrange by 'Country', 'year', replace the NAs in 'year', 'Y' for each 'Country' with the non-NA elements of that columns
library(tidyverse)
df1 %>%
   group_by(Country) %>%
   transmute_at(vars(starts_with("Ex")),
        list(demean = ~ . - mean(.))) %>%
   bind_rows(df1, .) %>%
   arrange(Country, year ) %>%
   group_by(Country) %>%
   mutate_at(vars(year, Y), list(~ replace(., is.na(.), .[!is.na(.)])))
# A tibble: 8 x 7
# Groups:   Country [2]
#  Country  year Y       Ex1   Ex2 Ex1_demean Ex2_demean
#  <chr>   <int> <chr> <int> <int>      <dbl>      <dbl>
#1 A        2015 lala      5     5       NA         NA
#2 A        2016 Popo      2     2       NA         NA
#3 A        2015 lala     NA    NA        1.5        1.5
#4 A        2016 Popo     NA    NA       -1.5       -1.5
#5 B        2015 baba     15    60       NA         NA
#6 B        2016 nono      9    20       NA         NA
#7 B        2015 baba     NA    NA        3         20
#8 B        2016 nono     NA    NA       -3        -20

Or in a slightly modified way
df1 %>%
   group_by(Country)  %>%
   nest %>%
   mutate(data = map(data, ~
              .x %>%
                   transmute_at(vars(starts_with("Ex")),
                       list(demean = ~ . - mean(.))) %>%
                   bind_cols(.x[1:2], .) %>%
                   bind_rows(.x, .))) %>%
   unnest

data
df1 <- structure(list(Country = c("A", "A", "B", "B"), year = c(2015L,
 2016L, 2015L, 2016L), Y = c("lala", "Popo", "baba", "nono"),
Ex1 = c(5L, 2L, 15L, 9L), Ex2 = c(5L, 2L, 60L, 20L)),
 class = "data.frame", row.names = c(NA, -4L))

A: A base R attempt, using ave to get the differences from the respective means, and some indexing to overwrite the sets of old and new values:
meas <- c("Ex1","Ex2")
s <- seq_len(nrow(dat))

out <- dat[rep(s,2),]
out[-s, meas] <- NA
out[-s, paste0("demean",meas)] <- lapply(
    dat[meas],
    function(x) x - ave(x,dat["Country"])
)
out

#    Country year    Y Ex1 Ex2 demeanEx1 demeanEx2
#1         A 2015 lala   5   5        NA        NA
#2         A 2016 Popo   2   2        NA        NA
#3         B 2015 baba  15  60        NA        NA
#4         B 2016 nono   9  20        NA        NA
#1.1       A 2015 lala  NA  NA       1.5       1.5
#2.1       A 2016 Popo  NA  NA      -1.5      -1.5
#3.1       B 2015 baba  NA  NA       3.0      20.0
#4.1       B 2016 nono  NA  NA      -3.0     -20.0

Where dat was:
dat  <- read.table(text="Country    year     Y       Ex1       Ex2
A          2015    lala     5         5
A          2016    Popo     2         2
B          2015    baba     15        60
B          2016    nono     9         20", header=TRUE)

A: Calculate and append the demean* columns and then rbind that to itself NA-ing out the appropriate columns.  Finally reorder.  No packages are used.
a <- transform(Answer, demean1 = Ex1 - ave(Ex1, Country), demean2 = Ex2 - ave(Ex2, Country))
a2 <- rbind(transform(a, demean1 = NA, demean2 = NA), transform(a, Ex1 = NA, Ex2 = NA))
a2[order(a2$Country), ]

The result is:
  Country year    Y Ex1 Ex2 demean1 demean2
1       A 2015 lala   5   5      NA      NA
2       A 2016 Popo   2   2      NA      NA
5       A 2015 lala  NA  NA     1.5     1.5
6       A 2016 Popo  NA  NA    -1.5    -1.5
3       B 2015 baba  15  60      NA      NA
4       B 2016 nono   9  20      NA      NA
7       B 2015 baba  NA  NA     3.0    20.0
8       B 2016 nono  NA  NA    -3.0   -20.0

or if we don't know how many Ex columns there are then first define ix as the column numbers of the Ex columns and calculate the demeaned values as demeans.
Create a data frame of three blocks of columns as shown.  Finally sort that.
# ix <- 4:ncol(Answer)
ix <- grep("Ex", names(Answer)) ##

demeans <-  Answer[ix] - sapply(Answer[ix], ave, Answer$Country)
names(demeans) <- paste0("demean", names(demeans))

aa <- cbind(
  Answer[-ix],
  rbind(Answer[ix], NA * Answer[ix]),
  rbind(NA * demeans, demeans)
)
aa[order(aa$Country), ]


text:
Q: How to increment a value in MySQL database with PHP? I am trying this code, but it isn't working.
The main problem is in these variables or in the script given at the bottom.
  <?PHP
  $upVote1 = "UPDATE facerate SET votes = votes + 1 WHERE Picture = '".$idOptain1."'";
  $upVote2 = "UPDATE facerate SET votes = votes + 1 WHERE Picture = '".$idOptain2."'";

  $upIgnore1 = "UPDATE facerate SET ignores = ignores + 1 WHERE Picture = '".$idOptain2."'";
  $upIgnore2 = "UPDATE facerate SET ignores = ignores + 1 WHERE Picture = '".$idOptain1."'";
  ?>

  <img onClick='renderData1()' src="<?php echo $img1['Picture'] ?>" />

  <img onClick='renderData2()' src="<?php echo $img2['Picture'] ?>" />

A: mysql_query does not support multiple queries. You will need to break it up into a single query per call.

A: You should set up some Ajax request to register user votes: This might give you some idea how to do it (using jQuery here):
Javascript function to execute on vote click event :
function upvote_picture(id){
    $.ajax({
        type: 'POST',
        url: 'vote.php',
        dataType: 'json',
        data: {
            picture_id: id
        },
        success: function (data) {
            alert(data);
        }
    });
}

vote.php file:
<?php
// Any error or warning in this script will break JSON response !

function send_json($array)
{
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($array);
    exit();
}

// Add query execution status variables and messages here
$response = array();

$id = !empty($_POST['picture_id']) ? $_POST['pciture_id'] : FALSE;

if($id){

    // Do you query here
    if ( mysql_query(....)) {
        $response['success'] = TRUE;
    } else {
        $response['success'] = FALSE;
    }
} else {
    $response['success'] = FALSE;
}

send_json($response);

?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a material-ui responsive to reactjs? Tell me which tool to use based on material for design with react components?
Try http://www.material-ui.com - for reactjs, but there is no responsive grid
Try https://github.com/react-materialize/react-materialize - This lib is not reliable and difficult for stability working of the application

A: material-ui already uses flexbox for their layouts. The components themselves are responsive as well. It seems that they did implement a grid layout. However, it looks like it's only available in the pre-release branch. The way I see it you have three options here:

*

*Implement your own responsive grid using flexbox

*Use a grid layout library, such as react-grid-layout(for React) or flexboxgrid

*Get their pre-release channel npm install material-ui@next


text:
Q: wxPython not binding callbacks to events properly Here's a roughly minimal demonstrative example:
import wx

app = wx.App(False)
frame = wx.Frame(None)

menuBar = wx.MenuBar()
menu = wx.Menu()
menuBar.Append(menu, "&Menu")
frame.SetMenuBar(menuBar)

for name in ['foo','bar','baz']:
    menuitem = menu.Append(-1,"&"+name,name)
    def menuclick(e):
        print(name)
    frame.Bind(wx.EVT_MENU, menuclick, menuitem)

frame.Show(True)
app.MainLoop()

The issue is that every menu item, when clicked, prints "baz".  Shouldn't the menuclick function wrap up the appropriate name in its closure and keep the original name around?

A: After the for loop name will be "baz", it's value will not go back in time to when you bound the menuclick to the menu event.
You can get to the menu item name via the event itself like this:
def menuclick(e):
    print(menu.FindItemById(e.Id).Label)

A: I found this solution, by I'm not sure why this works where the inner-def version doesn't:
from functools import partial

def onclick(name,e):
    print(name)

for name in ['foo','bar','baz']:
    menuitem = menu.Append(-1,"&"+name,name)
    frame.Bind(wx.EVT_MENU, partial(onclick,name), menuitem)


text:
Q: Typescript - Get class of caller of method I have a function which determines the calling function via Function.caller.
Is it possible to determine whether the caller belongs to a class, is a class, etc?
(I Know that when function.caller == null it is the root level from which it was called.)
Some code which may help in understand what i'm trying to achieve.
log(component: object, level: LogLevel, category: ILogCategory, message: string)
  {
    if(!component)
      let callingComponent = log.caller;
      // PSEUDOCODE
      if(parent of caller is class)
      callingComponent = class;

      //...
    }
  }

EDIT
I want to get the class to which the caller of my method belongs to.

A: I see your question as having two parts:
The first roadblock you'll hit is trying to determine who called the function. I know you said you're using Function.caller, but that feature is deprecated. Building code ontop of a deprecated feature doesn't seem like a good idea, even if the features is currently supported across most browsers. So you might take a step back and ask why you care who called the function. The logging use case is a good one (i.e. you want to log what class added the log entry), but I can't think of many other good ones. For the logging use case, you probably just need to add a parameter to the function that allows the caller to pass their name in. If you're dead set on not doing that, you could try using the error throwing technique described here but I can't vouch for it: https://stackoverflow.com/a/29572569/11300565
The second (and main) part of your question (if you can get the caller, how can you tell if its a class?) doesn't have a good answer. One approach would be to make all your classes inherit from some base class and then provide a static typeguard on that base class (MyBaseClass.isInstanceOfMe(unknownObject)) that you could use. Other than implementing something on your own, I'm not aware of a built-in way to detect typescript classes, since they get compiled down to javascript at the end of the day and are difficult to distinguish from objects and functions.


text:
Q: Mongodb Slave replication lag We using standard mongo setup: 2 replicas + 1 arbiter.
Both replica servers use same AWS m1.medium with RAID10 EBS.
We experiencing constantly growing replication lag on secondary replica.

I tried to do full-resync, you can see it on graph, but it helped only for some hours.
Our mongo usage is really low now, and frankly i can't understan why it can be.
iostat 1 for secondary:
avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          80.39    0.00    2.94    0.00   16.67    0.00

Device:            tps    kB_read/s    kB_wrtn/s    kB_read    kB_wrtn
xvdap1            0.00         0.00         0.00          0          0
xvdb              0.00         0.00         0.00          0          0
xvdfp4           12.75         0.00       189.22          0        193
xvdfp3           12.75         0.00       189.22          0        193
xvdfp2            7.84         0.00        40.20          0         41
xvdfp1            7.84         0.00        40.20          0         41
md127            19.61         0.00       219.61          0        224

mongostat for secondary (why 100% locks? i guess its the problem):
insert  query update delete getmore command flushes mapped  vsize    res faults locked % idx miss %     qr|qw   ar|aw  netIn netOut  conn        set repl       time
   *10     *0    *16     *0       0     2|4       0  30.9g  62.4g  1.65g      0      107          0       0|0     0|0   198b     1k    16 replset-01  SEC   06:55:37
    *4     *0     *8     *0       0    12|0       0  30.9g  62.4g  1.65g      0     91.7          0       0|0     0|0   837b     5k    16 replset-01  SEC   06:55:38
    *4     *0     *7     *0       0     3|0       0  30.9g  62.4g  1.64g      0      110          0       0|0     0|0   342b     1k    16 replset-01  SEC   06:55:39
    *4     *0     *8     *0       0     1|0       0  30.9g  62.4g  1.64g      0     82.9          0       0|0     0|0    62b     1k    16 replset-01  SEC   06:55:40
    *3     *0     *7     *0       0     5|0       0  30.9g  62.4g   1.6g      0     75.2          0       0|0     0|0   466b     2k    16 replset-01  SEC   06:55:41
    *4     *0     *7     *0       0     1|0       0  30.9g  62.4g  1.64g      0      138          0       0|0     0|1    62b     1k    16 replset-01  SEC   06:55:42
    *7     *0    *15     *0       0     3|0       0  30.9g  62.4g  1.64g      0     95.4          0       0|0     0|0   342b     1k    16 replset-01  SEC   06:55:43
    *7     *0    *14     *0       0     1|0       0  30.9g  62.4g  1.64g      0       98          0       0|0     0|0    62b     1k    16 replset-01  SEC   06:55:44
    *8     *0    *17     *0       0     3|0       0  30.9g  62.4g  1.64g      0     96.3          0       0|0     0|0   342b     1k    16 replset-01  SEC   06:55:45
    *7     *0    *14     *0       0     3|0       0  30.9g  62.4g  1.64g      0     96.1          0       0|0     0|0   186b     2k    16 replset-01  SEC   06:55:46

mongostat for primary
insert  query update delete getmore command flushes mapped  vsize    res faults locked % idx miss %     qr|qw   ar|aw  netIn netOut  conn        set repl       time
    12     30     20      0       0       3       0  30.9g  62.6g   641m      0      0.9          0       0|0     0|0   212k   619k    48 replset-01    M   06:56:41
     5     17     10      0       0       2       0  30.9g  62.6g   641m      0      0.5          0       0|0     0|0   159k   429k    48 replset-01    M   06:56:42
     9     22     16      0       0       3       0  30.9g  62.6g   642m      0      0.7          0       0|0     0|0   158k   276k    48 replset-01    M   06:56:43
     6     18     12      0       0       2       0  30.9g  62.6g   640m      0      0.7          0       0|0     0|0    93k   231k    48 replset-01    M   06:56:44
     6     12      8      0       0       3       0  30.9g  62.6g   640m      0      0.3          0       0|0     0|0    80k   125k    48 replset-01    M   06:56:45
     8     21     14      0       0       9       0  30.9g  62.6g   641m      0      0.6          0       0|0     0|0   118k   419k    48 replset-01    M   06:56:46
    10     34     20      0       0       6       0  30.9g  62.6g   640m      0      1.3          0       0|0     0|0   164k   527k    48 replset-01    M   06:56:47
     6     21     13      0       0       2       0  30.9g  62.6g   641m      0      0.7          0       0|0     0|0   111k   477k    48 replset-01    M   06:56:48
     8     21     15      0       0       2       0  30.9g  62.6g   641m      0      0.7          0       0|0     0|0   204k   336k    48 replset-01    M   06:56:49
     4     12      8      0       0       8       0  30.9g  62.6g   641m      0      0.5          0       0|0     0|0   156k   530k    48 replset-01    M   06:56:50

Mongo version: 2.0.6

A: Ok, we found the problem. We not the first, it was capped collections (logging).
Actually i checked this version before this post, but miss point that indexes did't get sync automatically.
It means that you have to stop replica slave member, remove it from replica (just remove replicaSet from mongo.config), start and add index to capped collections:
db.logs.ensureIndex({ _id: 1 }, { unique: true }), and return this instance to replica.


text:
Q: How to browserify module ethereumjs-tx? I have this demo code I want to broserify:
var Tx = require('ethereumjs-tx')
var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')

var rawTx = {
  nonce: '0x00',
  gasPrice: '0x09184e72a000',
  gasLimit: '0x2710',
  to: '0x0000000000000000000000000000000000000000',
  value: '0x00',
  data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
}

var tx = new Tx(rawTx)
tx.sign(privateKey)

var serializedTx = tx.serialize()
console.log(serializedTx.toString('hex'))

I have installed ethereum-tx almost succesfully like this:
npm install -g ethereumjs-tx
    ...
    npm WARN enoent ENOENT: no such file or directory, open '/root/package.json'
    npm WARN root No description
    npm WARN root No repository field.
    npm WARN root No README data
    npm WARN root No license field.

I am not sure whether these warning messages are important or I just should ignore them...
Nevertheless code above runs ok in nodejs. But the problem appears when trying to broserify it, creating a file main.js that is the code above and:
browserify main.js -o bundle.js
    Error: Cannot find module 'ethereumjs-tx' from 'myHomeDir'

My nodejs has a folder for ethereumjs-tx, that seems ok to me:
# ls -la /usr/local/lib/node_modules/ethereumjs-tx/
total 84
drwxr-xr-x  6 nobody root  4096 Jan 11 08:46 .
drwxr-xr-x  6 root   root  4096 Jan 11 08:46 ..
drwxr-xr-x  2 nobody root  4096 Dec 14 00:14 docs
drwxr-xr-x  2 nobody root  4096 Dec 14 00:14 examples
-rw-r--r--  1 nobody root  2028 Dec 14 00:14 fake.js
-rw-r--r--  1 nobody root  7395 Dec 15 03:40 index.js
-rw-r--r--  1 nobody root   600 Dec 14 00:14 karma.conf.js
-rw-r--r--  1 nobody root 16726 Dec 14 00:14 LICENSE
drwxr-xr-x 76 root   root  4096 Jan 11 08:46 node_modules
-rw-r--r--  1 nobody root  1187 Dec 14 00:14 .npmignore
-rw-r--r--  1 nobody root  3955 Dec 14 00:18 .package.json
-rw-r--r--  1 nobody root  4369 Jan 11 08:46 package.json
-rw-r--r--  1 nobody root  1871 Dec 15 03:40 README.md
drwxr-xr-x  2 nobody root  4096 Jan 11 08:46 test
-rw-r--r--  1 nobody root   599 Dec 14 00:14 .travis.yml

Any hint about how to get this code broserified? What am I doing wrong? Thx!

A: You need to install any module locally in order to browserify it. At least, I didn't find any option to get browserify to work with globally installed packages.
So, in the root of your project, you need to do:
npm install ethereumjs-tx --save-dev

--save indicates the package will not only be downloaded to a local node_modules folder, but also will modify your package.json and write down the dependency, so any further npm install command over that package.json will install ethereumjs-tx with the same version.
-dev indicates that the package will be saved as a development dependency, which means is not a package used by your application in production as a node application: so every package you bundle to be used in the client side should be a devDependency.
When you run npm install, npm expects a valid package.json to exist. The warnings npm is complaining about are due to a this package.json not existing in your project, and thus not having some package.json fields such as description. An easy way to initialize a package.json when you don't have one is to run npm init.
In fact it seems you're creating the bundle at '/root/', which seems a strage location for a web project.


text:
Q: "Explicit" embedding of $\ell^1$ as a closed subalgebra of a direct sum of matrix algebras For sake of brevity let $A$ denote the Banach algebra formed by equipping $\ell^1({\mathbb N})$ with pointwise multiplication. This algebra is clearly not isomorphic as a Banach algebra to any uniform algebra (since it has idempotents of arbitrarily large norm).
It has been known since the 1970s that there exists a Hilbert space $H$ and a continuous injective algebra homomorphism $\theta:A\to B(H)$ which has (norm-)closed range. That is, $A$ is isomorphic to a non-self-adjoint operator algebra. However, the proof is non-explicit; the only argument I have seen uses the fact that multiplication $A \otimes A \to A$ extends continuously to the injective tensor product of $A$ with itself, and then uses abstract GNS-flavoured techniques to build the required space $H$. See

Varopoulos, N. Th. Some remarks on $Q$-algebras. Ann. Inst. Fourier (Grenoble) 22 (1972), no. 4, 1–11.
Davie, A. M. Quotient algebras of uniform algebras. J. London Math. Soc. (2) 7 (1973), 31–40.

For each $n$ let $A_n$ be the subalgebra of $A$ generated by the first $n$ minimal idempotents (so $A_n$ is just ${\mathbb C}^n$ with the $\ell^1$-norm and pointwise product).
UPDATE I originally mis-stated part of the question, as Andreas, Bill and Gideon were all quick to point out; my apologies for the confusion.
UPDATE, ENCORE My apologies for having omitted yet another condition in my haste to get the original edits done - thanks to fedja for catching this
Taking the existence of $\theta$ as read, it is straightforward to show that given $a\in A_n$ there exists a subspace $H_n\subset H$ of dimension $n+1$ and a homomorphism $\theta_n A_n \to B(H_n)$ such that
$$ c\Vert a\Vert_1 < \Vert\theta_n(a)\Vert \leq C  \Vert a\Vert_1  $$
where the constants $c$ and $C$ are strictly positive and independent of $n$ and $a$.
By a crude compactness argument, this implies the following:

There exist constants $0 < c < C$ such that, for each $n\geq 1$, we can find $m(n)$ and idempotents $E_1,\dots, E_n$ in $M_{m(n)}({\mathbb C})$, which satisfy
$$ E_jE_k=0 \quad\hbox{for $j\neq k$} $$
and
$$ c\sum_{j=1}^n |a_j| \leq \left\Vert \sum_{j=1}^n a_j E_j \right\Vert \leq C \sum_{j=1}^n |a_j| $$
for all $a_1,\dots, a_n\in {\mathbb C}$.

My question is this: does anybody know of an explicit construction of such $E_1,\dots, E_n$? I would be interested just to know of a construction which works for a sequence $n_1 < n_2< \dots$ Also, how small can we make the containing matrix algebra? (The compactness argument referred to above produces an embedding into the block-diagonal matrices with block size $n+1$ -- I haven't tried to work out just how `long' the diagonal has to be.)
These seem to me like questions that must have been looked at before, so perhaps the answer would be as simple as supplying an appropriate reference.
(The choice to work over complex scalars here is not important; a solution just for real scalars would be just as welcome.)
Remark: perhaps it might be useful to use the fairly well-known equivalence between the $\ell^1$-norm and the norm
$$ \Vert x \Vert_S := \sup_{F \subseteq {\mathbb N}} \left\Vert \sum_{i\in F} x_i \right\Vert $$

A: You can manage to get $m(n)=(n+2)2^{n}$ (this can certainly be made a bit better). By your remark, it is enough to construct projections $E_1,\dots,E_n$ in $M_{n+2}(\mathbb C)$ such that:

*

*$E_i E_j=0$ for $i \ne j$

*$\|E_i\|\leq 3$

*$\| \sum s_i E_i\| \geq |\sum s_i|$ for any complex numbers $s_1,\dots s_n$.
(Then consider $\oplus_{F \subset (1,\dots,n)} M_{|F|+2}$ inside $M_{m(n)}(\mathbb C)$).
We use the following elementary fact: there exists $\Omega$ a unit vector in the euclidean space $\mathbb C^{n+2}$ and $x_1,\dots,x_n$ and $y_1,\dots,y_n$ of norm $\sqrt 3$ in  $\mathbb C^{n+2}$ such that $\langle x_i,y_j\rangle=1$ if $i=j$ and $0$ if $i\ne j$, and such that $\langle x_i,\Omega\rangle=\langle y_i,\Omega\rangle=1$.
(if $\Omega,e_0,\dots,e_n$ is an orthonormal basis, take $x_i=\Omega+e_0+e_i$ and $y_i=\Omega-e_0+e_i$).
Then the matrices $E_i=x_i^* \otimes y_i$ (the rank one operator mapping $x$ to $\langle x_i,x\rangle y_i$ satisfy the conditions above. The only point perhaps not completely evident is the third point, but this is because $\langle \Omega,\sum_i s_i E_i \Omega \rangle = \sum_i s_i$.

A: Here is  simple construction for $m(n)=2^n$. As is indicated in the remarks above one can't get an essentially lower dimension.
The $E_i$-s will be diagonal matrices. $E_1$ will have the first half diagonal entries equal to 1 the second half 0. $E_2$ the first and third fourths 1-s the rest zeroes, ..., $E_n$ alternatively 1 and zero. (These are $(r_i+1)/2$ where $r_i$ are the Rademacher functions). The point is that for each subset $A$ of $\{1,\dots,n\}$ there is a $j$ such that $\{E_1(j,j),\dots,E_n(j,j)\}$ is exactly the indicator function of $A$. The $E_i$ are idempotents.
Using the equivalent $\ell_1$ norm $\|\cdot\|_S$ at the end of the question, it is easy to see that these satisfy the inequalities. They satisfy them with constants 1 for the $\|\cdot\|_S$ norm.
Update: Disregard this answer. It relates to a previous version of Yemon's question.


text:
Q: How do you write to a pre-existing nested dictionary within a JSON file? I'm testing storing data with JSON files using python, however I don't seem to be able to write the data within a nested dictionary. It's hard to explain so hopefully the code will help.
import json

def write():

    usernameInput = input("Enter a username: \n")
    emailInput = input("Enter an email: \n")
    passwordInput = input("Enter a password: \n")
    nameInput = input("Enter your name: \n")
    dobInput = input("Enter your DOB (DD/MM/YYYY): \n")
    pastaInput = input("Do you like pasta? Y/N: \n")

    if pastaInput == "Y":
        likesPasta = True
    elif pastaInput == "N":
        likesPasta = False
    else:
        likesPasta = None

    userkey = usernameInput.lower()
    users = {"users": {userkey: {}}} #This uses the same format of nested dict as the JSON does

    users["users"][userkey]["username"] = usernameInput #This is how I set the variables for the nested Dict
    users["users"][userkey]["email"] = emailInput
    users["users"][userkey]["password"] = passwordInput
    users["users"][userkey]["name"] = nameInput
    users["users"][userkey]["dob"] = dobInput
    users["users"][userkey]["likespasta"] = likesPasta

    json_file = open("json_path_here", "w") #I have tried open modes "a" and "w" but neither work ("a" just makes a new dict in the json and "w" overwrites everything *duh*)
    json.dump(users, json_file)
    json_file.close()

The JSON file:
{
   "users": {
      "a": {
         "username": "a",
         "email": "b",
         "password": "c",
         "name": "d",
         "dob": "e",
         "likespasta": null
      }
   }
}

I want the output JSON to look like this when I add a new person (person b)
{
   "users": {
      "a": {
         "username": "a",
         "email": "b",
         "password": "c",
         "name": "d",
         "dob": "e",
         "likespasta": null
      },
      "b":{
         "username": "d",
         "email": "ve",
         "password": "dasd",
         "name": "sad",
         "dob": "cs",
         "likespasta": true
      }
   }
}

But it ends up like this:
{
   "users": {
      "a": {
         "username": "a",
         "email": "b",
         "password": "c",
         "name": "d",
         "dob": "e",
         "likespasta": null
      }
   }
}
   "users": {
      "b": {
         "username": "b",
         "email": "ve",
         "password": "dasd",
         "name": "sad",
         "dob": "cs",
         "likespasta": true
      }
   }
}

A: I think this will work for you, I modified your code quite a bit to make it a bit more simple:
import json
import os

def pasta_parse(answer):
    valid_answers = {
        'y': True,
        'n': False
    }
    # return none if not in valid_answers
    return valid_answers.get(answer.lower()) # convert to lower to match

def get_answers():
    return [{
        'username': input('Enter a username: \n'),
        'email': input('Enter an email: \n'),
        'password': input('Enter a password: \n'),
        'name': input('Enter your name: \n'),
        'dob': input('Enter your DOB (DD/MM/YYYY): \n'),
        'pasta': pasta_parse(input('Do you like pasta? Y/N: \n')) # <-- cool
    }]

def write_json(path, data, indent=4):
    with open(path,'w') as file:
        json.dump(data, file, indent=indent)

def append_json(path, data, key=None):
    if not os.path.exists(path):
        write_json(path, data)
    else:
        with open(path) as file:
            # load a dict of th edata
            json_data = json.load(file)
            # key should be a list of objects so you can __add__ them
            if key is None:
                json_data += data
            else:
                json_data[key] += data
            write_json(path, json_data)

# declare blank users list, we can add list(dict) to this without appending
users = []

# add get_answers to users
# if you had any more code earlier using this,
# you may have to do this data structure differently
users += get_answers()

append_json('user.json', users)

This will ask you the questions each time you run the script and append/create the json file. I modified your data structure a little bit to have an array at the root of the json by default but that can be changed and you can specify a key at the root of your json to save the array to. You may have to change the code a bit if you have other data at the root of your json file.
I ran the code a few times and got this json:
[
    {
        "username": "asdf",
        "email": "asdf",
        "password": "asdf",
        "name": "asdf",
        "dob": "asdfasdfasdf",
        "pasta": false
    },
    {
        "username": "asdfasdfasdf",
        "email": "sadfasdfasdf",
        "password": "asdfsadfasdfas",
        "name": "asdf",
        "dob": "asdfasdfas",
        "pasta": true
    },
    {
        "username": "asdfasdcasder",
        "email": "gfhnfgyi",
        "password": "srrtybzdt",
        "name": "sdrtfb",
        "dob": "",
        "pasta": null
    }
]


text:
Q: Gravity Forms, How to dynamically populate a multi column List (with select as a column) I believe with this snippet, one shall be able to populate a field in wordpress gravity forms:
add_filter( "gform_field_value_products", "mu_populate_products" );
function mu_populate_products() {
    global $currUserEntry;
    if($currUserEntry){
        $e = rgar( $currUserEntry, '37' );
        alertUser(maybe_unserialize($e));
        return $e;
    }
}

I can assure you that $e contains exactly the data which has been sent after validation of the form to the database, and the 37 and products are what they should be,
I think the problem is that this products field is a list with two columns and the first column is concerted to <select> by this snippet:
add_filter( 'gform_column_input_30_37_1', 'set_column', 10, 5 );
function set_column( $input_info, $field, $column, $value, $form_id ) {
    return array( 'type' => 'select', 'choices' => 'choice 1, choice 2' );
}

any help would be appreciated

A: Well after a while here is the answer, for googlers perhaps,
function mu_populate_products() {
    global $currUserEntry;
    if($currUserEntry){
        $e = rgar( $currUserEntry, '37' );
        return maybe_unserialize($e);
    }
}

all the point is that the function must return a deserialized object, while the rgar which returns the field value from db is serialized, so using maybe_unserialize was the key.
also bear in mind that this works since Gravity Forms 1.9.10.8
for more info:
https://www.gravityhelp.com/documentation/article/gform_field_value_parameter_name/#3-list-field


text:
Q: I would like to pass the attributes values in map for Jsoup Connect.data() method The xml structure looks like the following.I would like to pass the id name="hotelId" value="00000000003054D8" and id name="offerId" value="74" to the Jsoup's Connect class data() method.
<GetBookingIdsRequest token="f6ERmpwxbZ4ysUgCHB9mlSPcd9rf5DVB39C--yLbNSdG" sid="TVd8DY5OQi2vf82h" xmlns="http://www.travelfusion.com/xml/api/simple">
        <id name="hotelId" value="00000000003054D8"/>
        <id name="offerId" value="74"/>
</GetBookingIdsRequest>

How do I pass the same?

A: Here's an example how you get the values:
Document doc = ...

Elements request = doc.select("getbookingidsrequest");

for( Element element : request )
{
    final String hotelId = element.select("id[name=hotelId]").first().attr("value");
    final String offerId = element.select("id[name=offerId]").first().attr("value");

    System.out.println(hotelId);
    System.out.println(offerId);
}

Output:
00000000003054D8
74

If you have only a single GetBookingIdsRequest-tag you can use first() method instead of the for-loop:
Document doc = ...

Element request = doc.select("getbookingidsrequest").first();

final String hotelId = request.select("id[name=hotelId]").first().attr("value");
final String offerId = request.select("id[name=offerId]").first().attr("value");

System.out.println(hotelId);
System.out.println(offerId);

A: You can pass the below as part of the data map for the Connection object.
map.put("id[0].name", "hotelId");
map.put("id[0].value", hotel_Id);
map.put("id[1].name", "offerId");
map.put("id[1].value", offer_Id);


text:
Q: ember-cli: moduleFor fails with "Attempting to register an unknown factory" error I cannot get moduleFor to work in a fresh build using ember-cli version 0.1.5.
When using the documentation's example code for moduleFor (and no other changes to the app), I get the following error after running ember test:
TypeError: Attempting to register an unknown factory: `route:index`
    at Object.Container.register (http://localhost:4200/assets/vendor.js:14473:17)
    at isolatedContainer (http://localhost:4200/assets/test-support.js:24:19)
    at Object._callbacks.setup (http://localhost:4200/assets/test-support.js:150:23)
    at Object.Test.setup (http://localhost:4200/assets/test-support.js:1063:31)
    at http://localhost:4200/assets/test-support.js:1168:10
    at process (http://localhost:4200/assets/test-support.js:887:24)
    at http://localhost:4200/assets/test-support.js:476:5

Since I haven't made any changes to the app aside from adding the sample moduleFor example at /tests/unit/index-test.js, this seems like it may be an ember-cli bug?  For reference, below is the code for the moduleFor example:
// my-app/tests/unit/index-test.js
import { test, moduleFor } from 'ember-qunit';

moduleFor('route:index', "Unit - IndexRoute", {
  setup: function () {},
  teardown: function () {}
});

test("it exists", function(){
  ok(this.subject());
});

A: It seems like the route is auto-generated when it is routed to. But when running a unit test with moduleFor() like you are doing, there won't be an IndexRoute unless you explicitly declare one. If you want an IndexRoute you can test, you'll need to manually define it:
import Ember from 'ember'

IndexRoute = Ember.Route.extend();

export default IndexRoute

If you really just want to rely on the auto-generated one, there's no reason to unit test it because there is no additional functionality to test.
I think if you turn on LOG_ACTIVE_GENERATION then you can see when things get generated.
If you do want to test the auto-generated one, do it in the context of an acceptance test, when you can use the router to route there.
My guess is it gets generated here.


text:
Q: Cannot fetch image from the frontend when added proxy in package.json. Failed to load resource: the server responded with a status of 404 (Not Found) Initially, without adding a proxy in the frontend in the package.json, the app works completely fine.
But when I add the proxy,
  "proxy": "http://127.0.0.1:5000",

the app cannot fetch images from the public folder.
And show this error all over for all images.
I am using node js for the backend.

I have my image here in this directory.

Why is it?
Is it anything to do with the image path?


text:
Q: How can I use GitHub as a paclet server? I want to use GitHub as a paclet server, but this fails:
PacletInstall[
 "ServiceConnection_StackExchange",
 "Site" -> "https:/github.com/paclets/Repository"
 ]

PacletSiteUpdate::err: An error occurred attempting to update paclet information from site https:/github.com/b3m2a1/PacletServer. Does not appear to be a valid paclet site

PacletInstall::notavail: No paclet named ServiceConnection_StackExchange is available for download from any currently enabled paclet sites.

$Failed

Is there a work around?

See also: How to distribute Mathematica packages as paclets? and this answer

A: First things first we set up the paclet server in the normal way as described here or here.
Then all we need to do is pass the "raw.githubusercontent" version of that so that the resources themselves get downloaded instead of the HTML pages:
PacletInstall[
 "ServiceConnection_StackExchange",
 "Site" ->
  "http://raw.githubusercontent.com/paclets/Repository/master"
 ]

Paclet[
"Name" -> "ServiceConnection_StackExchange", "Version" -> "1.0.0",
 "Description" -> "A service connection to the Stack Exchange API. \
Supports the majority of the functions defined in the API",
 "Extensions" -> {{
   "Kernel", "Root" -> ".",
    "Context" -> "ServiceConnection_StackExchange`"}, {
   "FrontEnd", "Prepend" -> True}},
 "Location" -> "~/Library/Mathematica/Paclets/Repository/\
ServiceConnection_StackExchange-1.0.0"]

Note:
As Szabolcs points out, you must use "http://raw.githubusercontent.com". The PacletManger refuses to use the "https://" form.


text:
Q: ArcGIS -- Have a need for ArcGIS to correct addresses, via API, at speed. Possible? I have rough data coming in and I have a need to run it through address-correction in order to use it for other things.  That is, I have --
1313 Mucckingbird Ln, Bowie, MD 20305
. . . and I need a tool that returns --
1313 Mockingbird Ln, Bowie, MD 20305
I need to be able to do this programmatically for hundreds of thousands of addresses.  I keep raising this issue to management, and they keep sending me to ArcGIS installed in affiliated organizations.  I need to run this machine-to-machine and I need to be able to do it in bulk.
Here's the problem -- I can't find anything in ArcGIS that provides this service via an API.  I need a fuzzy match, not more details on perfectly-entered address.
The question -- does ArcGIS provide this capability, and if it does, can you tell me what feature or what term I should search for in the documentation?
I get the feeling that no matter how many times I express what our need is, my organization doesn't understand what I'm asking for.


text:
Q: Get index by value I want something like this:
var onlineMobilesAnon=[];
onlineMobilesAnon["abc1"]="test";
console.log(onlineMobilesAnon.indexOf("test"));  //Should return "abc1"

How can I achive this ?

A: This isn't exactly what you'd want, since it goes off of keys (Javascript Objects instead of Arrays, though an array is just a special javascript object anyway) and not index, but you could grab all the keys and check the value associated for the key and return that key with the following:
var onlineMobilesAnon = {}
onlineMobilesAnon["abc1"]="test"

var keys = Object.keys(onlineMobilesAnon);

for(var i = 0; i < keys; i++){
  if(onlineMobilesAnon[keys[i]] == "test"){
    console.log(keys[i])
  }
}


text:
Q: How can I stringify a BSON object inside of a MongoDB map function? I have documents with field xyz containing
{ term: "puppies", page: { skip: 1, per_page: 20 } } // not useful as a composite key...
{ page: { skip: 1, per_page: 20 }, term: "puppies" } // different order, same contents

For the sake of determining the "top" values in xyz, I want to map them all to something like
emit('term="puppies",page={ skip: 1, per_page: 20 }', 1); // composite key

but I can't get the embedded objects into a meaningful strings:
emit('term="puppies",page=[object bson_object]', 1); // not useful

Any suggestions for a function to use instead of toString()?
# return the top <num> values of <field> based on a query <selector>
#
# example: top(10, :xyz, {}, {})
def top(num, field, selector, opts = {})
  m = ::BSON::Code.new <<-EOS
    function() {

      var keys = [];

      for (var key in this.#{field}) {
        keys.push(key);
      }

      keys.sort ();

      var sortedKeyValuePairs = [];

      for (i in keys) {
        var key = keys[i];
        var value = this.#{field}[key];

        if (value.constructor.name == 'String') {
          var stringifiedValue = value;
        } else if (value.constructor.name == 'bson_object') {
          // this just says "[object bson_object]" which is not useful
          var stringifiedValue = value.toString();
        } else {
          var stringifiedValue = value.toString();
        }

        sortedKeyValuePairs.push([key, stringifiedValue].join('='));
      }

      // hopefully we'll end up with something like
      // emit("term=puppies,page={skip:1, per_page:20}")
      // instead of
      // emit("term=puppies,page=[object bson_object]")
      emit(sortedKeyValuePairs.join(','), 1);
    }
  EOS
  r = ::BSON::Code.new <<-EOS
    function(k, vals) {
      var sum=0;
      for (var i in vals) sum += vals[i];
      return sum;
    }
  EOS
  docs = []
  collection.map_reduce(m, r, opts.merge(:query => selector)).find({}, :limit => num, :sort => [['value', ::Mongo::DESCENDING]]).each do |doc|
    docs.push doc
  end
  docs
end

A: Given that MongoDB uses SpiderMonkey as its internal JS engine, can't you use JSON.stringify (will work even if/when MongoDB switches to V8) or SpiderMonkey's non-standard toSource method?
(sorry, can't try it ATM to confirm it'd work)

A: toSource method will do the work, but it adds also brackets.
for a clean document use:
value.toSource().substring(1, value.toSource().length - 1)


text:
Q: Laravel 5.2 asset implementation When I try to open the assets,I added on my page on the source (css, js),I get the log error at the end of the page.
Here's what I've tried so far:
homepage.blade.php
<link href="{{{asset('/css/bootstrap.css') }}}" rel="stylesheet">

Composer.json
"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*",
        "laravelcollective/html": "^5.2"
    }

composer update from console.
added to app.php->providers
Collective\Html\HtmlServiceProvider::class

added to app.php->aliases
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class

I get this in laravel.log:
local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Illuminate\Html\HtmlServiceProvider' not found' in /var/www/html/myproject/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php:146

Thanks in advance.

A: change this :
<link href="{{{asset('/css/bootstrap.css') }}}" rel="stylesheet">

into this :
<link href="{{URL::asset('/css/bootstrap.css') }}" rel="stylesheet">

A: Thanks for your answers.
The problem was about setting the virtual host settings wrong. So i wasn't able to reach the true path.
I re-set the vhost configuration and it works now.
<VirtualHost *:80>
        ServerName mysite.com
        ServerAdmin mysite@mysite.com
        DocumentRoot /var/www/html/mysite/public

        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory "/var/www/html/mysite">
                AllowOverride All
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Reference: http://vaguelyuseful.info/2016/02/02/installing-laravel-5-2-on-ubuntu-15-10-and-apache2/
Thank you all again.


text:
Q: C++ default constructor does not initialize pointer to nullptr? I wonder if I have a A* member in my class, shouldn't it we set to nullptr automatically if I have a constructor of my class in this form:
class MyCLass
{
    A* m_pointer;

public:
    MyCLass()
    {
    }
};

Does it matter if I do MyCLass* o = new MyCLass; or I do  MyCLass* o = new MyCLass(); in C++11?

A: The default constructor, if compiler-generated or defaulted, will default-initialize all members. Any user-defined constructor will similarly default-initialize all members that don't have an explicit initializer in the initializer-list.
To default-initialize means "call the default constructor for classes, leave everything else uninitialized".

A: Pointers are "POD types"...a.k.a. "Plain Old Data".  The rules for when and where they are default-initialized are summarized here:
Default initialization of POD types in C++
So no.  It doesn't matter what your constructor for a class is, if it's a raw pointer as a member of the class.  You aren't actually instantiating the class.  So members like Foo * or std::vector<Foo> * or anything ending in * will not be initialized to nullptr.
The smart pointer classes are not POD.  So if you use a unique_ptr<Foo> or a shared_ptr<Foo> that is creating instances of classes, that do have a constructor that makes them effectively null if you do not initialize them.

Does it matter if I do MyCLass* o = new MyCLass; or I do  MyCLass* o = new MyCLass(); in C++11?

One question per question, please.
Do the parentheses after the type name make a difference with new?


text:
Q: Does GNU find protect against finding a file multiple times if files are renamed with xargs or -exec? I used the following command to add a prefix to all filenames in the current directory:
find . -maxdepth 1 -type f | xargs -I {} basename {} | xargs -I {} mv {} prefix-{}

My question is: is this procedure safe with GNU find? Or could the find process, which may still be running after the first files are renamed, find the renamed files again, such that they get the prefix multiple times?
I used the same command to rename the same files with busybox and found that some of them got the prefix multiple times. This is perfectly understandable, but since I never had the problem with GNU find (GNU findutils) 4.7.0, I'm wondering if the GNU variant has some protection against this outcome.
I looked at the documentation and tried to find the answer with Google, but I could not find anything relevant.

A: Following experiment proves it can happen to GNU find :
#!/usr/bin/env bash

dir=/tmp/find

rm -rf $dir; mkdir $dir; cd $dir
for i in {1..120000}; do touch $i; done # Create 120000 empty files.
find . -maxdepth 1 -type f -printf "%P\n" | xargs -I {} mv {} prefix-{}
find . -name "prefix-prefix*" | wc # gives -> 14546   14546  319622

find --version # gives -> find (GNU findutils) 4.7.0
uname -a       # gives -> Linux ubuntu 5.15.0-52-generic #58~20.04.1-Ubuntu SMP Thu Oct 13 13:09:46 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

See wc result.


text:
Q: Navbar dropdown width resize I have a navigation bar that is fluid on both desktop and mobile devices. However, the drop-down items widths don't resize based on the parent's width. I would like to hover over a drop-down item and it has the same width as the list item I hovered over. At the moment it has a fixed width but I can't seem to get it working by trying other options. I also cannot get the entire navigation bar to center, as at the moment it is stuck to the left. Thanks for the help!
Here's a codepen of the code: https://codepen.io/Macast/pen/rYQPNe
HTML:

        Menu
        <input type="checkbox" id="drop" />

Home

                Short +
                Short
                <input type="checkbox" id="drop-1" />

History

Our Services

Our Aim

                Dropdown Even Longer +
                Dropdown Even Longer
                <input type="checkbox" id="drop-2" />

Option

Option

Option

                        More Options +
                        More Options
                        <input type="checkbox" id="drop-3" />

Option

Option

Option

Option

Option

Option

Option

CSS:
.toggle,
[id^=drop] {
    display: none;
}
/* Giving a background-color to the nav container. */

nav {
    margin: 0;
    padding: 0;
    background-color: #254441;
}
#logo {
    display: block;
    text-align: center;
    /*padding: 0 30px;*/
    /*float: left;*/
    /*font-size: 20px;*/
    /*line-height: 60px; */
}
#logo img {
    width: 30%;
}
/* Since we'll have the "ul li" "float:left"
 * we need to add a clear after the container. */

nav:after {
    content: "";
    display: table;
    clear: both;
}
/* Removing padding, margin and "list-style" from the "ul",
 * and adding "position:reltive" */

nav ul {
    /*float: right;*/
    padding: 0;
    margin: 0;
    list-style: none;
    position: relative;
}
/* Positioning the navigation items inline */

nav ul li {
    margin: 0px;
    display: inline-block;
    float: left;
    background-color: #254441;
    text-align: center;
}
/* Styling the links */

nav a {
    display: block;
    padding: 14px 20px;
    color: #FFF;
    font-size: 17px;
    text-decoration: none;
    text-align: center;
}
nav ul li ul li:hover {
    background: #000000;
}
/* Background color change on Hover */

nav a:hover {
    background-color: #000000;
}
/* Hide Dropdowns by Default
 * and giving it a position of absolute */

nav ul ul {
    display: none;
    position: absolute;
    /* has to be the same number as the "line-height" of "nav a" */
    top: 60px;
}
/* Display Dropdowns on Hover */

nav ul li:hover > ul {
    display: inherit;
}
/* Fisrt Tier Dropdown */

nav ul ul li {
    width: 170px;
    float: none;
    display: list-item;
    position: relative;
    text-align: center;
}
/* Second, Third and more Tiers
 * We move the 2nd and 3rd etc tier dropdowns to the left
 * by the amount of the width of the first tier.
*/

nav ul ul ul li {
    position: relative;
    top: -60px;
    /* has to be the same number as the "width" of "nav ul ul li" */

    left: 170px;
}
/* Change ' +' in order to change the Dropdown symbol */

li > a:after {
    content: ' +';
}
li > a:only-child:after {
    content: '';
}
/* Media Queries
--------------------------------------------- */

@media all and (max-width: 768px) {
    #logo {
        display: block;
        padding: 0;
        width: 100%;
        text-align: center;
        float: none;
    }
    #logo img {
        width: 100%;
        box-sizing: border-box;
        padding: 20px;
    }
    nav {
        margin: 0;
    }
    /* Hide the navigation menu by default */
    /* Also hide the  */

    .toggle + a,
    .menu {
        display: none;
    }
    /* Stylinf the toggle lable */

    .toggle {
        display: block;
        background-color: #254441;
        padding: 14px 20px;
        color: #FFF;
        font-size: 17px;
        text-decoration: none;
        border: none;
        text-align: center;
    }
    .toggle:hover {
        background-color: #000000;
    }
    /* Display Dropdown when clicked on Parent Lable */

    [id^=drop]:checked + ul {
        display: block;
    }
    /* Change menu item's width to 100% */

    nav ul li {
        display: block;
        width: 100%;
    }
    nav ul ul .toggle,
    nav ul ul a {
        padding: 0 40px;
    }
    nav ul ul ul a {
        padding: 0 80px;
    }
    nav a:hover,
    nav ul ul ul a {
        background-color: #000000;
    }
    nav ul li ul li .toggle,
    nav ul ul a,
    nav ul ul ul a {
        padding: 14px 20px;
        color: #FFF;
        font-size: 17px;
    }
    nav ul li ul li .toggle,
    nav ul ul a {
        background-color: #212121;
    }
    /* Hide Dropdowns by Default */

    nav ul ul {
        float: none;
        position: static;
        color: #ffffff;
        /* has to be the same number as the "line-height" of "nav a" */
    }
    /* Hide menus on hover */

    nav ul ul li:hover > ul,
    nav ul li:hover > ul {
        display: none;
    }
    /* Fisrt Tier Dropdown */

    nav ul ul li {
        display: block;
        width: 100%;
    }
    nav ul ul ul li {
        position: static;
        /* has to be the same number as the "width" of "nav ul ul li" */
    }
}
@media all and (max-width: 330px) {
    nav ul li {
        display: block;
        width: 94%;
    }
}

A: To adjust the dropdown menu size to the same size as the containing list-item, declare a left and right property value of 0 on the dropdown element in question (nav ul ul), then remove the explicitly declared width on the nested list items of the dropdown menu (nav ul ul li).
Example:
nav ul ul {
    display: none;
    position: absolute;
    top: 60px;
    /* additional property values declared */
    left: 0;
    right: 0;
}

This works because the dropdown menus are already positioned absolute and the containing parent element list item (nav ul li) is already positioned relative.
You can position absolute elements relative to their parents if their parents are relative.
So all we are doing here is defining the extent of the dropdown menu width to "stretch" from "left to right" of the parent's width.
Code Snippet Demonstration:

.toggle,
[id^=drop] {
    display: none;
}
/* Giving a background-color to the nav container. */

nav {
    margin: 0;
    padding: 0;
    background-color: #254441;
}
#logo {
    display: block;
    text-align: center;
    /*padding: 0 30px;*/
    /*float: left;*/
    /*font-size: 20px;*/
    /*line-height: 60px; */
}
#logo img {
    width: 30%;
}
/* Since we'll have the "ul li" "float:left"
 * we need to add a clear after the container. */

nav:after {
    content: "";
    display: table;
    clear: both;
}
/* Removing padding, margin and "list-style" from the "ul",
 * and adding "position:reltive" */

nav ul {
    text-align: center;
    padding: 0;
    margin: 0;
    list-style: none;
    position: relative;
}
/* Positioning the navigation items inline */

nav ul li {
    margin: 0px;
    display: inline-block;
    background-color: #254441;
    text-align: center;
    position: relative;
}
/* Styling the links */

nav a {
    display: block;
    padding: 14px 20px;
    color: #FFF;
    font-size: 17px;
    text-decoration: none;
    text-align: center;
}
nav ul li ul li:hover {
    background: #000000;
}
/* Background color change on Hover */

nav a:hover {
    background-color: #000000;
}
/* Hide Dropdowns by Default
 * and giving it a position of absolute */

nav ul ul {
    display: none;
    position: absolute;
    /* has to be the same number as the "line-height" of "nav a" */
    top: 60px;
    left: 0;
    right: 0;
}
/* Display Dropdowns on Hover */

nav ul li:hover > ul {
    display: inherit;
}
/* Fisrt Tier Dropdown */

nav ul ul li {
    /*width: 170px;*/
    float: none;
    display: list-item;
    position: relative;
    text-align: center;
}
/* Second, Third and more Tiers
 * We move the 2nd and 3rd etc tier dropdowns to the left
 * by the amount of the width of the first tier.
*/

nav ul ul ul li {
    position: relative;
    top: -60px;
    /* has to be the same number as the "width" of "nav ul ul li" */

    left: 170px;
}
/* Change ' +' in order to change the Dropdown symbol */

li > a:after {
    content: ' +';
}
li > a:only-child:after {
    content: '';
}
/* Media Queries
--------------------------------------------- */

@media all and (max-width: 768px) {
    #logo {
        display: block;
        padding: 0;
        width: 100%;
        text-align: center;
        float: none;
    }
    #logo img {
        width: 100%;
        box-sizing: border-box;
        padding: 20px;
    }
    nav {
        margin: 0;
    }
    /* Hide the navigation menu by default */
    /* Also hide the  */

    .toggle + a,
    .menu {
        display: none;
    }
    /* Stylinf the toggle lable */

    .toggle {
        display: block;
        background-color: #254441;
        padding: 14px 20px;
        color: #FFF;
        font-size: 17px;
        text-decoration: none;
        border: none;
        text-align: center;
    }
    .toggle:hover {
        background-color: #000000;
    }
    /* Display Dropdown when clicked on Parent Lable */

    [id^=drop]:checked + ul {
        display: block;
    }
    /* Change menu item's width to 100% */

    nav ul li {
        display: block;
        width: 100%;
    }
    nav ul ul .toggle,
    nav ul ul a {
        padding: 0 40px;
    }
    nav ul ul ul a {
        padding: 0 80px;
    }
    nav a:hover,
    nav ul ul ul a {
        background-color: #000000;
    }
    nav ul li ul li .toggle,
    nav ul ul a,
    nav ul ul ul a {
        padding: 14px 20px;
        color: #FFF;
        font-size: 17px;
    }
    nav ul li ul li .toggle,
    nav ul ul a {
        background-color: #212121;
    }
    /* Hide Dropdowns by Default */

    nav ul ul {
        float: none;
        position: static;
        color: #ffffff;
        /* has to be the same number as the "line-height" of "nav a" */
    }
    /* Hide menus on hover */

    nav ul ul li:hover > ul,
    nav ul li:hover > ul {
        display: none;
    }
    /* Fisrt Tier Dropdown */

    nav ul ul li {
        display: block;
        width: 100%;
    }
    nav ul ul ul li {
        position: static;
        /* has to be the same number as the "width" of "nav ul ul li" */
    }
}
@media all and (max-width: 330px) {
    nav ul li {
        display: block;
        width: 94%;
    }
}

            Menu
            <input type="checkbox" id="drop" />

Home

                    Short +
                    Short
                    <input type="checkbox" id="drop-1" />

History

Our Services

Our Aim

                    Dropdown Even Longer +
                    Dropdown Even Longer
                    <input type="checkbox" id="drop-2" />

Option

Option

Option

                            More Options +
                            More Options
                            <input type="checkbox" id="drop-3" />

Option

Option

Option

Option

Option

Option

Option

In Addition:
You can horizontally center the navigation menu by removing the float rule declared on nested list-items (nav ul li), as this will negate any attempt to align content (unless you use flex-box), then declare text-align: center on the containing unordered list (.menu), as demonstrated below:
nav ul {
    text-align: center;
    padding: 0;
    margin: 0;
    list-style: none;
    position: relative;
}


text:
Q: Prevent multiple form submission from same user at the same time with different devices I have website login system and after logging in, users can withdraw amount that is stored in database, the problem is when someone login using multiple devices and submit withdraw form at the same time he/she will recieve the amount multiple times. How to prevent users submitting at the same time ?

A: Make a field in the users table LOCKED with default value of zero and when its value is 1 disallow the transaction and every time a transaction takes place toggle it to 1 and back to zero when finished.

A: In order to answer your questions, I'll assume that:
1. You are using mysql database.
2. A user is allowed ONLY one withdrawal.
In your database, create a table named withdrawal.
Then, add fields like:
id INT PRIMARY KEY
user_id INT UNIQUE
withdraw_amount DECIMAL(10,2)
In this case, the user can only submit ONE record to withdrawal table since the user_id field is UNIQUE.
But, if my assumptions don't match with exactly what you require, then provide more information about what you need.


text:
Q: Normal modes in physics - solution of set of 2nd order linear differential equations In physics we study normal modes for vibrating system. Mathematically speaking we have a set of linear differential equations. For example we have something like this:
$$
\begin{align*}
m \frac{dx_1}{dt^2} &= k(x_2-x_1) \\
M \frac{dx_2}{dt^2} &= k(x_3-x_2) - k(x_2-x_1) \\
m \frac{dx_3}{dt^2} &= -k(x_3-x_2)
\end{align*}
$$
We seek solutions for $x_i(t)$. A general solution is to assume to look for these functions to be sines, cosines or exponents for all $x_i(t)$ having the same frequency $\omega$. For above example our solution would be something like:
$$
\begin{align*}
x_1 (t) &= A e^{\omega t + \varphi} \\
x_2 (t) &= B e^{\omega t + \varphi} \\
x_3 (t) &= C e^{\omega t + \varphi}
\end{align*}
$$
I could not find a clear explanation why we assume that we seek solution with the same $\omega$ (normal modes), and later why the general solution is the superposition of all such solutions (we obviously find . Many thanks for comments and explanation.

A: The system modeled as
$$
\begin{align*}
m \frac{d^2x_1}{dt^2} &= k(x_2-x_1) \\
M \frac{d^2x_2}{dt^2} &= k(x_3-x_2) - k(x_2-x_1) \\
m \frac{d^2x_3}{dt^2} &= -k(x_3-x_2)
\end{align*}
$$
can be represented shortly as
$$
\ddot x = A x
$$
Normally in this kind of problems $A$ can be represented as $T^{-1}\Lambda T$ with $T^{-1}T = I$ where $\Lambda$ is a diagonal matrix with the eigenvalues from $A$. So we can follow with
$$
\ddot y = \Lambda y,\ \ \ y = T x
$$
This system doesn't contain attenuation terms so it represents an oscillatory system. This system will remain forever oscillating along their natural frequencies  associated to the eigenvalues $\lambda_k$. The most plausible system with the properties you cited is an actuated dissipative system with the structure
$$
\ddot x + 2B \dot x + A x = u
$$
with $u = f(\omega t)$ in which $f$ represents a sinusoidal adequate function. The solution for this system can be written as
$$
y_k(t) = e^{-b_k t}\left(c_k e^{-\sqrt{b_k^2-\lambda_k}t}+\bar c_k e^{\sqrt{b_x^2-\lambda_k}t}\right)+ y_p(\omega t)
$$
For passive systems, the homogeneous component goes asymptotically to zero remaining the particular $y_p(\omega t)$


text:
Q: SoapUI: Connection has been shutdown: javax.net.SSLHandshakeException Currently using the open source version of SoapUI 5.5.0. I am trying to run a REST Request. In Postman I am able to bypass this issue by turning off SSL verification but that does not seem possible in SoapUI.
When I try to run a request I am getting the following error:

javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

I have tried adding:

*

*set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.https.protocols="SSLv3,TLSv1.2" to SoapUI.bat

*-Dsoapui.https.protocols=TLSv1.2,SSLv3 to SoapUI-X.X.X.vmoptions
Neither of these solutions work. I am not sure that the problem exists on the SoapUI side anymore.

A: Java comes with its own CA TrustStore. SoapUI, at least on Windows, comes with bundled Java, usually very outdated version of Java. we know that SoapUI is intelligent enough, that if it does not find the bundled Java it will look elsewhere ($PATH, $JAVA_HOME). So we go to your SoapUI install directory and renamed jre to jre.ignore.


text:
Q: Is it bad practice for a class to be aware of its location in an array? Is it bad practice for a class to store its location within an array?
Similarly, is it bad practice for the collection to maintain each object's internal location?
If these are bad practices, what is a better way to have quick access to an object's location in an array or to maintain that position?

A:
Is it bad practice for a class to store its location within an array?

It depends, but often, yes.  The problem is that you're breaking the single responsibility principle - the class not only has to maintain its state, but also its "position" within some other container.
This can lead to brittle designs, since there isn't a clear way of handling scenarios such as the class being in more than one container.  Also, moving an item becomes maintaining more code (changing the collection + the class internal representation), etc.

A: Generally, yes, it is a bad practice, for two reasons:

*

*Things that could be calculated should not be stored (e.g. storing an age and a DOB is a bad practice), and

*An object can belong to multiple collections at once, so it may not be clear which collection it should track.

There are two ways to address this problem:

*

*Avoid it in the first place - rather than passing around objects, pass around their indexes in the collection. When you need to access an object, apply the index to the collection. This way the index remains your "primary reference" to the object, so finding it out never becomes an issue, or

*Calculate the positions as needed - Keep a normal collection where objects do not keep an index. When you need to pair up objects and indexes, run a LINQ query that pairs them up temporarily; discard the results as soon as they are no longer needed.

Here is an example of a LINQ query to pair up objects and their indexes:
var objIndexPair = collection.
    Select((v, i) => new {
        Index = i
    ,   Object = v
    }).ToList();

Note that this approach does not make the class aware of its position in the collection. Rather, an anonymous class pairs up the object with its position in the collection, solving the problem of an object belonging to multiple collections.

A: If an object your class is stored within another class - in this case an array - then it is the responsibility of that class to tell you where the object is stored within itself. If your object is guaranteed to be stored only withing ONE other class, then you might have a reference on the containing class in your contained class, but that is about it.
If you use collections, then this is precisely what you can do:
private class MyData
{
    // ...
}

private List<MyData> myDataList = new List<MyData>();

public void SomeMethod()
{
    MyData myData = ...;
    int position = myDataList.IndexOf(myData);
}

You should really never use arrays unless you absolutely have to. And if you can, convert your arrays which you get from some archaic legacy API to collections (i.e. lists), and just convert those back to arrays once you are done with them.


text:
Q: Requests: Module works locally but failed on pythonanywhere I am trying to make a twitter bot that uses requests library to get data from nytimes api.
There is a line in the code
resp = requests.get(API_ENDPOINT, my_params)

Now this works very well when I run it locally. So I uploaded it to pythonanywhere. The moment I tried to run it I got this error:

resp = requests.get(API_ENDPOINT, my_params)
  TypeError: get() takes exactly 1 argument (2 given)

What is happening? I have started using requests as well as pythonanywhere recently. So I have literally no idea where to start debugging.

A: You have different requests versions installed on PythonAnywhere and locally.

From what I see requests version installed on PythonAnywhere is 2.4.0. At that point, you had to specify params keyword argument explicitly:

requests.get(url, **kwargs)

And you have to write:
resp = requests.get(API_ENDPOINT, params=my_params)

In the most recent version (2.10.0 at the moment), you can have params specified as a positional argument:

requests.get(url, params=None, **kwargs)

resp = requests.get(API_ENDPOINT, my_params)

A: You can do it like this:
API_ENDPOINT = 'http://your_endpoint_url.com'

my_params = {'key1': 'value1', 'key2': 'value2'}

r = requests.get(API_ENDPOINT, params=my_params) # notice params is named named


text:
Q: prove that $\sum_{n=0}^{\infty} {\frac{n^2 2^n}{n^2 + 1}x^n} $ does not converge uniformly in its' convergence radius In calculus:

Given $\displaystyle \sum_{n=0}^{\infty} {\frac{n^2 2^n}{n^2 + 1}x^n} $, prove that it converges for $-\frac{1}{2} < x < \frac{1}{2} $, and that it does not converge uniformly in the area of convergence.

So I said:

$R$ = The radius of convergence $\displaystyle= \lim_{n \to \infty} \left|\frac{C_n}{C_{n+1}} \right| = \frac{1}{2}$ so the series converges $\forall x$ : $-\frac{1}{2} < x < \frac{1}{2}$.

But how do I exactly prove that it does not converge uniformly there? I read in a paper of University of Kansas that states: "Theorem: A power series converges uniformly to its limit in the interval
of convergence." and they proved it.
I'll be happy to get a direction.

A: Let's prove a more general statement: if the coefficients of power series $\sum a_n x^n$ are such that the limit
$$\lim_{n\to\infty} \frac{a_n}{R^n}  $$
is finite and nonzero, then

*

*the interval of convergence is $(-R,R)$

*the series does not converge uniformly on $(-R,R)$

The first part is immediate from ratio test and the fact that $a_nx^n\not\to 0$ when $|x|\ge R$. For the second part, use the fact that for every $n$
$$\sup_{|x|< R} |a_n x^n| = \sup_{|x|\le  R} |a_n x^n| = |a_n| R^n$$
which by our assumption does not approach zero. Therefore, the uniform convergence fails: even individual terms of the series are not uniformly small, let alone the remainder.

A: According to Hagen von Eitzen theorem, you know that it will uniformly (and even absolutly) converge for intervals included in ]-1/2;1/2[. So the problem must be there.
The definition of uniform convergence is :
$ \forall \epsilon>0,\exists N_ \varepsilon \in N,\forall n \in N,\quad [ n \ge N_ \varepsilon \Rightarrow \forall x \in A,d(f_n(x),f(x)) \le \varepsilon] $
So you just have to prove that there is an $\varepsilon$ (1/3 for instance or any other) where for any $N_ \varepsilon$ there will always be an $x$ (look one close from 1/2) where $d(f_n(x),f(x)) \ge \varepsilon $ for an $n \ge N_ \varepsilon$


text:
Q: Interface Implementation (Interface Segregation Principle) I've a situation where I need to call a third party service to fetch some information. Those service could be different for different clients. I've a authenticate function in my Interface as follows.
interface IServiceProvider {

bool Authenticate(string username, string password);
}

class ABCServiceProvider : IserviceProvider
{
 bool Authenticate(string username, string password) { // implementation}
}

class EFGServiceProvider : IserviceProvider
{
 bool Authenticate(string username, string password) { // implementation}
}

and so on... now I've came across a service provider (let's say XYZServiceProvider) that needs some additional information (agentid) for authentication. something like this...
class XYZServiceProvider
{
 bool Authenticate(string username, string password, int agentid) { // implementation}
}

Now if I provide another function for Authenticate in my interface with 3 parameters, and throw not implemented exception in all the classes except for XYZServiceProvider, wouldn't it violate Interface segregation principle? I've similar situation in some of my other part of the code aswell. Can anyone please tell me whats the best way to implement this type of scenrio? I would be really very thankful.

A: The best way to solve this would probably be to require agentId in the interface, and to simply ignore it in the cases of ABC and DEF where they don't need it. That way, the consuming class still wouldn't know the difference.
Actually it's the Liskov Substitution Principle that is most important if the ABC, DEF and XYZ providers are to be used interchangeably; "Given a class A that is depended upon by class X, X should be able to use a class B derived from A without knowing the difference".
The Interface Segregation Principle basically says that an interface should not contain members that any of its consumers do not need, because if the definition of those members were to change, classes that don't even use that method would have to be recompiled because the interface they depended on has changed. While this is relevant (you do have to recompile all consumers of IServiceProvider if you add an overload), you will have to do that anyway if you change Authenticate()'s signature, and of more pressing concern from a maintenance standpoint is that if you added an overload of Authenticate(), your consumers now have to know which overload they need to use. That requires your consuming classes to know the difference between implementations of a common interface, violating LSP. It's never a problem providing more information than a particular provider needs, but there would be a problem using XYZ from a usage that only provides two inputs. To avoid those problems, you would always use the three-parameter overload, so why have the two-parameter one at all?
Now, if current usages of IServiceProvider are in areas that don't have and don't care about agentId, and therefore it would be difficult to begin providing it, then I would recommend an Adapter that the concrete XYZ provider plugs into, that implements your current IServiceProvider, and makes the new provider work like the old ones by providing the agentId through some other means:
public class XYZAdapter: IServiceProvider
{
   private readonly XYZServiceProvider xyzProvider;
   public XYZAdapter(XYZServiceProvider provider)
   {
      xyzProvider = provider;
   }

   public void Authenticate(string username, string password)
   {
      xyzProvider.Authenticate(username, password, GetAgentId());
   }

   public int GetAgentId()
   {
      //Retrieve the proper agent Id. It can be provided from the class creator,
      //retrieved from a known constant data source, or pulled from some factory
      //method provided from this class's creator. Any way you slice it, consumers
      //of this class cannot know that this information is needed.
   }
}

If this is feasible, it meets both LSP and ISP; the interface doesn't have to change to support LSP, therefore preventing the scenario (recompiling and redistributing dependencies) that ISP generally tries to avoid. However it increases class count, and forces new functionality in the Adapter to correctly get the needed agentId without its dependent having to provide anything it wouldn't know about through the IServiceProvider interface.


text:
Q: Thermal equilibrium in general relativity The Newtonian condition for thermal equilibrium for a static system is $T = \mathrm{const}$.
In this homework I'm asked to show that it's curved space generalization is $T(-g_{00})^{\frac{1}{2}} = \mathrm{const}$, where $g_{\mu \nu}$ is the metric (assumed stationary). But I have no idea how to start.

A: The clearest and most general derivation of this result is given in MTW's Gravitatiom p. 567-568 using the laws of thermodynamics in GR.
A simplified argument is in the "Problem book in relativity and gravitation" by Lightman et al. as (solved) exercise 14.2
The physical argument goes like this: imangine a black body higher up in a static gravitational field connected with a optical fiber to a lower black body. It emits a certain number of (thermal) fotons in a certain time with a certain frequency. They descend to the lower black body and arrive with a higher frequency (gravitational blueshift) with a different arrival time. The lower black body also emits a certain number of fotons with this higher frequency and if you calculate these quantities with GR and Planck's law you can see that a higher temperature is necessary in the lower black body (to equate the number of incoming/outgoing fotons) where the ratio of the temperatures is the same as that of the frequencies (look at the exponent in the denominator of Plank's law).
anyway, in my opinion this homework seems to me rather difficult if you have not been  given the appropriate background during the course (thermodynamics in GR).

A: Well T is an average energy and in general relativity, there is no guarantee of energy conservation if the metric isn't stationary, so I guess that may be the problem? You could have a system at equilibrium but the evolution of the metric could change the energy.

A: I don't know exactly where to start either but one could think of the black body radiation coming from a source far away that was emitted by a source at temperature $T_1$ where $g_{00}$ had some value say $g_{00}^1$.
Now,if we make use of the fact that $g_{00}$ influences the photon frequency via gravitational Doppler effect, then imagining balance of energy fluxes with another body at temperature $T_2$ and $g_{00}^2$ probably leads to the relation you have to find.
Sorry it's a bit hand waving for now...


text:
Q: Can't find five lowest values in an array...max works while min array is not assigned values I'm very close to completing this, all I need is help on finding the five lowest values from a text file by using arrays. I figured out how to find the five highest values, but my min array to find the lowest values always outputs five 0's.
Output: //obviously dependent on individual text file
Total amount of numbers in text file is 10
Sum is: 1832
1775 14 9 9 7 //max
0 0 0 0 0 //min
Any help is much appreciated!
import java.util.Scanner;
import java.io.*;

public class HW3
{
   public static void main(String[] args) throws IOException
   {
  File f = new File("integers.txt");
  Scanner fr = new Scanner(f);

    int sum = 0;
    int count = 0;
    int[] max = new int[5];
    int[] min = new int[5];
    int temp;

  while(fr.hasNextInt())
  {
        count++;
        fr.nextInt();
  }

    Scanner fr2 = new Scanner(new File("integers.txt"));
    int numbers[] = new int[count];

    for(int i=0;i<count;i++)
  {
    numbers[i]=fr2.nextInt(); //fills array with the integers
  }

    for(int j:numbers)//get sum
    {
        sum+=j;
    }

    for (int j=0; j < 5; j++) //finds five highest
    {
        for (int i=0; i < numbers.length; i++)
            {
                if (numbers[i] > max[j])
                {
                    temp = numbers[i];
                    numbers[i] = max[j];
                    max[j] = temp;
                }
            }
    }

    for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
    {
        for (int i=0; i < numbers.length; i++)
            {
                if (numbers[i] < min[j])
                {
                    temp = numbers[i];
                    numbers[i] = min[j];
                    min[j] = temp;
                }
            }
    }

    System.out.println("Total amount of numbers in text file is " + count);
    System.out.println("Sum is: " + sum);
    System.out.println(max[0] + " " + max[1] + " " + max[2] + " " + max[3] + " " + max[4]);
    System.out.println(min[0] + " " + min[1] + " " + min[2] + " " + min[3] + " " + min[4]);

   }
}

A: Your min array will be initialized with zero values. So the values in numbers will always be higher (assuming there are no negatives).
I'd suggest that you initialize min[j] with numbers[0] before the inner loop.
for (int j=0; j < 5; j++) //finds five highest
{
    min[j] = numbers[0]; // Add this line
    for (int i=0; i < numbers.length; i++)
        {

A: Try debugging your code by entering inside your nested min loop the following line:
System.out.println("the value of numbers[i] is: " + numbers[i]);
so it looks like this:
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
    for (int i=0; i < numbers.length; i++)
        {
            if (numbers[i] < min[j])
            {
                System.out.println("the value of numbers[i] is: " + numbers[i]);
                temp = numbers[i];
                numbers[i] = min[j];
                min[j] = temp;
            }
        }
}

You'll notice something interesting. The innermost nested part doesn't even start.
Try putting that line into the nested max loop in its respective location instead... and it will run fine and show the max array values. You are getting zero values for the min array because (other than initial assigning) the innermost part of the nested min loop isn't being started somehow, so it fails to run and searched values do not get assigned to the min array.
The outer nested parts of the min loop run fine if you try debugging them with a similar line. It's this part that won't start and something's wrong with:
            if (numbers[i] < min[j])
            {
                System.out.println("the value of numbers[i] is: " + numbers[i]);
                temp = numbers[i];
                numbers[i] = min[j];
                min[j] = temp;
            }

(Update)
In the min loop, numbers[i] from i=0 to i=4 have a value of 0 after completing the max loop.
You only need to add one line and use int i=5 instead of int i=0 inside your min loop:
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
    min[j] = max[4];                         // added line
    for (int i=5; i < numbers.length; i++)   // change to int i=5
    {
        if (numbers[i] < min[j])
        {...

A: Just curious , Cant you just sort it(using quick sort) select top five and bottom five ?
- if you can use sorting I think this should work then
            int sum = 0;
    int count = 0;
    int[] max =  {Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE};
    int[] min = {Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE};
    int temp;
    int visited[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    for (int j : numbers)// get sum
    {
        sum += j;
    }

    int tempindex;

    for (int j = 0; j < 5; j++) // finds five highest
    {

        for (int i = 0; i < numbers.length; i++) {
            if (visited[i] != 1) {
                if (numbers[i] > max[j]) {
                    max[j] = numbers[i];
                    tempindex = i;
                }
            }
        }
        visited[tempindex] = 1;
    }

    for (int j = 0; j < 5; j++) // finds five lowest...array not assigned
                                // values
    {
        for (int i = 0; i < numbers.length; i++) {
            if (visited[i] != 1) {
                if (numbers[i] < min[j]) {
                    min[j] = numbers[i];
                    tempindex = i;
                }
            }
        }
        visited[tempindex] = 1;
    }

A: As the other answer states, your problem is that you did not take into account the arrays beginning at 0. In Java, it sets default values for that data structure. For primitives, this will normally be 0 or false. However, when you move into data structures, you will have problems with null pointer exceptions if you fail to initialize your objects. For this reason, I would urge you to get into the habit of setting the values in your data structures before you ever use them. This will save you A LOT of debugging time in the future.

If you know the values in advance, you can set them manually with {0,0,0,0,0} notation, or your can initialize using a for loop:
for(int i = 0; i < array.length; i++)
array[i] = init_value;

I would recommend that you also look into trying to consolidate as much as possible. For example, in your code you go through the same data 4 times:
1) read the integers from the file into an integer array
2) sum all of the numbers in the integer array
3) look for max
4) look for min
I'm not sure if you've covered functions yet, but one example of consolidating this might look like:
while(fr2.hasNextInt()){
int i = fr2.nextInt();
sum += i;
checkHighest(i);
checkLowest(i);
}

You then define these functions and put the meat elsewhere. This lets you only worry about the loops in one place.

A: You have 2 problems.
First was explained by Tom Elliott.
The second problem is that also the max[] array is initialized with 0, and when you search for max values you change the value from max array (which is 0) with the value from the numbers array, so the numbers array becomes filled with 0s.
A quick solve (though not the best) would be to copy the numbers array in a temp array and use that temp when searching for min values.
In case you didn't exactly understood what I said, try to make a print of the numbers array after you found the 5 max values.


text:
Q: Why `volatile` makes no difference? According to the Wikipedia site:
http://en.wikipedia.org/wiki/Volatile_variable
I copied its sample code for testing in my laptop, but the two have no difference! Here is my GCC version info:
i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.1.00)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The C source code is
/* volatile_var.c */
#include <stdio.h>
int main() {
        /* in no_volatile_var.c there is no volatile here */
        volatile int a = 10, b = 100, c = 0, d = 0;
        printf("%d\n", a + b);

        a = b;
        c = b;
        d = b;

        printf("%d\n", c + d);
        printf("%d\n", a);
        return 0;
}

I compiled the no_volatile_var.c and volatile_var.c both with
gcc -S *.c

but the out is the same following
    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:
Leh_func_begin1:
    pushq   %rbp
Ltmp0:
    movq    %rsp, %rbp
Ltmp1:
    subq    $32, %rsp
Ltmp2:
    movl    $10, -12(%rbp)
    movl    $100, -16(%rbp)
    movl    $0, -20(%rbp)
    movl    $0, -24(%rbp)
    movl    -12(%rbp), %eax
    movl    -16(%rbp), %ecx
    addl    %ecx, %eax
    xorb    %cl, %cl
    leaq    L_.str(%rip), %rdx
    movq    %rdx, %rdi
    movl    %eax, %esi
    movb    %cl, %al
    callq   _printf
    movl    -16(%rbp), %ecx
    movl    %ecx, -12(%rbp)
    movl    -16(%rbp), %ecx
    movl    %ecx, -20(%rbp)
    movl    -16(%rbp), %ecx
    movl    %ecx, -24(%rbp)
    movl    -20(%rbp), %ecx
    movl    -24(%rbp), %edx
    addl    %edx, %ecx
    xorb    %dl, %dl
    leaq    L_.str(%rip), %rdi
    movl    %ecx, %esi
    movb    %dl, %al
    callq   _printf
    movl    -12(%rbp), %ecx
    xorb    %dl, %dl
    leaq    L_.str(%rip), %rdi
    movl    %ecx, %esi
    movb    %dl, %al
    callq   _printf
    movl    $0, -8(%rbp)
    movl    -8(%rbp), %eax
    movl    %eax, -4(%rbp)
    movl    -4(%rbp), %eax
    addq    $32, %rsp
    popq    %rbp
    ret
Leh_func_end1:

    .section    __TEXT,__cstring,cstring_literals
L_.str:
    .asciz   "%d\n"

    .section    __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
EH_frame0:
Lsection_eh_frame:
Leh_frame_common:
Lset0 = Leh_frame_common_end-Leh_frame_common_begin
    .long   Lset0
Leh_frame_common_begin:
    .long   0
    .byte   1
    .asciz   "zR"
    .byte   1
    .byte   120
    .byte   16
    .byte   1
    .byte   16
    .byte   12
    .byte   7
    .byte   8
    .byte   144
    .byte   1
    .align  3
Leh_frame_common_end:
    .globl  _main.eh
_main.eh:
Lset1 = Leh_frame_end1-Leh_frame_begin1
    .long   Lset1
Leh_frame_begin1:
Lset2 = Leh_frame_begin1-Leh_frame_common
    .long   Lset2
Ltmp3:
    .quad   Leh_func_begin1-Ltmp3
Lset3 = Leh_func_end1-Leh_func_begin1
    .quad   Lset3
    .byte   0
    .byte   4
Lset4 = Ltmp0-Leh_func_begin1
    .long   Lset4
    .byte   14
    .byte   16
    .byte   134
    .byte   2
    .byte   4
Lset5 = Ltmp1-Ltmp0
    .long   Lset5
    .byte   13
    .byte   6
    .align  3
Leh_frame_end1:

.subsections_via_symbols

According to Wiki's explanation, there should be difference and the volatile edition should bigger than the non-volatile one. I compiled them into binary and find that there size is also the same.
Questions:

*

*Does my llvm-gcc cause that?(latter I'll test these code on Linux) or the Wiki's explanation is error?

*Both them compiled the same binary code(simply according to their size), so their print result is the same. But according to Wiki's explanation, does the two print different screen output?

Update
This question is due to Wikipedia's error on optimization setting, and have no related with what the title says. Should I close this question?

A: Use gcc -O3 to turn on optimizations and you should see a difference.

A: The volatile keyword is merely a hint for the compiler that an external thread might change this variable at any time, so it should be careful with optimizations which rely on the assumption that this won't happen. But your application doesn't have any other threads, so there is no reason to treat it differently.
You could try to compile the program with a higher optimization setting (-O3 command line parameter) - this could cause the compiler to do optimizations on the non-volatile version which are forbidden for the volatile one.

A: If we declare variable as volatile, the compiler can not perform optimization.


text:
Q: loop a PRINT 3 times FOR each TIME it PRINT one word FROM this 3 PRINT I want TO loop a PRINT 3 times FOR each TIME it PRINT one word FROM this 3 SELECT
PRINT I'm mark

PRINT HI
PRINT hello
PRINT how are you

I try this
DECLARE @i INT
SET @i = 0

PRINT 'Im mark'
WHILE @i < 1
BEGIN
PRINT 'hi'
SET @i = @i + 1
END
PRINT '-------------------'
SET @i = 0
PRINT 'Im mark'
WHILE @i < 1
BEGIN
PRINT 'hello'
SET @i = @i + 1
END
PRINT '-------------------'
SET @i = 0
PRINT 'Im mark'
WHILE @i < 1
BEGIN
PRINT 'how are you'
SET @i = @i + 1
END

but it loop all the block 3 time I want the result to be like this
I want a loop it just a simple exemple my work is big
-----loop I------
I'm mark
Hi

-----loop II------
I'm mark
hello

-----loop III------
I'm mark
how are you

A: create table #test(id int,col varchar(50));
insert into #test values(1,'HI');
insert into #test values(2,'hello');
insert into #test values(3,'how are you');

declare @msg varchar(50);
declare @i int;
declare @msgTemp varchar(50);

set @msg='I m Mark' + CHAR(13); -- Char(13) is the New Line character in TSQL
set @i=1;

while(@i<4)
      begin
        print @msg

        select @msgTemp=col
        from #test where id=@i

        print @msgTemp + CHAR(13)

        set @i=@i+1;
      end

Drop table #test


text:
Q: How do I launch an app at start up but as a specific user? I want to launch an app at login but have it running as a specific user. Here's the use case:
I turn on my Mac and login in as Ben. In the background iTunes is launched for Bill. Ben can launch his own instance of iTunes and access Bills songs via iTunes sharing. Ben doesn't care have access to Bills instance of iTunes. All other iTunes on the local network can also access Bills shared iTunes library.
Please don't suggest iTunes specific solutions (e.g. Home Sharing) as I also want to run other apps in a similar fashion.
Is this possible?

A: If you just have two users, you can auto login as Bill, have Bill's account auto-launch multiple apps (see launchd, or via the GUI under User Accounts), and after a timed delay switch users (again, launchd or an Automater App + "sleep 30;" + this), returning you to the login screen. You now manually log in as Ben.
If you want multiple apps running under multiple user accounts in the background, it gets a bit more complicated. Please clarify if this is the case.


text:
Q: 301 redirect subfolder without allowing subdirectories to redirect with same rule I have set up the 301 redirect below which will redirect /jobs and all subpages below it when a user navigates to
https://www.main-domain.com/jobs/
 RedirectMatch 301 /jobs/.* https://www.main-domain.com/all-vacancies/

My issue arises as I have a sub-site in a subdirectory on "main-domain.com" which also uses the path /jobs which is being redirected when I want it excluded e.g.
 https://www.main-domain.com/subsite/jobs/
 # I don't want this url redirected back to https://www.main-domain.com/all-vacancies/

I have tried the below to keep the /jobs to only redirect from the root of the domain but it did not work and I am stumped!
 RedirectMatch 301 ^(?i)/jobs/.*?$ https://www.main-domain.com/all-vacancies/

Cheers, JB.

A: You already match any request contains /jobs/ by your code but to achieve what you want , to only match request starts with jobs , you should do the following  :
RedirectMatch 302 ^/jobs/.* https://www.main-domain.com/all-vacancies/

And also here this .* will not match any thong in new location and every request will be redirected to all-vacancies main page (index) but if you want any request to come as it is to all-vacancies change it to :
RedirectMatch 302 ^/jobs/(.*) https://www.main-domain.com/all-vacancies/$1

Note :   , clear your browser cache and test it .if Ok , change 302 to 301


text:
Q: Configure Kamon and AspectjWeaver in Play application I'm trying to configure a play application to use Kamon. I've created a new play application using
activator new kamon-play play-scala

Then I posted it on github. I'm running on OS X 10.11.1 and I'm running JDK 1.8.0_65-b17 and the project is configured with scala 2.11.6. I've configured it (to the best of my understanding) based on the instructions for configuring Play as well as the sbt-aspectj-runner kamon-play example. However when I try to run the application using either:
sbt run

or
activator run

I get the following error:
[ERROR] [11/25/2015 09:04:39.574] [ForkJoinPool-1-worker-9] [ModuleLoader(akka://kamon)]

  ___                           _      ___   _    _                                 ___  ___ _            _
 / _ \                         | |    |_  | | |  | |                                |  \/  |(_)          (_)
/ /_\ \ ___  _ __    ___   ___ | |_     | | | |  | |  ___   __ _ __   __ ___  _ __  | .  . | _  ___  ___  _  _ __    __ _
|  _  |/ __|| '_ \  / _ \ / __|| __|    | | | |/\| | / _ \ / _` |\ \ / // _ \| '__| | |\/| || |/ __|/ __|| || '_ \  / _` |
| | | |\__ \| |_) ||  __/| (__ | |_ /\__/ / \  /\  /|  __/| (_| | \ V /|  __/| |    | |  | || |\__ \\__ \| || | | || (_| |
\_| |_/|___/| .__/  \___| \___| \__|\____/   \/  \/  \___| \__,_|  \_/  \___||_|    \_|  |_/|_||___/|___/|_||_| |_| \__, |
            | |                                                                                __/ |
            |_|                                                                                |___/

 It seems like your application was not started with the -javaagent:/path-to-aspectj-weaver.jar option but Kamon detected
 the following modules which require AspectJ to work properly:

      kamon-akka, kamon-scala, kamon-play

 If you need help on setting up the aspectj weaver go to http://kamon.io/introduction/get-started/ for more info. On the
 other hand, if you are sure that you do not need or do not want to use the weaver then you can disable this error message
 by changing the kamon.show-aspectj-missing-warning setting in your configuration file.

I've tried all of the following:

*

*Adding aspectj-play-runner:run to the plugins.sbt file (doesn't compile)

*passing in the javaagent argument to activator:
activator -J-javaagent::~/.ivy2/cache/org.aspectj/aspectjweaver/jars/aspectjweaver-1.8.5.jar
but that results in the following error:
Error opening zip file or JAR manifest missing : :~/.ivy2/cache/org.aspectj/aspectjweaver/jars/aspectjweaver-1.8.5.jar
Error occurred during initialization of VM
agent library failed to init: instrument

*

*passing in the javaagent argument to sbt:
sbt run -Djavaagent:~/.ivy2/cache/org.aspectj/aspectjweaver/jars/aspectjweaver-1.8.5.jar
also tried
sbt run -Djavaagent:~/.ivy2/cache/org.aspectj/aspectjweaver/jars/aspectjweaver-1.8.5.jar -Daspectj-play-runner:run

UPDATE
I figured out that aspectj-play-runner:run is an sbt task/command so I tried that:
sbt
aspectj-runner:run

which outputs:
[WeavingURLClassLoader] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
java.lang.RuntimeException: Kamon has not been started yet. You must either explicitlt call Kamon.start(...) or enable automatic startup by adding -Dkamon.auto-start=true to your JVM options.

So then I tried:
sbt -Dkamon.auto-start=true
aspectj-runner:run

Which outputs:
[WeavingURLClassLoader] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
com.typesafe.config.ConfigException$IO: application.conf: java.io.IOException: resource not found on classpath: application.conf

Lastly, the documents actually say I should be running
sbt
aspectj-play-runner:run

But the command/task isn't even recognized.

A: I was able to contact @kamonteam on twitter and this was their reply:

@dvMENTALmadness currently we have a bug in kamon when using the akka and play modules together, until next release that we hope do in...... the weekend for now the only option is remove the kamon-akka module :(

Based on that I removed references to the kamon-akka module from my build.sbt and application.config and now it's working. Once I have an issue # from the project I'll track it and post when the issue is resolved. In the meantime, here's the commit that "fixed" the issue for me. I still need the akka module for it to be a complete solution for me however.

A: One workaround is to set JAVA_OPTS environment variable.
export JAVA_OPTS="-javaagent:$HOME/.ivy2/cache/org.aspectj/aspectjweaver/jars/aspectjweaver-1.8.10.jar"
sbt run


text:
Q: Javascript split with regular expression return empty values Hi I have to split a string in two parts, the first one is always a char the second one is a number.
i.e.
a12
c4
I try to use this expression:

var myString = 'a12';
var mySplits = myString.split(/^([a-zA-Z]{1,2})([0-9]{1,2})$/);
console.log(mySplits);

the array expected is:
["a", "12"]

the result instead is:
["", "a", "12", ""]

I don't understand the reason why the result array has an empty value at start and at end.
Any help is really appreciated.
UPDATE
the solution proposed works but we can use a more elegant way.
ES18
With ES18 we could use the group capturing name

var myString = 'a12';
var matches =
/^(?<letter>[a-zA-Z]{1,2})(?<number>[0-9]{1,2})$/.exec(myString).concat();

console.log(matches.groups.letter);
console.log(matches.groups.number);

ES10
ES10 added the method .matchAll() that returns an Iterator, so if the need is not capture a single value but capture globally this method can be useful.

var myString = 'a12 b12 ';
for (const match of myString.matchAll(/(?<letter>[a-zA-Z]{1,2})(?<number>[0-9]{1,2})/g)) {
  console.log(match.groups.letter);
  console.log(match.groups.number);
}

A: var myString = 'a12';
var list = /^([a-zA-Z]{1,2})([0-9]{1,2})$/.exec(myString).concat();
list.shift();    // remove the first element
console.log(list); //This is the list that you want