text:
Q: what(): No such node json boost I am trying to parse below JSON file using boost::property_tree.
{
    "pi": 3.141,
    "temp": 3.141,
    "happy": true,
    "name": "Niels",
    "nothing": null,
    "answer": {
        "everything": 42
    },
    "list": [
        1,
        0,
        2
    ],
    "object": {
        "currency": "USD",
        "value": 42.99
    }
}

But for second node 'temp', it is giving an error-
terminate called after throwing an instance of 'boost::wrapexcept<boost::property_tree::ptree_bad_path>'
  what():  No such node (temp)
Aborted (core dumped)
@ubuntu:~/git_

Have written code like below-
std::ifstream file(jsonPath, std::ifstream::binary);
  using json = nlohmann::json;
  namespace pt = boost::property_tree;
  pt::ptree root;
  pt::read_json(jsonPath, root);  // Load the json file in this ptree
  string valPi = root.get<string>("pi");
  string valtemp = root.get<string>("temp");

A: Boost Property Tree is not a JSON library.
Why would you (ab)use it, if you already have nlohmann::json included?
Your selector paths may not match the JSON. It's hard to tell because the example you show works correctly:
Live On Coliru
Prints
{
    "pi": "3.141",
    "temp": "3.141",
    "happy": "true",
    "name": "Niels",
    "nothing": "null",
    "answer": {
        "everything": "42"
    },
    "list": [
        "1",
        "0",
        "2"
    ],
    "object": {
        "currency": "USD",
        "value": "42.99"
    }
}
Yay 3.141 and 3.141

No problem.

Note, however, how all type information is lost, which is merely scratching the surface of "limitations" in PropertyTree: https://www.boost.org/doc/libs/1_75_0/doc/html/property_tree/parsers.html#property_tree.parsers.json_parser

Use Boost JSON
Get serious:
#include <boost/json.hpp>
#include <iostream>

int main() {
    auto root = boost::json::parse(R"({
    "pi": 3.141,
    "temp": 3.141,
    "happy": true,
    "name": "Niels",
    "nothing": null,
    "answer": {
        "everything": 42
    },
    "list": [
        1,
        0,
        2
    ],
    "object": {
        "currency": "USD",
        "value": 42.99
    }
})");

    std::cout << root << "\n";
    auto valPi   = root.at("pi").get_double();
    auto valtemp = root.at("temp").get_double();

    std::cout << "Yay " << valPi << " and " << valtemp << "\n";
}

Prints
{"pi":3.141E0,"temp":3.141E0,"happy":true,"name":"Niels","nothing":null,"answer":{"everything":42},"list":
[1,0,2],"object":{"currency":"USD","value":4.299E1}}
Yay 3.141 and 3.141

Using nlohmann::json
Live On Compiler Explorer
#include <nlohmann/json.hpp>
#include <iostream>

int main() {
    auto root = nlohmann::json::parse(R"({
    "pi": 3.141,
    "temp": 3.141,
    "happy": true,
    "name": "Niels",
    "nothing": null,
    "answer": {
        "everything": 42
    },
    "list": [
        1,
        0,
        2
    ],
    "object": {
        "currency": "USD",
        "value": 42.99
    }
})");

    std::cout << root << "\n";
    auto valPi   = root["pi"].get<double>();
    auto valtemp = root["temp"].get<double>();

    std::cout << "Yay " << valPi << " and " << valtemp << "\n";
}

Prints
{"answer":{"everything":42},"happy":true,"list":[1,0,2],"name":"Niels","nothing":null,"object":{"currency"
:"USD","value":42.99},"pi":3.141,"temp":3.141}
Yay 3.141 and 3.141


text:
Q: Memory Units, calculating sizes, help! I am preparing for a quiz in my computer science class, but I am not sure how to find the correct answers. The questions come in 4 varieties, such as--
Assume the following system:
Auxiliary memory containing 4 gigabytes,
Memory block equivalent to 4 kilobytes,
Word size equivalent to 4 bytes.

*

*How many words are in a block,
expressed as 2^_? (write the
exponent)

*What is the number of bits needed to
    represent the address of a word in
    the auxiliary memory of this system?

*What is the number of bits needed to
represent the address of a byte in a
block of this system?

*If a file contains 32 megabytes, how
many blocks are contained in the
file, expressed as 2^_?

Any ideas how to find the solutions? The teacher hasn't given us any examples with solutions so I haven't been able to figure out how to do this by working backwards or anything and I haven't found any good resources online.
Any thoughts?

A: Work backwards. This is actually pretty simple mathematics. (Ignore the word "auxilliary".)

*

*How much is a kilobyte? How much is 4 kilobytes? Try putting in some numbers in 2^x, say x == 4. How much is 2^4 words? 2^8?

*If you have 4GB of memory, what is the highest address? How large numbers can you express with 8 bits? 16 bits? Hint: 4GB is an even power of 2. Which?

*This is really the same question as 2, but with different input parameters.

*How many kilobytes is a megabyte? Express 32 megabytes in kilobytes. Division will be useful.

A: Questions like these basically boil down to working with exponents and knowing how the different pieces fit together.  For example, from your sample questions, we would do:

How many words are in a block, expressed as 2^_? (write the exponent)

From your description we know that a word is 4 bytes (2^2 bytes) and that a block is 4 kilobytes (2^12 bytes).  To find the number of words in one block we simply divide the size of a block by the size of a word (2^12 / 2^2) which tells us that there are 2^10 words per block.

What is the number of bits needed to represent the address of a word in the auxiliary memory of this system?

This type of question is essentially an extension of the previous one.  First you need to find the number of words contained in the memory.  And from that you can get the number of bits required to represent a word in the memory.  So we are told that memory contains 4 gigabytes (2^32 bytes) and that the word is 4 bytes (2^2 bytes); therefore the number words in memory is 2^32/2^2 = 2^30 words.  From this we can deduce that 30 bits are required to represent a word in memory because each bit can represent two locations and we need 2^30 locations.
Since this is tagged as homework I will leave the remaining questions as exercises :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert form input type file attributes into database I want to start off with that this will be my first post on Stackoverflow, so thanks for helping me in advance.
I'm trying to make a form in which i can enter a name, artist, genre and upload an audio file into a folder.
I have it all setup except for the query doesn't work.
Here is the form:
<form action="upload" method="post" enctype="multipart/form-data">

Title:

        <input type="text" class="form-control" name="musicName" id="musicName" required />

Artist:

        <input type="text" class="form-control" name="musicArtist" id="musicArtist" required />

Genre:

        <select class="form-control" name="musicGenre" id="musicGenre" required >
          <option value="hiphop">Hip Hop</option>
          <option value="trap">Trap</option>
          <option value="pop">Pop</option>
          <option value="edm">EDM/Dance</option>
          <option value="rock">Rock</option>
          <option value="rnb">RnB</option>
          <option value="jazz">Jazz</option>
          <option value="country">Country</option>
          <option value="metal">Metal</option>
          <option value="blues">Blues</option>
          <option value="reggae">Reggae</option>
          <option value="classical">Classical</option>
        </select>

    drop a file to upload

    <input type="file" name="fileToUpload" id="fileToUpload" class="hidden" multiple>

    <input type="submit" value="Upload Image" id="submitSong" name="submitSong" class="btn btn-primary">

Then first i do all my checks etc.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$file_name = $_FILES["fileToUpload"]["name"];
$file_tmp = $_FILES["fileToUpload"]["tmp_name"];
$file_size = $_FILES["fileToUpload"]["size"];
$file_type = $_FILES["fileToUpload"]["type"];

$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submitSong"])) {
    $check = filesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
    } else {
        echo "";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "";
    $uploadOk = 0;
}

$filesize = 5000000;

// Check file size
if ($_FILES["fileToUpload"]["size"] > $filesize) {
    echo "";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "mp3" && $imageFileType != "wav" && $imageFileType != "flac" ) {
    echo "";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "";

And then at last i upload the file and the attributes that came with it
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

        if(isset($_POST[`submitSong`]))
    {
        $song_title = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicName`]));
        $song_artist = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicArtist`]));
        $song_genre = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicGenre`]));
        $current_time = `CURRENT_TIMESTAMP`;

        $sql = "INSERT INTO songs (song_name, song_artist, song_genre, uploaded_at, song_link, user_id VALUES
        ($song_title, $song_artist, $song_genre, $current_time, $file_tmp," . $_SESSION[`userid`] . ")";
        // ($song_title, $song_artist, $song_genre, $current_time, $file_tmp," . $_SESSION[`userid`] . ")";

        $result = $mysqli->query($sql);

        var_dump($result);

        // echo "";

    }

    } else {
        echo "";
        // echo "Sorry, there was an error uploading your file.
";
    }
}?>

Any help would be appreciated!


text:
Q: How to decode JSON data with mlr3 package in the prediction phase? I have developed a graphlearner with the mlr3 package and I would like to publish it in a Rplumber service. However, when I receive the data to make predictions (data in JSON format), the graphlearner has trouble recognizing the data because the fromJSON function of jsonlite does not infer the right types (on which the graph was learned). Do you have a solution for this ? is there a mechanism to manage JSON data in mlr3 in the prediction phase?
Learning step
library(mlr3)
imp_missind = po("missind")
imp_fct     = po("imputenewlvl", param_vals =list(affect_columns = selector_type("factor")))
imp_num     = po("imputehist", param_vals =list(affect_columns = selector_type("numeric")))
learner = lrn('regr.ranger')
graph = po("copy", 2) %>>%
  gunion(list(imp_missind, imp_num %>>% imp_fct)) %>>%
  po("featureunion") %>>%
  po(learner)
t1 = tsk("boston_housing")
g1 = GraphLearner$new(graph)
g1$train(t1)
saveRDS(g1,'my-model')

Predction step : it works  (simulate data to prediction, remove target col)
data=t1$data()[1:1,-1]
model = readRDS('my-model')
model$predict_newdata(newdata=data)

Predction step : it does not work  (simulate JSON data to prediction)
model = readRDS('my-model')
data = t1$data()[1:1,-1]
json = fromJSON(toJSON(data, na="string"))
model$predict_newdata(newdata=json)

and the error  :
Erreur : Cannot rbind task: Types do not match for column: cmedv (numeric != integer)
UPDATE  reproducible example
library(mlr3learners)
library(mlr3)
library(mlr3pipelines)
library(jsonlite)

imp_missind = po("missind")

imp_fct     = po("imputenewlvl", param_vals =list(affect_columns = selector_type("factor")))

imp_num     = po("imputehist", param_vals =list(affect_columns = selector_type("numeric")))

learner = lrn('regr.ranger')

graph = po("copy", 2) %>>%
  gunion(list(imp_missind, imp_num %>>% imp_fct)) %>>%
  po("featureunion") %>>%
  po(learner)

task = tsk("boston_housing")

graphlearner = GraphLearner$new(graph)

#train model
graphlearner$train(task)

# create data to predict  (juste one observation)

data= task$data()
data[1:1, chas := NA]
data = data[1:1,-1]

# look the the types of columns
str(data)

# predictin, this works fine
predict(graphlearner, data)

# simulate the case when json data is received

json_data = toJSON(data, na="string")

print(json_data)

# get R data from json formatted data
data_from_json = fromJSON(json_data)

# look the types of columns, some are different numeric != integer, factor != char
str(data_from_json)

# try to predict, this does not work, get erro  :    cmedv (numeric != integer)
predict(graphlearner,data_from_json)

A: I think we might want to fix this at some point, but until a fix is available I would suggest to fix the problem by repairing the schema given you saved task$feature_types:
library(mlr3misc)
repair_schema = function(data, feature_types) {
   imap_dtc(data, function(v, k) {
    ft_type = feature_types[id == k,][["type"]]
    if (typeof(v) != ft_type) {
      fn = switch(ft_type,
        "character" = as.character,
        "factor" = as.factor,
        "numeric" = as.numeric,
        "integer" = as.integer
      )
      v = fn(v)
    }
    return(v)
  })
}
data_from_json2 = repair_schema(data_from_json, task$feature_types)
predict(graphlearner,data_from_json2)

This approach would also provide you with more flexibility, as you might encounter a range of encoding problems that can not always be anticipated.


text:
Q: Intercept console logs to file Nodejs I am working on a game using NodeJs, and realized it would be immensly helpful to have access to old console.log output. The mechanics and calculations get rather complicated, and it would be nice to have access to them later to search through and do some data analysis on them to find the correct values for my modifiers (battle mechanics). At the same time, I want to see console.log in the console as well.

I know this isn't possible with regular javascript, (see This), but I was hoping npm had a package of some way to intercept logs and log them to a file on the server. Any thoughts?

A: An NPM option to log to stdout and to a file at the same time could be Winston. Winston is a logging library that allows you to define your own loggers, specifying their transports (a transport being what do you do with these log lines). In your case, you could define a logger with two transports, stdout and a log file. Example (inspired by the Winston documentation):
const winston = require('winston');

let logger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)(),
        new (winston.transports.File)({ filename: 'somefile.log' })
    ]
});

logger.info('hello, world!');

If you run this code above, you'll see the logs in the console and in somefile.log.

A: You can intercept console.log like so
var cl = console.log

console.log = function(...args){
  // your custom logging logic here
  cl.apply(console, args)
}

A: The purest form would be by overriding stdout and stderr methods, e.g.
process.stdout.write = (data) => {
  w(data);
};

process.stderr.write = (data) => {
  w(data);
};

Here w is whatever mechanism that you would like to use to record this data, e.g.
const w = (...args) => {
  appendFileSync(
    path.resolve(__dirname, "test.json"),
    JSON.stringify(args, null, "  ")
  );
};

Beware that you cannot output anything from this function as that would cause an infinite loop.
The above behaviour would discard any output though. If you want the program to continue producing output, then you need to call the original write methods, e.g.
const stdoutWrite = process.stdout.write.bind(process.stdout);
const stderrWrite = process.stderr.write.bind(process.stderr);

process.stdout.write = (data, callback) => {
  w(data);

  return stdoutWrite(data, callback);
};

process.stderr.write = (data, callback) => {
  w(data);

  return stderrWrite(data, callback);
};


text:
Q: Use of isolate scope - @, &, and = in a simple Angular Directive I have made a simple example with Angular.js directives for 'Celebrity Name'. I am reading about isolated scopes @,&,=, but I dont know how to use these in the following simple example to understand their usage and differences. Can someone help me out?
HTML:

    <celebrity></celebrity>
    <celebrity></celebrity>
    <celebrity></celebrity>

Result:
Currently all my 3 instances of directive 'celebrity' print 'Brad Pitt'.

Please, someone tell me how to use the 3 types of isolate scope in this simple example.

A: The 3 symbols, have different use :

*

*@(read more) : allow you to pass a string from your current scope to the isolated one.

html :

  <my-dir first-attr="Hello" second-attr="{{what}}"></my-dir>

js :
angular
.controller('myCtrl', function ( $scope ) {
  $scope.what = 'World !'
})
.directive('myDir', function () {
  return {
    scope : {
      firstAttr  : '@',
      secondAttr : '@'
    }
    controller : function ($scope, $log) {
      $log.log($scope.firstAttr + ' ' + $scope.secondAttr);  // logs : 'Hello World !'
    }
  };
});

*

*= (read more) : allow you to pass an object that you can use and modify from the isolated scope.
The thing is, if you want to modify this object, never change directly the object itself or it will break the two way bindings
between your current scope and the isolated one and create two different copies of it (one in the current scope, and one in the isolated).
So just alter its properties to keep bindings unless is it what you want.

html :

  <my-dir my-attr="helloWorld"></my-dir>

js :
angular
.controller('myCtrl', function ( $scope ) {
  $scope.helloWorld = {
    first   : 'Hello',
    second  : 'World !'
  };
})
.directive('myDir', function () {
  return {
    scope : {
      myAttr  : '='
    }
    controller : function ($scope, $log) {
      $scope.myAttr.second = 'Space !';

      $log.log($scope.myAttr.first + ' ' + $scope.myAttr.second);  // logs : 'Hello Space !'
    }
  };
});

*

*&(read more) allows you to call a function expression of your current scope from the isolated scope.

html :

  <my-dir my-attr="helloWorld"></my-dir>

js :
angular
.controller('myCtrl', function ( $scope ) {
  $scope.helloWhat = function ( what ) {
    $log.log('Hello ' + what + ' !');
  };
})
.directive('myDir', function () {
  return {
    scope : {
      myAttr  : '&'
    }
    controller : function ($scope, $log) {
      $scope.myAttr('Angular');      // logs : 'Hello Angular !'
    }
  };
});


text:
Q: How to write a Choose function in powershell to edit the pipeline? I wish to edit the git sparse-checkout information inplace using the nvim editor. I have the following code that almost works.

function Choose () {
    begin {
        $file = New-TemporaryFile
    }
    process
    {
        $_ >> $file
    }
    end {
        nvim $file
        Get-Content $file
        Remove-Item $file
    }
}

function Git-Sparse-Checkout-Edit
{
    git sparse-checkout list | Choose | git sparse-checkout set --stdin

}

if I write
git sparse-checkout list | Choose

then the nvim editor is opened on the output of the git sparse-checkout command and when I 'wq' ( save and quit ) then the contents of the file are written to stdout. But when I try
git sparse-checkout list | Choose | git sparse-checkout set --stdin

instead of opening the editor the entire windows terminal stalls and I have to kill it. Is my Choose function correctly implemented?

A: function Choose () {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string[]]
        $Text
    )
    begin {
        $file = New-TemporaryFile
        $Text
    }
    process
    {
        foreach ($line in $Text){
            $line >> $file
        }
    }
    end{
        start-process nvim $file -wait
        Get-Content $file
        Remove-Item $file
    }
}

and using it to edit the git sparse-checkout list
function Git-Sparse-Checkout-Edit
{
    git sparse-checkout list | Choose | git sparse-checkout set --stdin

}

Using start-process seems to be the key to stop the pipeline stalling though I'm not sure why.


text:
Q: Upper bound of joint probability of two RVs $X$ and $Y$, $\mathbb P(XAssume that $X$ and $Y$ are random variables and they are independent.
They are following their own distributions, for example, $X$ follows $\mathcal{D}_{X}$.
Let me draw a sample from the distribution $\mathcal{D}_{X}$ and call it $X_1$.
I know that the probability $\mathbb P(X_1 < Y_1) = a$.
However, now I want to pick more samples from $\mathcal{D}_{Y}$, for example, I sample $n$ instances, $Y_1,..., Y_n$.
I would like to make an upper bound of $\mathbb P(X_1<Y_1, X_1<Y_2,..., X_1<Y_n)$ in terms of $a$.
Any suggestions will be appreciated.

One of my trial
$$\mathbb P(X_1<Y_1, ..., X_1<Y_n) = \sum_{x} \mathbb P\left(X_1<Y_1, ..., X_1<Y_n \mid X_1=x\right)\mathbb P(X_1=x) = \sum_x {\mathbb P(x<Y)}^n \mathbb P(X_1=x),$$ but hard to link it to $a$.

A: For an upper bound, the best that you can do is
$$
\Pr(X_1 < Y_1 , \dotsc, X_1 < Y_n)
\leq \Pr(X_1 < Y_1)
= a.
$$
To see that this is tight for any $a$, let $X \sim \mathrm{Bernoulli}(1 - a)$ and $Y_n = 1/2$ so that
$$
\Pr(X_1 < Y_1 , \dotsc, X_1 < Y_n)
= \Pr(X_1 = 0)
= a.
$$
More interesting is a lower bound, that follows from Jensen's inequality.
Since $X_1$ is independent from the $Y_i$, we have
\begin{align*}
\Pr(X_1 < Y_1 , \dotsc, X_1 < Y_n)
&= \mathbf{E}[\Pr(X_1 < Y_1| X_1)^n ] \\
&\geq \mathbf{E}[\Pr(X_1 < Y_1 | X_1)]^n \\
&= \Pr(X_1 < Y_1)^n \\
&= a^n .
\end{align*}
This bound is also tight, which follows from taking $X_1 = 1 - a$ and $Y_n \sim \mathrm{Uniform}(0, 1)$.


text:
Q: Wrong overlap in bar3d plot I've made this 3d bar plot, but I've found a wrong overlap in some bars, as I show in the image below with green circles:
The plot is made by:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.colors as colors

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')
matrix = np.array([
[84 80 68 56 60 44 55 39 27 29]
[82 67 63 44 47 33 22 19  9  2]
[53 61 48 34  0 16  0  0  0  0]
[48 25  0  0  0  0  0  0  0  0]])

len_x, len_y = matrix.shape
_x = np.arange(len_x)
_y = np.arange(len_y)

xpos, ypos = np.meshgrid(_x, _y)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)

dx = np.ones_like(zpos)
dy = dx.copy()
dz = matrix.flatten()

cmap=plt.cm.magma(plt.Normalize(0,100)(dz))

ax.bar3d(xpos+0.32, ypos-0.3, zpos, dx-0.6, dy-0.1, dz, zsort='max', color=cmap)

ax.set_xlabel('x')
ax.set_xticks(np.arange(len_x+1))
ax.set_xticklabels(['1000','500','100','50','0'])
ax.set_xlim(0,4)
ax.set_ylabel('y')
ax.set_yticks(np.arange(len_y+1))
ax.set_yticklabels(['0.5','1.','1.5','2.','2.5','3.','3.5','4.','4.5','5.'])
ax.set_ylim(-0.5,10)
ax.set_zlabel('z')
ax.set_zlim(0,100)
ax.view_init(ax.elev, ax.azim+100)

Is it a bug? Why some bars are badly overlapping?
I'm using matplotlib version 2.1.0 and anaconda python 3.6.3

A: As pointed out by @DavidG in the comments, this is an issue without an ideal solution:

My 3D plot doesn't look right at certain viewing angles
This is probably the most commonly reported issue with mplot3d. The problem is
that – from some viewing angles – a 3D object would appear in front of
another object, even though it is physically behind it. This can
result in plots that do not look "physically correct."
Unfortunately, while some work is being done to reduce the occurrence
of this artifact, it is currently an intractable problem, and can not
be fully solved until matplotlib supports 3D graphics rendering at its
core.
[Source]

However, I was able to greatly reduce this issue by playing with the viewing angle of the plots and reducing the contact areas between the bars.
For example, to change the viewing angle (the "camera position"), I used:
ax.view_init(elev=30, azim=-60) # Changes the elevation and azimuth

More details in how to set "camera position" for 3d plots using python/matplotlib?
As per the contact areas, it depends on your plot. In my case, all the bars had contact alongside the y axis, so I just reduced the dy param a little to left some gap between the bars.


text:
Q: Cordova app using WebSQL hit quota limit and cannot recover I have hit a quota roadblock on iOS using standard Cordova WebSQL (with MS OpenTech polyfill plugin but I don't think it actually uses that on iOS).
An error is thrown from WebSQL indicating quota exceeded. When this happens I catch the error and drop my main table, then refresh it from the internet.
However, when it hits the quota limit it either will not allow a drop table statement to proceed or the drop statement doesn't free any space because the quota error still keeps coming up. Does anyone know why dropping the table wouldn't free space? I have also tried the vacuum statement which thinks for a while but does not appear to free any space either.
Note that this is an existing app in the field so I would prefer not to switch out the database platform unless we need to. (I see there is a plugin available now (https://github.com/litehelpers/cordova-sqlite-ext) which says it has no quota limit - could be the best/only solution?)

A: I decided to replace my default WebSQL with the plugin https://github.com/litehelpers/cordova-sqlite-ext
It went extremely well. This plugin swapped out without any code changes needed in my SQL statements!!! Very pleased!
I tested adding a couple of GB of data to the database and it performed very well and at no point stopped accepting data.
By the way, I tested the limits default WebSQL on iOS and found it dies in a screaming heap at 50MB exactly. You cannot delete any data, drop or vacuum from that point and so you can never recover. It is a pretty serious bug! (This is still recommended as an option on the Cordova docs - it should come with a serious warning)


text:
Q: puppet or chef for stand alone server with limited resources I have a small virtual linux server (500 megs ram). I may eventually get one or two more servers, not more.
I'm a dev, not a sys admin so I don't know the best practices involving linux administration. I do know that I don't want to setup a machine, issue a bunch of commands to set up users, install packages, change environment variables, only to lose all of it if my machine crashes.
I'd rather keep all this information in a source repository, along with my code.
Obvious solutions are puppet or chef, but I don't run a cluster of machines. I want a declarative way of setting up users, installing packages, etc. but don't want to setup ssl certificates, master servers, etc. (frankly, I can't, my machines are very cheap and have very little memory).
Is there a better solution for stand-along machines? I want to be able to use this solution quickly to re-create my machine (on amazon, linode, rackspace or my down desktop).

A: Puppet is pretty easy to setup. You don't have to do almost anything, and a client can run standalone. Let me just give you an example. Say you have a file called config.pp with the following lines:
package { 'apache2': ensure => installed }
service { 'apache2':
   ensure  => running,
   enable  => true,
   require => Package['apache2'],
}
user { 'bob':
   ensure  => present,
   uid     => 1000,
   gid     => 'bob',
   require => Group['bob'],
}
group { 'bob':
    ensure => present,
    gid    => 1000,
}

If you run puppet apply config.pp, it will ensure the package apache2 is installed, that the service is running and enabled to start when booting, and that the user bob will be created with the group bob.
That's all -- install puppet client, type that into this file, and run a command. You may schedule that on crontab if you feel like guaranteeing the configuration is kept in check, without a master. I once installed 10 ganeti servers -- which involves setting up a number of packages and configurations, with at least one reboot midway -- pretty much like this.
Puppet does consume some memory -- 500 MB is a bit on the low end, but if you are going to run it mostly to install stuff, it should be enough. I keep my own servers at 1 GB, at least, to guarantee puppet won't cause problems to the services running on the server.
Also, Puppet is definitely declarative, though you may need to augment it a bit either with scripts to be run, or with ruby code to teach it new tricks. For your needs, it seems unlikely you'll have to resort to that.

A: Cfengine is a configuration management tool, that inspired Puppet and then Chef, with a proven record going over 15 years.
A few points to note:

*

*It's easy to setup - see this guide by IBM

*It can run standalone (no server required)

*It is very economical on resources - memory consumption is described in this blog post - both for running once off and as a resident daemon

*It is coded in C, and has very few dependencies (only BerkeleyDB and the PCRE library)

You can automate your installation procedures and have Cfengine check them out of a source repository, and be able to replay them on any server if you lose your current one. You'll also get the added benefit of automatic reparations - once you've defined the state you want your server to be in, any changes (ie, a package gets removed, a user deleted, etc) will be automatically reverted by the configuration management tool.


text:
Q: Are there unconditional results for boundedness of finitely many rational points on $f(x,y)=n$ for all $n$? Major rewrite due to comments.
Let $f(x,y) \in \mathbb{Q}[x,y]$ and $f$ depends on both $x,y$.

Q1 Is it possible the number of rational solutions to $f(x,y)=n$
  to be uniformly bounded for all rational $n$?

Looking for unconditional answer.
It is conjectured that polynomial injection $\mathbb{Q}^2 \to \mathbb{Q}$
exists and proving this will give bound $1$ (there are suspected injections).


text:
Q: How to get access of an variable or an function from a foreign in angular? I am new in angular and there are many variables in an existing code that I want to acess from an other controller other than where they get declared. The controllers are sibling controllers. Does anyone has any other idea how something like that can work or is firing to the rootscope the only possibility?
I tried firing to the rootscope but that didint work.


text:
Q: Clearing Locks between JUnit tests in Hibernate Search 4.1 we recently upgraded to Hibernate Search 4.1 and are getting errors when we run our JUnit tests based on the changes hibernate made with regards to locks.  When we run Junit tests with  the AbstractTransactionalJUnit4SpringContextTests we often see locks left after each test. In reviewing (How to handle Hibernate-Search index recovery) we tried the native locks, but this did not resolve the issue.
We've tried out the various locking mechanisms (simple, single, and native) using the default directory provider (Filestore) and regularly see messages like:
build   20-Apr-2012 07:07:53    ERROR 2012-04-20 07:07:53,290 154053 (LogErrorHandler.java:83) org.hibernate.search.exception.impl.LogErrorHandler  - HSEARCH000058: HSEARCH000117: IOException on the IndexWriter
build   20-Apr-2012 07:07:53    org.apache.lucene.store.LockObtainFailedException: Lock obtain timed out: NativeFSLock@target/indexes/Resource/write.lock
build   20-Apr-2012 07:07:53        at org.apache.lucene.store.Lock.obtain(Lock.java:84)
build   20-Apr-2012 07:07:53        at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:1108)

or
build   19-Apr-2012 19:31:09    ERROR 2012-04-19 19:31:09,395 153552 (LuceneBackendTaskStreamer.java:61) org.hibernate.search.backend.impl.lucene.LuceneBackendTaskStreamer  - HSEARCH000072: Couldn't open the IndexWriter because of previous error: operation skipped, index ouf of sync!

Some of these messages seem to show the lock issue cascading from one test to another, hence the need for the reset, and some may be valid because the tests are testing 'invalid' behaviors and how our application reacts to them, but often because of cases like this where the ID is null
build   19-Apr-2012 19:31:11    Primary Failure:
build   19-Apr-2012 19:31:11        Entity org.tdar.core.bean.resource.CodingSheet  Id null  Work Type  org.hibernate.search.backend.PurgeAllLuceneWork

But, regardless, we need to make sure that one test does not effect another.
In reading some of the discussions (email discussion on directory providers) it was suggested that the RAM based directory provider might be a better option, but we'd prefer to use the same provider as we use in production wherever possible.
How should we be resetting HibernateSearch between tests to clean up lock files and reset potential issues where the index is out-of-sync or corrupted? At the beginning of the test suite, we wipe the index directory, is it recommended to wipe it after every test?
thanks

A: If you have stale locks in the directory, it means that Hibernate Search wasn't shut down properly as it certainly will close the locks.
If you start a new Hibernate SessionFactory in each test, you should make sure it's closed as well after the test was run:
org.hibernate.SessionFactory.close()

(This is often missing in many examples as there are no noticeable problems when forgetting to close a Hibernate SessionFactory, but has never been optional and might leak connections or threads).
The thread from the Hibernate mailing list you linked to ended up changing the locks to use native handles in Hibernate Search 4.1, so that locks are cleaned up automatically in case the JVM crashes or is killed. But in your case I guess you're not killing the VM between tests, so you just need to make sure locks are released properly by shutting down the service.
exclusive_index_use=false hides the problem as the IndexWriter will be closed at the end of each transaction. That makes it slower though, as it's significantly more efficient to reuse the IndexWriter. The reason you have this issue after upgrading to Hibernate Search 4.1 is that this option was changed to true by default. But even then, you should still close it properly.

A: My understanding is that Spring manages the SessionFactory lifecycle, so it is not necessary to call close() at any time.
I have seen this locking error when there are multiple contexts loaded during a test run. For example, the first context creates the locks on the index file. The second context attempt to access the same indexes and fails due to the existence of the open SessionFactory from the first context.
I have fixed this by using @DirtiesContext which closes context before the next is instantiated


text:
Q: How I can implements method from one class in another class I have class Shape2D, in that class I have method that calculate circle area circleArea, also I have class CircleArea where I store all atributes that I need for my method. Also, my class CircleArea extends class Shape2D. So, How I can implement my method from class Shape2D into class CircleArea.
This is my Shape2D class:
public class Shape2D {
    public static void areaCircle(Circle c) {
        double circleArea = Math.pow(c.getR(), 2) * Math.PI;
    }
}

And this is my Circle class:
public class Circle extends Shape2D {

    private double r;

    public Circle() {
    }

    public double getR() {
        return r;
    }

    public void setR(double r) {
        this.r = r;
    }

}

A: To implement one of the methods from the Shape2D class in the Circle class, you could do:
Shape2D.areaCircle(circleObject);

The above line can be called in the Circle class. Don't forget to pass  in an actual circle object into the function.

A: You have a static method inside of 2D shape, meaning you can use it in any class without having 2DShape instantiated. This also means that you do not need the circle class to extend 2DShape to use this method, but I imagine you are going for that parent child relationship for the OO paradigm. If you don't want the method to be called from any class, remove static from the method. If you wish to call it statically inside of your Circle class constructor, first instantiate r to something, and then pass it into the static method call.
public class Circle extends Shape2D {

    private double r;

    public Circle() {
         r=1;
         Shape2D.areaCircle(this);
    }

    public double getR() {
        return r;
    }

    public void setR(double r) {
        this.r = r;
    }

}

Note that your static function doesn't actually return anything, so it calculates the area and the value is lost. You can fix this inside of shape2D by changing the return type of circleArea to double in stead of void, and returning the result appropriately.
public static double areaCircle(Circle c) {
        double circleArea = Math.pow(c.getR(), 2) * Math.PI;
        return circleArea;
    }

or non-statically, and protected in stead of public (either will work)
protected double areaCircle(Circle c) {
        double circleArea = Math.pow(c.getR(), 2) * Math.PI;
        return cricleArea;
    }

If you wanted to do the same thing, but removed the static flag from the method, then you can use super to call parent methods.
public class Circle extends Shape2D {

    private double r;

    public Circle() {
         r=1;
         super.areaCircle(this);
    }

    public double getR() {
        return r;
    }

    public void setR(double r) {
        this.r = r;
    }

}

Now if you wanted to actually store the area inside of this circleObject, I would create another attribute for the Circle class, and modify your constructor as such. Perhaps even adding a constructor that takes an int argument for radius (or in the future, an area with some way to differentiate the two that can get the radius value).
public class Circle extends Shape2D {

    private double r;
    private double area;
    //Default Constructor
    public Circle() {
         r=1;
         this.area = super.areaCircle(this);
    }
    //Radius constructor
    public Circle(double rad) {
        this.r = rad;
        this.area = super.areaCircle(this);
    }
    public double getR() {
        return r;
    }

    public void setR(double r) {
        this.r = r;
    }

}

It's also worth mentioning that you should look at the scope of these methods you create, and what you are trying to accomplish with them. For instance, you have your circleArea method defined as public, when it could be defined as protected and function similarly for this case. Protected means that the method can be used inside of the class, as well as all subclasses (children of the parent class, like circle). You can read information about these closures here. Also, when working with object inheritance, you should get into the habit of using the this keyword to reference which methods/attributes you actually wish to retrieve. Info on this keyword.
I realize this is a lot to take in, but if you have any questions feel free to comment!


text:
Q: Controls re-initialization using WatiN I ran in to a situation where I need to re-initialize the controls of each page when the page gets loaded for each test. I have separated the controls declaration of a page in one code file and operation that are performed on those controls in another code file.
I have exposed those operations to the test cases, so that no controls are passed from test cases.
I have implemented Singleton for controls initialization. Due to this, the first test case excutes with out any issues. When second test kicks off, it says "Object reference not set to an instance of an object." when trying to access control that is already initialized.
public partial class Login : Page
{
    protected TextField txtUserName;
    protected TextField txtPassword;
    protected TextField txtConPassword;

    public Login()
      {
        this.txtUserName = Util.Browser.TextField(Find.ById("username"));
        this.txtPassword = Util.Browser.TextField(Find.ById("password"));
        this.txtConPassword = Util.Browser.TextField(Find.ByValue("password"));
      }
 }

public partial class Login

  {
    /// <summary>

    /// Set user name.

    /// </summary>

    /// <param name="userName">User name.</param>

    public void SetUserName(string userName)
    {
        this.txtUserName.TypeText(userName);
        //Util.SetTextHelper(this.txtUserName, userName);
    }
 }

I guess the controls get initialized only when Browser gets loaded with Document. When the first test ends, Browser gets closed and disposed. So when the Browser gets re-initialized (for the second test) with the document since the controls initialization implemented using a Singleton, the control values throws the error.
This issue can be resolved by not implementing Singleton, but re-initializing the controls where ever required does not make sense.

A: UPDATED!  Try using the WatiN FindBy attribute...
public partial class LoginPage : Page
{
    [FindBy(Id = "username")]
    public TextField txtUserName;

    [FindBy(Id = "password")]
    public TextField txtPassword;

    [FindBy(Value = "password")]
    public TextField txtConPassword;
}

public partial class LoginPage
{
    public void SetUserName(string userName)
    {
        this.txtUserName.TypeText(userName);
    }
}

public void LoginTest()
{
    using (IE browser = new IE())
    {
        browser.GoTo("http://yourLoginPage.html");

        LoginPage loginPage = browser.Page<LoginPage>();
        loginPage.SetUserName("some_username");

        //Do your other stuff

        //If you haven't navigated away from the page this should still work
        //If not just grab the login page again: -
        //loginPage = browser.Page<LoginPage>();
        loginPage.SetUserName("some_other_username");
    }
}

HTH!


text:
Q: RDD operation to sort values in pyspark I have a file format as follow,
0, Alpha,-3.9, 4, 2001-02-01, 5, 20
0, Beta,-3.8, 3, 2002-02-01, 6, 21
1, Gamma,-3.7, 8, 2003-02-01, 7, 22
0, Alpha,-3.5, 4, 2004-02-01, 8, 23
0, Alpha,-3.9, 4, 2005-02-01, 8, 27

I want to sort distinct 1st elements in each line by 3rd elements using rdd operation. I prefer to get the following output,
(Beta, 3)
(Alpha, 4)
(Gamma, 8)

This is what I have done at the moment,
rdd = sc.textFile(myDataset)
list_ = rdd.map(lambda line: line.split(",")).map(lambda e : e[1]).distinct().collect()
new_ = list_.sortBy(lambda e : e[2])

But I could not sort as I wanted. Could anyone tell how to do this only rdd based operation?

A: rdd = sc.textFile(myDataset) is correct.
list_ = rdd.map(lambda line: line.split(",")).map(lambda e : e[1]).distinct().collect()
new_ = list_.sortBy(lambda e : e[2]) # e[2] does not exist.

You already called collect on list_, so it is no longer an RDD. Then you have proceeded to call sortBy on it, so it won't work. Perhaps you made this mistake while posting.
The main issue is the map operation. You need to create a pairWiseRdd, but you have not created one. Hence, there is no e[2] to sort with. See below.
>>> rdd.map(lambda line: line.split(",")).map(lambda e : e[1]).collect()
[' Alpha', ' Beta', ' Gamma', ' Alpha', ' Alpha']

The above will not have the value you need to use the distinct()
Instead, you need to do this
>>> list_ = rdd.map(lambda line: line.split(",")).map(lambda e : (e[1],e[3]))
>>> list_.collect()
[(' Alpha', ' 4'),
 (' Beta', ' 3'),
 (' Gamma', ' 8'),
 (' Alpha', ' 4'),
 (' Alpha', ' 4')]
>>> distinct_rdd = list_.distinct() #making stuff distinct
>>> distinct_rdd.collect()
[(' Alpha', ' 4'), (' Beta', ' 3'), (' Gamma', ' 8')]

Now that we have made our pairWiseRdd, we can use the second value of every pair to sort it.
>>> sorted_rdd = distinct_rdd.sortBy( lambda x:x[1] )
>>> sorted_rdd.collect()
[(' Beta', ' 3'), (' Alpha', ' 4'), (' Gamma', ' 8')]


text:
Q: template instantiation issue with complex data types I have the type of parameters as
typedef double DP;
typedef const NRVec<DP> Vec_I_DP; //NRVec is a parametrized template class.
typedef NRVec<DP> Vec_DP, Vec_O_DP, Vec_IO_DP;

xa -> Vec_I_DP(30)
ya -> Vec_I_DP(30)
yp1 -> DP(30)
ypn -> DP(30)
y2 -> Vec_O_DP(30)

My function call is
NR::spline(xa,          ya,          yp1,          ypn,         y2);

And the function declaration is
void spline(Vec_I_DP &x, Vec_I_DP &y, const DP yp1, const DP ypn,Vec_O_DP &y2);

Can somebody tell me, why I get the following error.
1>Hiwi.obj : error LNK2019: unresolved external symbol "void __cdecl NR::spline(class NRVec<double> const &,class NRVec<double> const &,double,double,class NRVec<double> &)" (?spline@NR@@YAXABV?$NRVec@N@@0NNAAV2@@Z) referenced in function "void __cdecl smooth_Line(double *,int *,int,int,double *,double *,int,int)" (?smooth_disp_Line@@YAXPANPAHHH00HH@Z)

A: It seems you are using NR2. The newest version is NR3 which defines spline in a class called Spline_interp. You should use NR3. For this matter, I will show you an example for using the aforementioned class. Let's say you have five values for sin(x) and you can to interpolate these values and acquire the interpolated values, say sin(x=.25). In this example, we know true value, therefore, we can compare the result with the interpolated value. In the following code, I got the interpolated value plus the error.
#include <iostream>
#include <iomanip>
#include "nr3.h"
#include "interp_1d.h"

int main() {
    VecDoub x(5), y(5);

    //x = 0:0.3:1
    //y = sin(x)

    x[0] = 0.0;
    x[1] = 0.3;
    x[2] = 0.6;
    x[3] = 0.9;

    y[0] = 0.0;
    y[1] = 0.2955;
    y[2] = 0.5646;
    y[3] = 0.7833;

    /**************************************************
        3.3 Cubic Spline Interpolation
        page(120)
    ***************************************************/

    Spline_interp myfunc3(x,y);
    std::cout << "Cubic Spline Interpolation: " << std::endl;
    std::cout << "interp value: " << myfunc3.interp(.25)  << "\n"
              << "  true value: " << sin(0.25)            << "\n"
              << "       error: " << ( ( sin(0.25) - myfunc3.interp(.25) )/sin(0.25) )*100.0  << "%" << std::endl;

    std::cout << std::setw(25) << std::cout.fill('=') << std::endl;

    return 0;
}

For compilation in Windows from the command prompt,
cl /EHsc main.cpp /Fetest.exe /I path\to\NR\code

The result is
Cubic Spline Interpolation:
interp value: 0.247187
  true value: 0.247404
       error: 0.0876794%
========================

The error is very small.


text:
Q: Pop after concatenate I have some large csv files which I imported. I extracted some specific columns to create new matrix only with those columns. I used concatenate in order to place the columns next to each other. Now I would like to divide this matrix into two smaller ones by extracting some rows from it. I don't know why I keep getting the error when using pop function on the concatenated data.
data_set=[annual_inc, delinq_2yrs, dti, emp_length, loan_amnt, installment, int_rate, open_acc, total_acc, pub_rec, acc_now_delinq, loan_stat]

result=pd.concat(data_set,axis=1)

def splitDataSet(x, splitRatio):
    trainSize  = int(len(x)*splitRatio)
    trainSet=[]
    copy=x
    while len(trainSet)<trainSize:
        index=random.randrange(len(copy))
        trainSet.append(copy.pop(index))
    return[trainSet, copy]

splitRatio=0.67
train, test=splitDataSet(result, splitRatio)
print(train)

When I use pop on data_set before it has been concatenated it works, but then it removes the respective column and it is not what I am looking for. For example after command
result.pop(0)

I get the error 'KeyError: 0' I would simply like to remove row '0' from the array result
PS: I omitted the lines from the beginning like imports and some variable preprocessing. If someone needs it, I can paste it.

A: copy=x doesn't really copy the list (x is a list, right?) but make copy to point to the same list as x. Of course, copy.pop() is equivalent to x.pop() which is not what you want.
To copy the list do copy = x[:].

A: Ok. I think I got this. Firstly i had to transform pandas array 'result' into list. In order to do this i used:
a=result.values.tolist()

then from this point a.pop() works fine.


text:
Q: Writing to S3 via Kinesis Stream or Firehose I have events that keep coming which I need to put to S3. I am trying to evaluate if I muse use Kinesis Stream or Firehose. I also want to wait for few minutes before writing to S3 so that the object is fairly full.
Based on my reading of Kinesis Data stream, I have to create an analytics app which will then be used to invoke a lambda. I will then have to use the lambda to write to S3. Or Kinesis Data Streams can directly write to lambda somehow? I could not find anything indicating the same.
Firehose is not charged by hour(while stream is). So is firehose a better option for me?

A:
Or Kinesis Data Streams can directly write to lambda somehow?

Data Streams can't write directly to S3. Instead Firehose can do this:

delivering real-time streaming data to destinations such as Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon Elasticsearch Service (Amazon ES), Splunk, and any custom HTTP endpoint or HTTP endpoints owned by supported third-party service providers, including Datadog, MongoDB, and New Relic.

What's more Firehose allows you to buffer the records before writing them to S3. The writing can happen based on buffer size or time. In addition to that you can process the records using lambda function before writing to S3.
Thus, colectively it seems that Firehose is more suited to your use-case then Data Streams.


text:
Q: Incrementally updating data on HDFS We are copying data from various sources such as Oracle, Teradata to HDFS using Sqoop.  We use incremental update feature to 'import' new data & then 'merge' it with the existing data.  Data first gets populated in a temporary directory & then we 'remove' the old & 'rename' the new one.
Problem is, if a user is running a query against the data on HDFS using a tool such as Hive while we swap the directory, the query terminates abnormally.
Is there a better way to handle the updates on HDFS?
(Please note, that even though HBase keeps different versions, it doesn't work for us because we want to query by any column.  HBase is very slow in cases where you don't search by primary key.)

A: Hadoop is not designed to work like that. It is good for storing data but not editing. I would just add new data beside old data and while adding it(copying or any other import) you could add sufix .tmp to filename. But i did not use hive that much(pig user here) and in pig i could tell A = LOAD '/some/path/to/hdfs/*.log' and that would load all files except .tmp which are importing. With that there is no problems.


text:
Q: Select the price in a jquery array and add to Total i a have a combo box where i can choose specific vehicle, each has engine size, name and price wrapped in an array.
If vehicle 1 chosen i want to add their price to the total amount.
Here is my code:
HTML
<select id="selector" onChange="Expedisi(this);">
            <option>Select product</option>
          <optgroup label="Sedan">
            <option value="Lancer EX">Lancer EX 1.6 / 2.0</option>
            <option value="Lancer EX GT">Lancer EX GT</option>
          <optgroup label="Sport">
            <option value="Lancer Evolution X">Lancer Evolution X</option>
          <optgroup label="SUV">
            <option value="Outlander">Outlander</option>
        </select>

JavaScript
var data = {
    "Lancer EX" : { img: "cars/mitsubishi/lancerex.png" , label: "Lancer EX " , engine: "1.6 L" , price :"16500" },
    "Lancer EX GT" : { img: "cars/mitsubishi/gt.png", label: "Lancer EX GT", engine: "2.0 L" , price: "22000"},
    "Lancer Evolution X" : { img: "cars/mitsubishi/evox.jpg", label: "Evolution X", engine:"2.0L Turbocharged", price: "85000" },
    "Outlander" : { img: "cars/mitsubishi/outlander.jpg", label: "Outlander", engine: "2.0 L" , price : "33000" },
};

I want to add the price of the chosen vehicle from the combo box to the Total which is 0 at first.
Thank you.

A: You can access the correct vehicle in your object by using the selected value as the property name.
Example:
data[$(this).val()].price

var data = {
    "Lancer EX" : { img: "cars/mitsubishi/lancerex.png" , label: "Lancer EX " , engine: "1.6 L" , price :"16500" },
    "Lancer EX GT" : { img: "cars/mitsubishi/gt.png", label: "Lancer EX GT", engine: "2.0 L" , price: "22000"},
    "Lancer Evolution X" : { img: "cars/mitsubishi/evox.jpg", label: "Evolution X", engine:"2.0L Turbocharged", price: "85000" },
    "Outlander" : { img: "cars/mitsubishi/outlander.jpg", label: "Outlander", engine: "2.0 L" , price : "33000" },
};

var total = 0;

$('#selector').on('change', function() {
    total = data[$(this).val()].price;
    console.log(total);

    $('#thetotal').text("The total is: " + total);
})

<select id="selector">
  <option>Select product</option>
  <optgroup label="Sedan">
  <option value="Lancer EX">Lancer EX 1.6 / 2.0</option>
  <option value="Lancer EX GT">Lancer EX GT</option>
  <optgroup label="Sport">
  <option value="Lancer Evolution X">Lancer Evolution X</option>
  <optgroup label="SUV">
  <option value="Outlander">Outlander</option>
</select>

A: You can change your Expedisi function like below -
 var data = {
     "Lancer EX": {
         img: "cars/mitsubishi/lancerex.png",
         label: "Lancer EX ",
         engine: "1.6 L",
         price: "16500"
     },
     "Lancer EX GT": {
         img: "cars/mitsubishi/gt.png",
         label: "Lancer EX GT",
         engine: "2.0 L",
         price: "22000"
     },
     "Lancer Evolution X": {
         img: "cars/mitsubishi/evox.jpg",
         label: "Evolution X",
         engine: "2.0L Turbocharged",
         price: "85000"
     },
     "Outlander": {
         img: "cars/mitsubishi/outlander.jpg",
         label: "Outlander",
         engine: "2.0 L",
         price: "33000"
     },
 };

 function Expedisi(elem) {
     var total = 0;
     total += parseInt(data[elem.value].price, 10);
     console.log(total);

 }


text:
Q: Adding text to javascript items Is there a way for me to add text to sprites in Javascript so each can be given it's own number instead of having to edit the picture?
I'm working with a simple matching game described here. Currently to have the number shown, the image resource must be changed.
<!DOCTYPE html>
<html>
   <head>
     <title>BakerIce</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type ="text/javascript"
    src ="simpleGame.js"></script>
    <script type="text/javascript">

        var game;
        var iC;
        var iB;

        function cone() {
            TiC = new Sprite(game,"ICE-Cream-cone.png",150,150);
            TiC.setSpeed(0);
            TiC.setBoundAction(CONTINUE);
            TiC.setPosition(200,400);

            TiC.checkDrag = function(){
                if(TiC.isMouseDown()){
                    TiC.setX(document.mouseX);
                    TiC.setY(document.mouseY);
                }
            };
            return TiC;
        }
        function box(){
            TiB = new Sprite(game,"Ice-Cream-Box.png",200,200);
            TiB.setSpeed(0);
            TiB.setBoundAction(CONTINUE);
            TiB.setPosition(400,250);
            TiB.addText = function(text){
                var Text = text;
            };
            return TiB;
        }
        function init() {
            console.log("Begin Init");
            game = new Scene();

            iC = new cone();
            iC.checkDrag();
            iB = new box();
            iB.addText(1/2);
            game.setBG("orange");
            game.start();
            console.log("End Init");
        }
        function update() {
            // console.log("Begin Update");

            game.clear();
            iB.update();
            iC.update();
            iC.checkDrag();

            // console.log("End Update");
        }

    </script>

</head>
<body onload = "init()">

</body>


text:
Q: Backspace in python 3x Following python code is not giving me a backspace as it's supposed to.
var=('hel\b')
print(var)

Outputs:
hel
>>>

But setting terminal character as nothing works as expected.
var=('hel\b')
print(var,end='')

Outputs:
he>>>

In following example.
var=('hello\b\b \b')
print(var)

Outputs:
hel o
>>>

What exactly is happening here ?
Am coding in Python 3.5 in Notepad++. Os is Windows 7, 32-bit.

A: The backspace character \b only moves the cursor one character backwards, but never deletes or overwrites anything.
In your second example, you should be able to observe it precisely: the Python prompt >>> has overwritten the last character, l.
If you had written print('hel', end=''), you would have seen:
hel>>>

The \b character shifted the cursor one character backwards, which made the prompt started printing at l, instead of after l.
If you want it to erase a character, fill it with a space, then backshift again:
>>> print('hel\b \b')
he
>>>


text:
Q: Discrepancy between Matlab and Mathematica What is the difference between how Matlab and Mathematica solve State-Space and Transfer Function models?
I have a $16 \times 16$ state space system for which I am calculating transfer function. Mathematica and Matlab give me completely different answers. I can imagine truncation may lead to slightly different answers but what I get is a huge difference. I have checked the difference in numerical values to check the conditioning. There is no significant difference. I give the matrix as seen in Mathematica to you to check.
Please find the code attached!
a={{-(350103/48500), -14.9811, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0}, {1.75898, -6.08528, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0}, {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {12.4114, -32.0709, 310.284,
0, -19.63, -102.059, -310.284, 77.9757, 0, 0, 0, 0, 0, 0, 0,
0}, {2.21387, -5.72064, 55.3468, 0, -0.454893, -21.6178, -55.3468,
13.9089, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0}, {1, -2.584, 25, 0, -1, -7.016, -25, 0, 0, 0, 0, 0,
0, 0, 0, 0}, {0, 0, 0, 0, 12.4114, -32.0709, 310.284,
0, -19.63, -102.059, -310.284, 77.9757, 0, 0, 0, 0}, {0, 0, 0, 0,
2.21387, -5.72064, 55.3468, 0, -0.454893, -21.6178, -55.3468,
13.9089, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0}, {0, 0, 0, 0, 1, -2.584, 25, 0, -1, -7.016, -25, 0, 0, 0, 0,
0}, {0, 0, 0, 0, 0, 0, 0, 0, 12.4114, -32.0709, 310.284,
0, -19.63, -102.059, -310.284, 77.9757}, {0, 0, 0, 0, 0, 0, 0, 0,
2.21387, -5.72064, 55.3468, 0, -0.454893, -21.6178, -55.3468,
13.9089}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, {0, 0,
0, 0, 0, 0, 0, 0, 1, -2.584, 25, 0, -1, -7.016, -25, 0}};

b={{116319/1940}, {10.695}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0},
{0}, {0}, {0}, {0}, {0}, {0}};

c={{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1}};

sys = StateSpaceModel[{a,b,c}]

BodePlot[sys, {2 \[Pi] 0.01, 2 \[Pi] 100},
ScalingFunctions -> {{Automatic, Automatic}, {Automatic, "Degree"}},
PhaseRange -> {-\[Pi], \[Pi]}, GridLines -> Automatic, ImageSize ->Large]

Corresponding Matlab code with the same set of matrices:
[num,den] = ss2tf(a,b,c,[0;0;0]);

P1 = tf(num(1,:),den);
P2 = tf(num(2,:),den);
P3 = tf(num(3,:),den);

figure; bode(P1,P2,P3);

The transfer function that I can from Matlab and Mathematica are completely different in nature. I am pretty sure that according to theory Matlab gives me the right answer. But why is Mathematica so off the mark?
Could it be any of the following?

*

*Precision/truncation

*Size of the system

*Conditioning

Edit:
I have included the plots for both. Left is Mathematica and right is Matlab. The colors correspond to each other. Please take note of the Magnitude scale for both!

Any insight would be appreciated!

A: Using Mathematica 10.4.1 (Windows 7) the following code finds a pretty good match with the Matlab results.  (And I'd argue that any differences between the two are due to differences in how the precision of the input numbers are handled.)
a = Rationalize[a, 0.00001];
b = Rationalize[b];

sys = StateSpaceModel[{a, b, c, d}];

BodePlot[sys, {2 π 0.01, 2 π 100},
 ScalingFunctions -> {{Automatic, Automatic}, {Automatic, "Degree"}},
 PhaseRange -> {-π, π}, GridLines -> Automatic,
 ImageSize -> Large,
 PlotRange -> {{Full, {0, -400}}, {Full, {-180, 180}}},
 PlotStyle -> {Blue, Red, Green}]

A: In M11.3 this is much much easier to solve. Simply: use instead of d Automatic:
a = {{-(350103/48500), -14.9811, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0}, {1.75898, -6.08528, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0}, {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {12.4114, -32.0709, 310.284,
     0, -19.63, -102.059, -310.284, 77.9757, 0, 0, 0, 0, 0, 0, 0,
    0}, {2.21387, -5.72064, 55.3468, 0, -0.454893, -21.6178, -55.3468,
     13.9089, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0}, {1, -2.584, 25, 0, -1, -7.016, -25, 0, 0, 0, 0,
     0, 0, 0, 0, 0}, {0, 0, 0, 0, 12.4114, -32.0709, 310.284,
    0, -19.63, -102.059, -310.284, 77.9757, 0, 0, 0, 0}, {0, 0, 0, 0,
    2.21387, -5.72064, 55.3468, 0, -0.454893, -21.6178, -55.3468,
    13.9089, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
    0, 0}, {0, 0, 0, 0, 1, -2.584, 25, 0, -1, -7.016, -25, 0, 0, 0, 0,
     0}, {0, 0, 0, 0, 0, 0, 0, 0, 12.4114, -32.0709, 310.284,
    0, -19.63, -102.059, -310.284, 77.9757}, {0, 0, 0, 0, 0, 0, 0, 0,
    2.21387, -5.72064, 55.3468, 0, -0.454893, -21.6178, -55.3468,
    13.9089}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, {0, 0,
     0, 0, 0, 0, 0, 0, 1, -2.584, 25, 0, -1, -7.016, -25, 0}};

b = {{116319/
     1940}, {10.695}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, \
{0}, {0}, {0}, {0}, {0}};

c = {{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 1}};

a = Rationalize[a, 0.00001];
b = Rationalize[b];

sys = StateSpaceModel[{a, b, c, Automatic}]
BodePlot[sys, {2 \[Pi] 0.01, 2 \[Pi] 100},
 ScalingFunctions -> {{Automatic, Automatic}, {Automatic, "Degree"}},
 PhaseRange -> {-\[Pi], \[Pi]}, GridLines -> Automatic,
 ImageSize -> Large,
 PlotRange -> {{Full, {0, -400}}, {Full, {-180, 180}}},
 PlotStyle -> {Blue, Red, Green}]

Both MATLAB and Mathematica 11.3 provide the very same results.


text:
Q: Determining Documents folder redirection on Windows 8 In a desktop winforms application, I am using the Documents folder to store user data. Some users have redirected this folder to a server location. In Windows 7, I can successfully detect this using:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

In Windows 8 (specifically 8.1 Update 1), this results in a "\" response when the folder in redirected. It works correctly if it is not redirected.
I need to determine where this redirection is going to in order to access the user data.

A: The issue is actually related to rights.
Visual Studio is running as Administrator, if you run an admin command prompt and type in net use there are no mapped drives. A normal command prompt returns the mapped drives.
By enabling linked locations in the registry as per this article it now returns the value in Visual Studio.


text:
Q: How to use Mori's superpixels Matlab code on Windows How to use Mori's superpixels Matlab code (http://www.cs.sfu.ca/~mori/research/superpixels/)  on Windows?
i ran mex and downloaded the segbench.Readme file in segbench says
(1) For the image and segmentation reading routines in the Dataset
directory to work, make sure you edit Dataset/bsdsRoot.m to point to
your local copy of the BSDS dataset.
(2) Run 'gmake install' from this directory to build everything.  You
should then probably put the lib/matlab directory in your MATLAB path.
(3) Read the Benchmark/README file.
For the 1st step, I changed the path in bsdsRoot.m as C:\Users\rajan\Desktop\superpixels which have the file i want to segment.
For the 2nd step  I ran command gmake install in terminal and i got
C:\Users\rajan\Desktop\superpixels\segbench>gmake install
gmake[1]: Entering directory `c:/Users/rajan/Desktop/superpixels/segbench/Util'
GNUmakefile-library:26: * mexSuffix not defined.  Stop.
gmake[1]: Leaving directory `c:/Users/rajan/Desktop/superpixels/segbench/Util'

A: Slightly adapted the explanation given on the website.

*

*Run mex on each .c file in the yu_imncut directory

*Obtain mfm-pb boundary detector code from
http://www.cs.berkeley.edu/projects/vision/grouping/segbench/

*Change path names in sp_demo.m and pbWrapper.m

*Run sp_demo.m


text:
Q: html/css empty space at bottom of the website So I have a problem with empty space at bottom of the website. Here is website: click
Repo of website: https://github.com/bdevelops/feditor
I read questions on stack, tried to find solution, but nothing works.
Sorry for bad English, if it is.

A: In your CSS class .box is margin-top:30px or height:100%. This is what makes white space at the bottom of your website
box {
    background: #fff none repeat scroll 0 0;
    box-sizing: border-box;
    height: 100%; **//Set it to "auto"
    margin-top: 30px; **//or this one, change it to 0px or remove**
    overflow: hidden;
    width: 100%;
}


text:
Q: Nested aggregation binding and access parent properties I have this JSON data:
oDC = [
   {
      "DC_GROUP":"TEST_DC_GROUP",
      "COUNT":0,
      "MULTIPLE_DATA_COLLECT":"false",
      "USERREF":"UserBO:SEA1,EVERTN",
      "STATUS_OP":"IN_WORK",
      "STATUS_SS":"READY",
      "PARAMS":[
         {
            "PROMPT":"CAPTURE",
            "DATA_TYPE":"N",
            "visible":false
         },
         {
            "PROMPT":"DEFAULT TEXT",
            "DATA_TYPE":"T",
            "visible":true
         }
      ]
   }
]

Saved in a property called "dataCollection" in a model called "viewModel"
let oView = this.getView();
let oModel = oView.getModel("viewModel");
oModel.setProperty("/dataCollection", oDC);

And this is an extract of my XML View
<IconTabBar id="IconTabBarDC" items="{viewModel>/dataCollection}" class="sapUiResponsiveContentPadding">
    <items>
        <IconTabFilter text="{viewModel>DC_GROUP}" key="{viewModel>DC_GROUP}">
            <Title
                text="{viewModel>DC_GROUP}"
                wrapping="true"
                titleStyle="H4"
                level="H4"
                class="sapUiSmallMarginBottom"/>
            <List
                id="idDataCollect"
                width="40%"
                mode="None"
                updateFinished="handleConstraints"
                headerText=""
                items="{path: 'viewModel>PARAMS', templateShareable:false}">
                <items>
                    <CustomListItem visible="{viewModel>visible}">
                        <HBox
                            alignItems="Center"
                            justifyContent="SpaceBetween"
                            class="sapUiTinyMargin">
                            <Label text="{viewModel>PROMPT}" wrapping="true"/>
                            <Input
                                type="Number"
                                enabled="{
                                    parts: [
                                        { path: 'viewModel>/STATUS_OP' },
                                        { path: 'viewModel>/COUNT' },
                                        { path: 'viewModel>/MULTIPLE_DATA_COLLECT' },
                                        { path: 'viewModel>/STATUS_SS' }
                                    ],
                                    formatter: '.formatter.isDCParamEnabled'
                                }"
                                required="{viewModel>visible}"
                                change=".changeNumParam"/>
                        </HBox>
                    </CustomListItem>
                </items>
            </List>
        </IconTabFilter>
    </items>
</IconTabBar>

My issue is that the in inner aggregation (PARAMS) I cannot access the fields from the outer aggregation (/dataCollection).
I tried in all these formats, with no success:
'viewModel>STATUS_OP'
'viewModel>/STATUS_OP'
'viewModel>dataCollection/STATUS_OP'
'viewModel>/dataCollection/STATUS_OP'

The fields inside PARAMS work fine
for example {viewModel>PROMPT}

A: dataCollection is an array. PARAMS is also an array.
Your first IconTabbarFilter is dataCollection/0/.
Your first CustomListItem is dataCollection/0/PARAMS/0.
The problem is that you need the dataCollection index in your PARAMS array to know which element you are in. You have to modify your dataCollection with a script like this:

var oDC = [{
  "DC_GROUP": "TEST_DC_GROUP",
  "COUNT": 0,
  "MULTIPLE_DATA_COLLECT": "false",
  "USERREF": "UserBO:SEA1,EVERTN",
  "STATUS_OP": "IN_WORK",
  "STATUS_SS": "READY",
  "PARAMS": [{
      "PROMPT": "CAPTURE",
      "DATA_TYPE": "N",
      "visible": false
    },
    {
      "PROMPT": "DEFAULT TEXT",
      "DATA_TYPE": "T",
      "visible": true
    }
  ]
}];

var aTransferProperties = ["MULTIPLE_DATA_COLLECT", "STATUS_SS", "STATUS_OP", "COUNT"];

for(var i = 0; i < oDC.length; i++){ //Loop oDC array with objects
  for(key in oDC[i]){ //Loop oDC array object properties
    if (aTransferProperties.indexOf(key) > -1) { //if the key is needed in child

       for(var j = 0; j <  oDC[i].PARAMS.length; j++){ //Loop PARAMS
             oDC[i].PARAMS[j][key] = oDC[i][key]; //insert key/value from parent in every child
           }
           delete oDC[i][key]; //optional Delete the key/value from parent
        }
   }
}

console.log(oDC);


text:
Q: MLE of $f(x\vert\theta)=1/\theta$, $x_1 , \cdots , x_n \sim U(0,\theta) \;\;, \theta>0$, Original question
$x_1 , \cdots , x_n$ are independent random variables, identically distributed as
a uniform distribution over $(0,\theta)$.
$$
f(x \vert \theta) = \frac{1}{\theta}, \; 0<x<\theta, \;\; \theta >0
$$
What's the Maximum Likelihood Estimator for $\theta$.
Comment on strict inequalities
(from olooney, edited slightly)
The MLE does not exist if we use strict inequality. But
$x_i \sim U(0, \theta)$ has various definitions but makes the intent clear: to model the data as a uniform distribution. For a continuous p.d.f. any finite number of points has measure 0 and can be added or removed and the answer is "almost surely" (jargon for "with probability 1") the same.
Why not use a definition of the U which makes the MLE problem tractable and which is almost surely the same?
Note that the question has strict inequalities, not weak
This is highlighted in this answer
Other similar posts to this
Though I searched others have highlighted other posts of a similar nature :
MLE for Uniform $(0,\theta)$
How do you differentiate the likelihood function for the uniform distribution in finding the M.L.E.?

A: The p.d.f for one $x_i$ is given as
$$
f(x| \theta) = \begin{cases}
     \frac{1}{\theta} & & \text{if } 0 \leq x \leq \theta \\
     0 & & \text{otherwise}
\end{cases}
$$
Let's call $\vec{x} = (x_1, ..., x_n)$.
The $n$ observations are i.i.d. so the likelihood of observing the $n$-vector $\vec{x} = (x_1, ... x_n)$ is the product of the component-wise probabilities. Ignoring the issue of support for the moment, note that this product can be simply written as a power:
$$
f(\vec{x}| \theta) =  \prod_i^n \frac{1}{\theta} = \frac{1}{\theta^n} = \theta^{-n}
$$
Next, we turn our attention to the support of this function. If any single component is outside its interval of support $(0, 1/\theta)$, then its contribution to this equation is a 0 factor, so the product of the whole will be zero. Therefore $f(\vec{x})$ only has support when all components are inside $(0, 1/\theta)$.
$$
f(\vec{x}| \theta) = \begin{cases}
  \theta^{-n} & & \text{if } \forall i, \ 0 \leq x_i \leq \theta \\
  0 & & \text{otherwise}
\end{cases}
$$
By definition, this is also our likelihood:
$$
\mathcal{L}(\theta; \vec{x}) = f(\vec{x}| \theta) = \begin{cases}
  \theta^{-n} & & \text{if } \forall i, \ 0 \leq x_i \leq \theta \\
  0 & & \text{otherwise}
\end{cases}
$$
The MLE problem is to maximize $\mathcal{L}$ with respect to $\theta$. But because $\theta > 0$ (given in the title of the problem) then $\theta^{-n} > 0$ therefore 0 will never be the maximum. Thus, this is a constrained optimization problem:
$$
\hat{\theta} = \text{argmin}_\theta \,\, \theta^{-n} \text{ s.t. } \forall i \,\, 0 \leq x_i \leq \theta
$$
This is easy to solve as a special case so we don't need to talk about the simplex method but can present a more elementary argument. Let $t = \text{max} \,\, \{x_1,...,x_n\}$. Suppose we have a candidate solution $\theta_1 = t - \epsilon$. Then let $\theta_2 = t - \epsilon/2$. Clearly both $\theta_1$ and $\theta_2$ are on the interior of the feasible region. Furthermore we have $\theta_2 > \theta_1 \implies \theta_2^{-n} < \theta_2^{-n}$. Therefore $\theta_1$ is not at the minimum. We conclude that the minimum cannot be at any interior point and in particular must not be strictly less than $t$. Yet $t$ itself is in the feasible region, so it must be the minimum. Therefore,
$$\hat{\theta} = \text{max} \,\, \{x_1,..., x_n\}$$
is the maximum likelihood estimator.
Note that if any observed $x_i$ is less than 0, then $\mathcal{L}$ is a constant 0 and the optimization problem has no unique solution.

A: Let us first consider the case when the question is read as stated. This is the approach I would recommend if asked this question when, say, taking a class in introductory theoretical statistics. Toy examples like this are commonly assigned as homework problems or on exams in such classes.
You can show (do it) that the likelihood function is
$$
 L(\theta) = \begin{cases} \theta^{-n} & \theta > x_{(n)} \\ 0 & \theta \leq x_{(n)}\end{cases},
$$
where $x_{(n)} = \max(x_1, \dots, x_n)$. The maximum likelihood estimate (MLE), if it exists, is the $\theta \in (0, \infty)$ that maximizes $L(\theta)$. In this case, since the inequality $\theta > x_{(n)}$ is strict, the MLE does not exist. Indeed, for any $\theta' > x_{(n)}$, the likelihood can always be increased by moving slightly to the left. However, you cannot pick as your MLE $\hat{\theta} = x_{(n)}$ since $L(x_{(n)}) = 0$. Clearly, no points to the left of $x_{(n)}$ can be the MLE either since the likelihood vanishes there.
Now let us also deal with the case where the question is interpreted differently. If you are free to pick which density for the $U(0, \theta)$ distribution to consider, i.e. you do not have to use the one given in the question, then it makes sense to pick the the density $f(x\mid \theta) = \theta^{-1}$, $0 \leq x \leq \theta$, instead. Recall, (Lebesgue) densities are only unique up to changes on sets of Lebesgue measure zero, so this is a density for the same distribution. With this density, the MLE exists and is equal to $\hat{\theta} = x_{(n)}$ which is easy to prove by noting that the likelihood is strictly decreasing on $[x_{(n)}, \infty)$.

A: As already discussed in the answer by Anon Ymous, the discussion on whether or not using the strict inequality is not pertinent from a measure theoretic point of view: the definition of a $\mathcal U$$(0,1)$ distribution is one of a probability measure against the Lebesgue measure on $\mathbb R$ that gives any open interval within $[0,1]$ a probability proportional to its length:$$\mathbb{P}_\theta[U\in(a,b)]\propto b-a$$
This distribution being absolutely continuous wrt the Lebesgue measure, it enjoys a density$\frac{\text{d}\mathbb{P}_\theta}{\text{d}\lambda}$ that is constant almost everywhere on $[0,\theta]$. Hence
$$f_\theta(x)=\frac{1}{\theta}\mathbb I_{(0,\theta)}(x)\quad\text{and}\quad f_\theta(x)=\frac{1}{\theta}\mathbb I_{[0,\theta]}(x)$$
are two equivalent versions of the density of the same distribution. In such instances, the MLE will exist for some versions and not for others, which requires the selection of a smooth version of the density and hence of the likelihood function that allows for a solution. This is obviously a drawback of the MLE approach. (A similar difficulty arises with the Bayesian MAP which further depends on the definition of the dominating measure over the parameter space.)


text:
Q: Determine quicktime version with C# I am writing a C# application and I need to determine if quicktime is installed on the system and what version.
This is on windows.

A: A quick Google search turned up the following code from this page:
strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery _
    ("Select * From Win32_Product Where Name = 'QuickTime'")

If colItems.Count = 0 Then
    Wscript.Echo "QuickTime is not installed on this computer."
Else
    For Each objItem in colItems
        Wscript.Echo "QuickTime version: " & objItem.Version
    Next
End If

"But wait!" you say, "That's VBScript, not C#!" That's true, but it's VBScript that does WMI queries. Another quick Google search turns up how to do WMI queries from C#.

A: Try this:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"))
{
    if (key != null)
    {
        foreach (string subKeyName in key.GetSubKeyNames())
        {
            using (RegistryKey subKey = key.OpenSubKey(subKeyName))
            {
                if (subKey == null) continue;

                var displayName = subKey.GetValue("DisplayName") as string;

                if (displayName == null || !displayName.Equals("QuickTime")) continue;

                var version = subKey.GetValue("DisplayVersion");

                Console.WriteLine(displayName);
                Console.WriteLine(version);
            }
        }
    }
}


text:
Q: Modules registration in Prism 7.1 In Prism 7.1, the IModule interface has changed from version 6.3, and now exposes the two methods RegisterTypes (IContainerRegistry containerRegistry) and OnInitialized (IContainerProvider containerProvider). I ask forgiveness, but I cannot understand how I have to register the Views implemented in the Module. it's probably so simple that I can not see the solution to the problem. Can you give me an example to finally make me understand how I should do? Wherever I looked, I found only examples regarding version 6.3, which I know rather well ..

A: Prism 7.X introduces an abstraction around the DI Container. There were a number of reasons for this but the top two are:

*

*Many of the support questions from the community to the Prism team revolved around how to do something with a container that has nothing to do with the Prism team.

*By abstracting the container it makes scenarios around sharing code and swapping out containers easier.

It's also important to understand that by abstracting the Container we've also made changes to the Container Extensions responsible for registering Views. Specifically we now have them on the IContainerRegistry. So given the sample Prism 6.X Module here:
public class ModuleA
{
    private IUnityContainer _container { get; }

    public ModuleA(IUnityContainer container)
    {
        _container = container;
    }

    public void Initialize()
    {
        // register stuff
        _container.RegisterViewForNavigation<ViewA>();

        // Setup Event listeners etc...
        var ea = _container.Resolve<IEventAggregator>();
    }
}

We would update this to:
public class ModuleA
{
    public void OnInitialized(IContainerProvider containerProvider)
    {
        // Setup Event listeners etc...
        var ea = containerProvider.Resolve<IEventAggregator>();
    }

    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        // register stuff
        containerRegistry.RegisterForNavigation<ViewA>();
    }
}

A:
it's probably so simple that I can not see the solution to the problem

Just use RegisterTypes - registering a view is registering a type, after all.


text:
Q: Email Validation using Regular Expressions Pandas Dataframe I would like to do a simple email validation for list import of email addresses into a database. I just want to make sure that there is content before the @ sign, an @ sign, content after the @ sign, and 2+ characters after the '.'  . Here is a sample df:
import pandas as pd
import re

errors= {}

data= {'First Name': ['Sally', 'Bob', 'Sue', 'Tom', 'Will'],
     'Last Name': ['William', '', 'Wright', 'Smith','Thomas'],
     'Email Address': ['sally@gmail.co.uk','bobby123@gmail.com','suewright_123@yahoo.gov','tom.smith23@students.wacs.fl.us','']}
df=pd.DataFrame(data)

This is the expression I was using to check for valid emails:
regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')
def isValid(email):
    if re.fullmatch(regex, email):
      pass
    else:
      return("Invalid email")

This regex is working fine but I am not sure how to easily loop through my entire df email address column. I have tried:
for col in df['Email Address'].columns:
   for i in df['Email Address'].index:
      if df.loc[i,col] = 'Invalid email'
           errors={'row':i, 'column':col, 'message': 'this is not a valid email address'

I am wanting to write the invalid email to a dictionary titled errors. with the above code I get an invalid error.

A: The beautiful thing about Pandas dataframes is that you almost never have to loop through them--and avoiding loops will increase your speed significantly.
df['Email Address'].str.contains(regex) will return a boolean Series of whether each observation in the Email Address column.
Check out this chapter on vectorized string operations for more.

A: According to your description, I'd probably do
df["Email Address"].str.match(r"^.+@.+\..{2,}$")

str.match returns True if the regex matches the string.
The regex is

*

*the start of the string ^

*content before the @ sign .+

*an @ sign @

*content after the @ sign .+

*a dot \.

*and 2+ characters after the '.' .{2,}

A: You can iterate through rows using .iterrows() on a dataframe. row contains a series and you can access your column the same way you would a dictionary.
for i, row in df.iterrows():
    if not isValid(row['Email Address']):
        print("Invalid email")


text:
Q: Выбор платформы PHP или Java? Выбираем, пробуем разные платформы для разработки web-приложения (тонкий клиент, важно для платформ iOS), у которого должна быть кросс платформенная оффлайн версия. Запутался уже совсем, думал на Java писать, похоже, для нашего несложного приложения вполне подходит PHP (его и изучать проще), на PHP реализовано немало проектов и такие высоконагружные как ВКонтакте.
Главная сложность нашего проекта состоит в том, что онлайн и оффлайн версии должны иметь один код и один интерфейс (чтобы не пришлось их отдельно писать).
Решение видим следующие:

*

*Писать десктопное Java приложение и развертывать его на сервере.
Для запуска настольной версии на Windows, Linux, (Mac OS?) нужно только JVM установить.
На сервере можно как апплет или JWS оформить (вопрос относительно тонкого клиента придется решать?).

*Писать web-приложение на JavaEE, работающее на GlassFish например.
Настольную версию предлагается делать следующим образом: запускать локальный сервер GlassFish, на котором выполняется наше приложение. Похож на какой-то кустарный метод? Вопрос удобства для пользователя - установка и настройка сервера, возможные подводные камни?

*Писать на PHP.
Схож с пунктом 2, с серверами только вроде попроще?

Вопрос бредовый, тем не менее хотелось бы узнать ваши комментарии, какие еще есть варианты?
Предыдущие темы:
Язык программирования для Web-приложений
Развертывание приложений Java на сервере
Оффлайн запуск web-приложений

A: Дополню ответ @ArtFeel. Adobe Flex + AIR в вашем случае, возможно, единственное разумное и доступное решение. Ниже делюсь личным опытом разработки решения с аналогичными требованиями.
Вы получите из одного и того же кода практически:

*

*Десктопный клиент (AIR).

*Клиент для браузера (Flash).

*Клиент для коммуникаторов (Flash).

Но будут определенные ограничения архитектурного плана.
Web-сервис в данном случае можно будет писать на чем угодно - его задачей будет только прием и возврат данных, вполне сойдет и PHP, если есть ограничения по времени на освоение технологий. Лично я бы выбирал между REST-службой на Java (Jersey) и REST-службой на Ruby (Ruby On Rails), оба варианта позволят быстро и просто сделать сервис для выполнения CRUD операций, HTTPS на Java поднимается за 5 минут. В качестве транспорта данных -  просто XML или JSON (я бы выбрал второй).
Клиент будет "толстым" - вся логика приложения должна быть сосредоточена в нем. Кроме того, в клиенте организуете абстрактный слой доступа к данным, через который приложение будет читать-писать. Для конкретных источников данных пишите соответствующие реализации: для связи с web-сервисом, для локального desktop-хранилища, для локального хранилища на мобильных платформах. В зависимости от внешних условий (с какой платформы запущено и есть ли связь с сервером) приложение включает конкретную реализацию слоя доступа к данным.
A: Посмотрите на Adobe Air, он позволит написать кросплатформенное приложение не только на все десктоп платформы, но и на iOS, и веб часть на флеше.


text:
Q: Array class not rendering into datagrid The following application is not rendering the information  that I am getting back from a web service into the datagrid. I know I am being able to connect to the webservice because I am getting the count for the class array. I am being able to get a Response.Write but when I try to pull all the information from the array class I haven't been able to see the elements nor to render the whole class into the data grid. What might be my issue? I am stuck with this one.
void LoadABCPhoneInfo()
{

    PhoneTypeInfo[] PhoneInfo = GetPhoneInfo();

    DataSet quoteDataSet = XmlString2DataSet(PhoneInfo.ToString());

    //Here is NOT doing the databinding.
    grdABC.DataSource = quoteDataSet;
    grdABC.DataBind();
    grdABC.Visible = true;
}

private PhoneTypeInfo[] GetPhoneInfo()
{
    //string strGetPhoneInfo = String.Empty;
    PhoneTypeInfo[] strGetPhoneInfo; //

    try
    {
        OwnerAndReservation ownerAndReservationWS = new OwnerAndReservation();

        strGetPhoneInfo = ownerAndReservationWS.GetPhoneTypes();
        //GetPhoneTypesAsync()
        //Here I can get the count for the array
        Response.Write("GetPhoneInfo Length "+ strGetPhoneInfo);
    }
    catch (Exception ex)
    {
        //raise the error
        string errorMessage = String.Format("Error while trying to connect to the Web Service. {0}", ex.Message);
        throw new Exception(errorMessage);

    }
    //return the quote information
    return strGetPhoneInfo;
}

private DataSet XmlString2DataSet(string xmlString)
{
    //create a new DataSet that will hold our values
    DataSet quoteDataSet = null;

    //check if the xmlString is not blank
    if (String.IsNullOrEmpty(xmlString))
    {
        //stop the processing
        return quoteDataSet;

    }

    try
    {
        //create a StringReader object to read our xml string
        using (StringReader stringReader = new StringReader(xmlString))
        {
            //initialize our DataSet
            quoteDataSet = new DataSet();

            //load the StringReader to our DataSet
            quoteDataSet.ReadXml(stringReader);
        }
    }
    catch
    {
        //return null
        quoteDataSet = null;
    }

    //return the DataSet containing the stock information
    return quoteDataSet;
}


text:
Q: Symfony Change render login FosUserBundle I use this in my navbar on my web site
{{ render(controller('FOSUserBundle:Security:login')) }}

And i put the login form in my navbar where my login work when i put the correct data into.. my problem come when the data is incorrect because the render redirect me on the login.html.twig page for say me the error message.
I think my problem is in this lines
     protected function renderLogin(array $data)
       {
      return $this->render('FOSUserBundle:Security:login.html.twig', $data);
    }

I try to change this, with the initial page or the directory of navbar but is not the good way..
How can i do??? I want the error message in the index and I do not want to redirect the login page..

A: I personally had this problem; You can either override the login function of FOS, and handle the error when there's any, or do as i did, and create an ajax call for the login, and handle it yourself


text:
Q: How to add a view in image editor of adobe creative sdk? I want to add a banner below the tools in the image editor component of adobe creative sdk.
I have searched online but it seems they only let you customize of the options of the image editor like colors and values etc.
If anyone here know any way to do it please let me know
THanks Guys

A: This isn't currently possible via the Creative SDK APIs.
Altering the Image Editor UI beyond the scope of what the Creative SDK APIs make possible isn't allowed, and apps doing so won't be approved for Production IDs.
You can read more about Creative SDK app submission guidelines on the Creative SDK developer portal.


text:
Q: How to explicitly refer to the current uncommited state of a repo in a git diff When you run git diff or git diff <some commit> you're implicitly diffing the current state of the repo (whether staged or unstaged) implicitly against HEAD implicitly in the first case or whatever commit is specified in the latter case.
My question is: how do I explicitly refer to the current state of the repo?
Ideally, I'd like to be calling something like git diff CURRENT_STATE HEAD.

A:
how do I explicitly refer to the current state of the [work tree]?

git diff is already an explicit reference to that, Git compares against the current state of the work tree unless you override it and tell it to compare against content somewhere else instead, but if you're after a further override like --no-cached to override any earlier --cached override, that, git diff doesn't have at the moment, you'll have to write a little options preprocessor to strip out anything you don't like rather than just tacking the override on the end.
edit:

Ideally, I'd like to be calling something like git diff CURRENT_STATE HEAD

You can get this effect with -R, a reverse diff that swaps the usual order. You'd do that specific diff with just git diff -R HEAD (I much prefer the @ synonym for HEAD, git diff -R @).

A: jthill's answer is fine; I just want to address this comment directly, with much more detail and formatting than will fit into a comment:

Basically, I'm asking: Does the uncommitted state of the repo explicitly have its own ref?

The short answer is "no".
A ref, like HEAD or master or (fully spelled out) refs/heads/master, ultimately resolves to a hash ID.1  If it's a branch name or remote-tracking name, it resolves specifically to a commit hash ID; if it's a tag name, it may resolve to any of Git's four internal object types: commit, tree, blob, or (annotated) tag.
A tree object is the closest thing you can get to the work-tree, but it's not the work-tree at all.  In fact, there are two uncommitted representations, in a normal Git repository, that you cannot refer to by name.  One of these is the stuff that is in the index—essentially, the proposed next commit—and the other is the stuff in the work-tree.
If the index is in a good state,2 you can run git write-tree.  The result is a hash ID.  This is not a reference name at all, it's just a hash ID, but a hash ID is usually just as good.  So if you'd like some Git command to take notice of the proposed next commit, you can run git write-tree to write it to a tree object, and then use the resulting hash ID.
The work-tree, however, isn't at all suitable for this.  To turn the work-tree into a hash ID, you need to write it to the—or at least an—index and then run git write-tree.  You can use the environment variable GIT_INDEX_FILE to name a temporary file that will hold a temporary index.
The git diff and git status commands have built-in tricks to use the index and work-tree as if they were commits, but most other Git commands don't.

1If the ref is symbolic—as HEAD usually is—it just contains the name of another ref.  If that other ref doesn't actually exist, the symbolic ref won't resolve to a hash ID at all, and git rev-parse will fail on it, but git symbolic-ref will let you examine the target.
2The index can be in the merge conflict state, in which it can't be converted into a tree object. In this case git write-tree just errors out.  Unfortunately, there is no good way to deal with this other than just to resolve the merge conflicts.  I say "unfortunately" because it would sometimes be very handy to stash (as if by git stash or some such) the conflicted state for safekeeping and/or transport, and the way Git is today, that's simply not possible.  You can get pretty close, using git ls-files --stage to translate the index into text and git update-index to invert that, but protecting temporary blob hashes from GC is a problem.

A: you can specify two commits to git diff:
git diff [--options] <commit> <commit> [--] [<path>...]
   This is to view the changes between two arbitrary <commit>.

Please write:
git help diff

For more options.
Good luck!


text:
Q: How to hide the title of the product on Woocommerce widget "Recently Viewed" I love this widget, but I only need the image of the product, not the name. I attached a picture to show what I mean, I only want that the widget to show the image of the product. enter image description here

A: select its class and add display : none ;


text:
Q: Spring javax.validation problem In my application with spring framework, I have this import which it couldn't find
 import javax.validation.Valid;

Thing is I already have that javax.jar in the classpath. So my question is is there a different version of javax.jar that has validation package or I need any other jar files?
   I couldn't find any javax.jar that has validation package on the internet. So please give me a link if you know any. Thanks in advance!

A: You're looking for javax.validation:validation-api.
Also, as Amir mentioned, if you've found stackoverflow useful, accept some answers. People will be more inclined to help out.

A: javax.validation.* is part of jsr-303 which needs to be downloaded separately here.

A: If you are using maven, just add the external dependency in your pom.xml
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

Verify the latest version here: https://mvnrepository.com/artifact/javax.validation/validation-api