text:
Q: How to speed up index based assignment? I have a problem where the idea is to find unique elements of an extremely large matrix, apply some function (in this example, it is a sine function, but it can be an arbitrary function, even a trained neural net) to each unique element, and then replace it back in the original matrix.
I have the following R code snippet:
nrows <- 28000
ncols <- 3000

x <- matrix(round(runif(nrows*ncols, 1, 5), 5), nrow=nrows, ncol=ncols)

u <- unique(as.vector(x))
uindex <- seq(from=1, to=length(u), by=1)
ut <- sin(u)

for (hh in uindex) {
  x[x == u[hh]] <- ut[hh]
}

In the above, code-snippet, the portion
for (hh in uindex) {
  x[x == u[hh]] <- ut[hh]
}

takes forever to finish for the matrix dimension of order 1e4x1e3. How can I optimize the for loop?
Please note that this is just a minimal working example for Stackoverflow only. Hence, please refrain from telling me that I can do x = sin(x). My point is the for loop.

A: To expand on my comment regarding avoiding the for loop entirely...
As OP knows, using loops in R is generally slow and if there's an alternative, it's likely to be faster.  One answer that avoids the for loop has already been provided.  Here is another, with benchmarking.
To start, turn the OP's code into a function.
withForLoop <- function(nrows=28000, ncols=3000) {
  x <- matrix(round(runif(nrows*ncols, 1, 5), 5), nrow=nrows, ncol=ncols)
  u <- unique(as.vector(x))
  uindex <- seq(from=1, to=length(u), by=1)
  ut <- sin(u)
  for (hh in uindex) {
    x[x == u[hh]] <- ut[hh]
  }
}

and benchmark it
library(microbenchmark)
microbenchmark(withForLoop, times=100)

Unit: nanoseconds
        expr min lq  mean median uq  max neval
 withForLoop  47 49 83.46     49 55 3226   100

So we are trying to beat a median time of 49 nanoseconds.  (You could, of course, pick any other summary statistic as your target metric.)
Now rewrite the code using the tidyverse.  OP's code starts with a matrix, converts it to a vector and then manipulates the vector.  It's not clear if the matrix needs to be recovered.  Assume it does, so provide the means to recover it, but - for consistency with OP's code - don't do the recovery.
library(tidyverse)

withTidyverse <- function(nrows=28000, ncols=3000) {
  x <- tibble() %>%
         expand(
           Row=1:nrows,
           Col=1:ncols
         ) %>%
         mutate(
           Random=round(runif(nrow(.), 1, 5), 5),
           Sin=sin(Random)
         )
}

microbenchmark(withTidyverse, times=100)

Unit: nanoseconds
           expr min lq  mean median uq max neval
 withTidyverse1  41 42 52.21   42.5 43 964   100

So that's reduced the median execution time to 42.5 nanoseconds on my machine.  That's a saving of just over 13%.
Because sin is a relatively quick function I've not bothered to search for unique values and replace each unique value in a batch.  I've just taken a blunderbuss approach and recalculated each value in the vector as it arises.  Here's a way of taking the more sophisticated, "replace unique values in batches" approach:
withTidyverse2 <- function(nrows=28000, ncols=3000) {
  x <- tibble() %>%
    expand(
      Row=1:nrows,
      Col=1:ncols
    ) %>%
    mutate(
      Random=round(runif(nrow(.), 1, 5), 5)
    )
  y <- x %>%
         distinct(Random) %>%
         mutate(Sin=sin(Random))
  x <- x %>%
         left_join(y, by="Random")
}

microbenchmark(withTidyverse2, times=100)

Unit: nanoseconds
           expr min lq  mean median uq  max neval
 withTidyverse2  44 45 82.31   45.5 51 2543   100

So, in this specific case, the overhead of extracting the unique values and updating in batches is not worthwhile, although it is still quicker than the for loop.  OP will have to investigate their actual use case.
There are, of course, lots of other ways to address the actual problem.  Which one is optimal is impossible to say based on the information provided.

A: Here is a data.table based solution:
nrows <- 28000
ncols <- 3000

x <- round(runif(nrows*ncols, 1, 5), 5)
u <- unique(as.vector(x))

uindex = seq(from = 1, to = length(u),  by = 1)

dt.x <- data.table(x)
dt.u <- data.table(u)
dt.u[, ut := sin(u)]
dt.res <- merge(dt.x, dt.u, by.x = "x", by.y = "u", all.x = TRUE)
ut <- dt.res[, ut]

output <- matrix(ut, nrow=nrows, ncol=ncols)

Main idea here, is to work with the vectors and tables. I think you can convert to the matrix at the very end.

A: You could use match:
    nrows <- 28000
    ncols <- 3000

    x <- matrix(round(runif(nrows*ncols, 1, 5), 5), nrow=nrows, ncol=ncols)
    u <- unique(as.vector(x))
    ut <- sin(u)

    i <- match(x, u)
    ut[i]


text:
Q: How do I limit my PHP script to only run when requested by localhost? I'm having trouble getting my php page to only run when it is requested by the server itself.
This is what I have right now:
if ($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
        //process page
} else {
        $this->redirect('http://' . $_SERVER['HTTP_HOST'] . '/404');
}

However, when I curl it, it doesn't give any errors or return anything at all. If I remove the check, it spits out the HTML as expected.
I tried echoing both of those values and got 192.168.1.186, and 192.168.1.225 respectively. I do realize they are different (this is being run by the server itself), but how can I fix it? This code was from this S.O answer

A: The title of your question implies that I can provide an answer which doesn't quite match the body of your question.
My response to this is that putting your entire script in a giant if statement seems somehow insecure and unmaintainable.
You would need a guard like this if it were possible for other computers to run your script, say by accessing it from the web.
But, if the server is the only machine which can run the script, why not just put it in a place where only the server can access it? For instance, one directory level above the web-accessible directory or in a child-directory with 700 permissions. Or use .htaccess to limit access.
That seems both safer and more maintainable.

A: It is easier and better to use your server configuration to limit file access. You could for instance use a .htaccess file in you specific directory with these contents:
order deny,allow
deny from all
allow from 127.0.0.1

To deny all traffic except from 127.0.0.1 (localhost). This will return a 403 error when someone tries to access these files from another computer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kubernetes Cluster- Worker node error while using kubectl I have created a Kubernetes cluster with 2 nodes, one Master node and one Worker node (2 different VMs).
The worker node has joined the cluster successfully, so when I run the commanad:
kubectl get nodes in my master node it appears the 2 nodes exists in the cluster!
However, when I run the command kubectl apply -f https://k8s.io/examples/controllers/nginx-deployment.yaml from my worker node terminal, in order to create a deployment in the worker node, I have the following error:
The connection to the server localhost:8080 was refused. - did you specify the right host or port?

Any help what is going on here?

A: The easy way to do it is to copy the config from master node usually found here : /etc/kubernetes/admin.conf , to whetever node you want to configure kubectl ( even on master node) . The location to be copied is : $HOME/.kube/config
Also, you can this command from master node by specify nodeselector or label.
Assign POD node

A: It looks like you have issue with your kubeconfig file, as usually localhost:8080 is the default server to connect in absence of this file . Generally, Kubernetes uses this   file  to store cluster authentication information and a list of contexts to which  kubectl  refers when running commands - that's why kubectl can't work properly without this file.
To check the presence of kubeconfig file, enter this command: kubectl config view.
Or just check the presence of the file named config in the $HOME/.kube directory, which is the default location for kubeconfig file.
If it is absent, you would need to copy the config file to your node, e.g.:
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
sudo service kubelet restart

It is also possible to generate config file in a more difficult way - instead of copying - as described here.


text:
Q: How to get proxy ip with some php function? I have two vps ,to  build  sshd on my vps_ip1 and install autoproxy plugin in firefox on local machine, to bind some_domain with vps_ip2,and put the read.php on the vps_ip2.
<?php
echo  $_SERVER['REMOTE_ADDR'];
echo  "
";
echo  $_SERVER['REQUEST_TIME'];
echo  "
";
echo  $_SERVER['HTTP_X_FORWARDED_FOR'];
echo  "
";
echo  $_SERVER['HTTP_CLIENT_IP'];
?>

Now my local ip is ip0, I connect vps_ip1 with ssh and start autoproxy,when to input  some_domain/read.php in firefox , to get the fllowing output :
vps_ip1
1426332103

$_SERVER['HTTP_X_FORWARDED_FOR'] and $_SERVER['HTTP_CLIENT_IP'] get nothing about my ip0.
How to get my local ip0 with some php function?

A: You need to read up on proxies and in which way they can function. Especially read the part about anonymous proxies.
In short, depending on the configuration of the proxy server, it might not give the originating IP, to protect the anonymity of the client.
HTTP_X_FORWARDED_FOR only holds whatever data, the proxyserver voluntarily gives you. It might be nothing. It might be the public IP of the client. It might be the local (lan) IP of the client. It might be a comma separated list of preceding/chained proxies with or without the client. It might even be any spoofed ip(s).
In the end, you cannot just trust any proxy server and what it gives you in the HTTP_X_FORWARDED_FOR header, or even if it gives you anything.
So now you need to check the proxy server that you installed on vps_ip1 and disable the anonymous functionality.

A:    <?php
   if (!empty($_SERVER["HTTP_CLIENT_IP"]))
   {
    //check for ip from share internet
    $ip = $_SERVER["HTTP_CLIENT_IP"];
   }
   elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
   {
    // Check for the Proxy User
    $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
   }
   else
   {
    $ip = $_SERVER["REMOTE_ADDR"];
   }

   // This will print user's real IP Address
   // does't matter if user using proxy or not.
   echo $ip;

   ?>

A: You have to look at the content of $_SERVER array with the command
 print_r($_SERVER);

and find which variable uses your proxy to transmit your local IP.
Depending on your proxy server, it can be many any of the following possibilites : HTTP_X_FORWARDED,HTTP_X_FORWARDED,HTTP_FORWARDED_FOR,HTTP_FORWARDED,HTTP_CLIENT_IP,HTTP_FORWARDED, or anything else.
See the following question for a quick way to retrieve the IP:
What is the most accurate way to retrieve a user's correct IP address in PHP?


text:
Q: Quadratic Programming "big M" method How does the optimization problem
$$\min_{x,\eta} \frac{1}{2} x^TGx+x^Tc+M\eta$$
$$ s.t. Ax+\eta-b \geq0$$
$$\eta\geq0$$
look in standard form? What would the KKT look like?
The problem is, that I've got a solver that needs the standard
$$\min_{x} \frac{1}{2} x^TGx+x^Tc$$
$$ s.t. Ax-b \geq0$$
as input format.
I tried to use the substitution $y=[x \quad \eta]^T$. Then the problem is
$$\min_{y} \frac{1}{2} y^T\begin{bmatrix}G & 0\\0 & 0\end{bmatrix}y+y^T\begin{bmatrix}c\\M\end{bmatrix}$$
$$ s.t. [A\quad 1]y-b \geq0$$
$$\eta\geq0$$
but with this problem the 'new' G- matrix $\begin{bmatrix}G & 0\\0 & 0\end{bmatrix}$  is singular and the solver can't solve the problem any more.


text:
Q: difference between q=word1 word2 and q="word1 word2" in Solr/Lucene Can someone please tell me what is the difference between:
q=word1 word2

and
q="word1 word2"

I'm trying to match a keyword "word1 word2" (yes, my keyword can have whitespaces) that is analyzed with KeywordTokenizerFactory and it seems it only works when I add the quotes in the query.
By the way I use Solr extended Dismax, don't know if this matters.
The syntax is then:
q="some text"&qf=KeywordField&qf=FrenchtextField

Edit:
The problem I have with quotes is that I have another field that contains fulltexte (analysis is basic and close to FrenchAnalyzer, including a lowercase filter)
I have 'HelloWorld' text indexed, and I can find it back with q=helloWoRLD but not with q="helloWoRLD": this unit test is broken since I added quotes in all my queries. I don't understand what is the difference between q=helloWoRLD and q="helloWoRLD" since it would still be 1 term search right?

A: Lucene query syntax uses spaces to separate terms so you are performing a search for "word1" in the field "q" and "word2" but with no specified field (I'm not sure how lucene behaves when no field is specified).

*

*If you want to search for the string "word1 word2" (consecutive words) in the field q then you will have to use quotes i.e. q="word1 word2"

*If you want to search for records which contain both of these words (non-consecutive) then you can search for "q=word1 AND q=word2"

I don't quite follow your hello world problem so can't comment on that. Hope this helps


text:
Q: Understanding time synchronization in Linux My /etc/localtime on my Ubuntu gives my correct timezone - EAT which is UTC +3. The date command gives the time as 21:44:58 EAT which is about the correct time (I'm not concerned about accuracy to the second in this question).
However, when I do sudo hwclock -r, it gives my time as 12:44:31 AM EAT, which is approximately three hours ahead of the correct time. I assume that the hardware clock assumes the 21:44 is in UTC.
Running the command ntpdate ntp.ubuntu.com has no effect on the hardware clock (it returns 21:44:23).
When I invoke the python interpretter and do:
import datetime
print datetime.datetime.utcnow()

It gives me 18:44:36, which is the correct UTC time (as per now).
So is it that although the hardware clock is wrong, the Operating System maintains it's own correct time? As this seems to 'go against the manual' can I safely modify the hardware clock without messing up with some other time component?

A: The operating system knows that your hardware clock is set to localtime, not UTC.  This is a configurable system parameter.  Linux tools that use system facilities for date/timezone management will produce the correct time.  hwclock -r is guessing that your hardware clock is set to UTC, but it is guessing wrong and adding three hours when it shouldn't.


text:
Q: Browsers and Jquery Is it possible for a browser to disable J QUERY. I have an issue where the user is submitting details in a form, it is saving to the database but when it submit the email, the dates set to the details dates ie Decemeber 31, 1969. Is it possible this is a browser issue. I did the same test and did not encounter this issue.
If so, how can i use my code to prevent this from happening?

A: That means that the date is being submitted in a format that the server is not understanding.

> xkcd
The solution is to better coordinate your browser and server. Not ask questions like whether the browser is capable of disabling arbitrary pieces of code...


text:
Q: Nginx reverse proxy is not sending my http requests to server running on localhost (POST/GET) I'm running a node express server on an ec2 instance (ec2-13-229-218-180.ap-southeast-1.compute.amazonaws.com). It is running a web server that handles http POST requests that will interact with an RDS database, returning queries.
My goal is to have POST/GET requests to the endpoints for example  (ec2-13-229-218-180.ap-southeast-1.compute.amazonaws.com/getData), and have nginx understand and translate that to a POST/GET request to http://localhost:3000/getData)
From my understanding, I have to setup the nginx configuration like so:
server {
    listen 80;
    listen [::]:80;

    root /var/www/example.com/html;
    index index.html index.htm index.nginx-debian.html;

    server_name ec2-13-229-218-180.ap-southeast-1.compute.amazonaws.com;

    location / {

            proxy_server http://localhost:3000;
            //other stuff
    }

}
Nginx is able to run with the current configuration, but when I try to test sending post requests to ec2-13-229-218-180.ap-southeast-1.compute.amazonaws.com/getData , i'm getting 404's. Can anyone help me with this? Thanks.

A: Add below code snippet outside the server block
    upstream nodejs {
        server 127.0.0.1:3000;
}

Then replace
proxy_server http://localhost:3000;

by
proxy_pass       http://nodejs;


text:
Q: How to say that the navigation is approximate? I have an app that is an index for businesses, so the user can search for a business and navigate to that business.
I have two types of coordinates to the business:

*

*Accurate coordinates, which navigate the user exactly to the
business building.

*Inaccurate coordinates, which navigate the user to a place near the business.

So if the coordinates are the second one, I want to write next to the navigation button that it's approximate navigation or not 100% accurate. How could I say that in English ?
thanks

A: I think you would be safe calling the second type of coordinates approximate coordinates.

Approximate (adjective):

*

*near or approaching a certain state, condition, goal, or standard

*nearly exact; not perfectly accurate or correct
(Dictionary.com)

On the other hand, the first type of coordinates could be called exact coordinates.

Exact (adjective)

*

*strictly accurate or correct

*precise, as opposed to approximate
(Dictionary.com)


text:
Q: bash: Python source venv/bin/activate No such file or directory I have a venv called TimmyEnv which should get activated to run a python script in a bash file.
The TimmyEnv folder is at /home/timmya/TimmyMain-SS/TimmyEnv and the bash file called startTimmyMain.sh is in /home/timmya.
The TimmyEnv has following folders: bin, include, lib, lib64, pyvenv.cfg. Because I'm not familiar with linux, I can't say if that's a venv or not. However I can't see activate in bin.
Bash file:
cd TimmyMain-SS
source TimmyEnv/bin/activate
nohup python3.8 main.py &

When I run sudo su - timmya -c "bash startTimmyMain.sh" in /home/timmya, I get this error:
startTimmyMain.sh: line 2: TimmyEnv/bin/activate: No such file or directory


text:
Q: Maximum Likelihood and Sampling/Independence If I viewed the data of a unknown weighted coin that was flipped N times and I see that there are H heads and T tails, I know that the maximum likelihood estimation for the probability of heads is just H/N and likewise for tails it is T/N. This is based off the assumption that each flip/trial was independent from each other and that the same coin was used for each trial. However, say if I only selected all the trials that resulted in heads and combined that into a different dataset and used that for maximum likelihood. Still, each trial is technically independent from each other and if so I would get that the maximum likelihood probability for heads is 100%. I know intuitively that this procedure is wrong, but I'm not sure why exactly it is. In addition, what if I selected the first half of all the trials, and then used that result to compute the maximum likelihood for the probability of the coin. Would that be an "ok" thing to do as I think it would just be computing the maximum likelihood for data with half the sample size?  Can someone explain intuitively what is going on here and clarify what is the difference between the two procedures?

A: MLE is a data driven framework. The question it asks is what probability distribution "most likely" would have led to the data observed. Independence just makes the calculations easier. Things get a lot more complicated otherwise.
So all you know about the world is the data you feed into MLE. If you have reasons to believe that the answer you get is not the correct one, then that knowledge ("prior knowledge") should be used to "adjust" the likelihood. This adjusting is the heart of Bayesian calculations.


text:
Q: Are each of the following statements for chords, radiuses, diameters and arcs of a circle true? Are each of the following statements for a circle true?

*

*If a radius bisects a chord, then this radius is perpendicular to this chord.

*If a radius is perpendicular to a chord, then this radius bisects this chord.

*If a radius bisects a chord, then this radius bisects a corresponding arc.

*If a radius bisects a arc, then this radius bisects a corresponding chord.

*If a radius is perpendicular to a chord, then this radius bisects a corresponding arc.

*If a radius bisects a arc, then this radius is perpendicular to a corresponding chord.

Are each of these statements true for a diameter instead of the radius?
What if the chord is a diameter? Are each of these statements true in this case?

A: They are definitely all true. Any straight line going through the center of the circle has to be perpendicular to a chord if it bisects it. To bisect it, after all, it must split it into two equal parts. This works for diameters as well, yes. Most of these situations follow the same logic as others.
I suggest drawing chords and seeing if you can create a radius that is not perpendicular to them but must also split them into equal parts. It is impossible, I guarantee (unless you draw ovals or some other shapes).


text:
Q: VBA Create Function option I have written a function which returns me value based on the Month. Like if month is January then it will return me value "Qtr 1". The problem is I have to input the month in double quotes when using the function in Excel or else Excel gives me #value error.
Function quarter(m As String) As String

If m = "January" Or m = "February" Or m = "March" Then
quarter = "Qtr 1"
ElseIf m = "April" Or m = "May" Or m = "June" Then
quarter = "Qtr 2"
ElseIf m = "July" Or m = "August" Or m = "September" Then
quarter = "Qtr 3"
Else: quarter = "Qtr 4"
End If

End Function

A: As you can see from this screenshot (based on your User Defined Function (UDF)), this is indeed correct and it is working properly:

As you can see, no double quotes are need (nor allowed) in your Excel cells, but I imagine this is not the basic idea, so everything seems to be working fine.
The usage of the double quotes in your VBA macro is basic VBA syntax.


text:
Q: Kotlin ... in function parameters, e.g. from Java - setFilterById(long... ids) In Android DownloadManager class, for example, there is a function declared in Java as:
    private long[] mIds = null;

    public Query setFilterById(long... ids) {
        mIds = ids;
        return this;
    }

In Java I can pass to it an array of long values, and it works great. In Kotlin, when I try:
    val mEnqued = ArrayList<Long>()
    // collect download ids to mEnqued...
    query.setFilterById(mEnqued.toLongArray())
    // or try to pass an array of long created in any other way...
    // it will take: query.setFilterById(7L, 15L, 234L) - but it's useless

Kotlin compiler complains "Type mismatch: inferred type is LongArray but Long was expected"... How else I could pass to this function a list or array of long Id values? I cannot type them directly in the source code, because in advance I have no idea how many of them there will be, or what will be their values? Kotlin seems to be very limited or "brain damaged" here...

A: Kotlin has the spread operator to deliver an array as list of single parameters to a vararg function:
query.setFilterById(*mEnqued.toLongArray())

See also Kotlin documentation


text:
Q: Mouse coordinates in a canvas to 30 degree isometric coordinates on a grid I have an isometric grid I'm drawing on a canvas. It uses a 30 degree angle offset and I use some script to draw a basic grid. For this grid I am projecting a flat grid with 40x40 tile sizes.
gridRows = 10;
gridCols = 10;
tileSize = 40;

gridWidth = gridCols * tileSize;
gridHeight = gridRows * tileSize;

canvasWidth = tileSize * (gridCols + gridRows) * Math.sqrt(3) / 2;
canvasHeight = tileSize * (gridRows + gridCols) / 2;

canvasOffset = tileSize * gridRows * Math.sqrt(3) / 2;

function carToIso(x, y) {
      // Convert cartesian (x, y) to isometric coordinates
      return [
        Math.round((x - y) * Math.sqrt(3) / 2 + canvasOffset),
        Math.round((x + y) / 2)
      ];
}

function drawGrid() {
            let canvas = $("#canvas");
      canvas.attr('width', canvasWidth);
      canvas.attr('height', canvasHeight);

            let ctx = canvas.get(0).getContext('2d');

      // Background
      ctx.fillStyle = "white";
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);

      // Draw lines
      ctx.beginPath();
      ctx.lineWidth = 1;

      // Rows
      for(let i = 0; i <= gridRows; ++i) {
        ctx.moveTo(...carToIso(0, i * tileSize));
        ctx.lineTo(...carToIso(gridWidth, i * tileSize));
      }

      // Columns
      for(let i = 0; i <= gridCols; ++i) {
        ctx.moveTo(...carToIso(i * tileSize, 0));
        ctx.lineTo(...carToIso(i * tileSize, gridHeight));
      }

      ctx.stroke();
}

drawGrid();

This works perfectly fine and gets me the grid I want. A fiddle with this working is here; https://jsfiddle.net/fgw10sev/2/
For the next step, I need to figure out what tile someone is hovering over. I initially had a 2:1 grid and was able to convert mouse coordinates within the canvas to grid coordinates in the original un-projected grid like so;
function mouseToIso(x, y) {
      // Convert mouse (x, y in canvas) to grid coordinates
      return [
        Math.round((2 * y + x - canvasOffset) / 2),
        Math.round((2 * y - x + canvasOffset) / 2)
      ];
    }

However, with the addition of the sqrt(3) factor, this no longer works and I cannot - for the life of me - figure out how to fix this. The original mouseToIso function was already a hackjob of trial and error and I've tried injecting the sqrt(3) factor in various places, but I just can't get it to work.
Can anyone help me out here? Or tell me I need to use a completely different approach entirely?
Note; I need this sqrt(3) factor in there because of the images I'm using. They're all at 30 degree angles and without that factor, the grid does no line up properly with the images.
Note 2; just for completenes - sqrt(3)/2 == cos(deg2rad(30)) and the 2 can be used interchangeably.

A: I am not myself very well versed in algebra so there may be an even simpler solution but anyway...
What your function needs to do is to invert the transformation that occurred in the previous step in order to find back the original x and y values.
a = Math.round((x - y) * Math.sqrt(3) / 2 + canvasOffset);
b = Math.round((x + y) / 2);

From this we can retrieve the values (x - y) and (x + y) as being
(x - y) = (a - canvasOffset) / Math.sqrt(3) * 2;
(x + y) = b * 2;

Now that we have both (x - y) and (x + y) we can find x by adding up these two values and dividing by 2, the y value cancels itself.
And now it's easy to find y, since it's just (x + y) - x.

const pre = document.querySelector("pre");
const log = (txt) => pre.textContent = JSON.stringify(txt);

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const gridRows = 10;
const gridCols = 10;
const tileSize = 40;

const gridWidth = gridCols * tileSize;
const gridHeight = gridRows * tileSize;

const canvasWidth = tileSize * (gridCols + gridRows) * Math.sqrt(3) / 2;
const canvasHeight = tileSize * (gridRows + gridCols) / 2;

const canvasOffset = tileSize * gridRows * Math.sqrt(3) / 2;

canvas.width = canvasWidth;
canvas.height = canvasHeight;

function carToIso(x, y) {
  // Convert cartesian (x, y) to isometric coordinates
  // I moved the scaling part here, it makes lees noise in the rest of the code
  // But feel free to change it back
  x *= tileSize;
  y *= tileSize;
  return [
    Math.round((x - y) * Math.sqrt(3) / 2 + canvasOffset),
    Math.round((x + y) / 2)
  ];
}

function isoToCar(a, b) {
  // Convert isometric (a, b) to cartesian coordinates
  const xMinusY = (a - canvasOffset) / Math.sqrt(3) * 2;
  const xPlusY = b * 2;
  const x = (xMinusY + xPlusY) / 2;
  const y = xPlusY - x;
  return [
    Math.floor(x / tileSize), // scaling is here too
    Math.floor(y / tileSize)
  ];
}

function drawGrid() {
  // Draw lines
  ctx.beginPath();
  ctx.lineWidth = 1;

  ctx.fillStyle = "red";

  // Rows
  for (let i = 0; i <= gridRows; ++i) {
    const [x1, y1] = carToIso(0, i);
    const [x2, y2] = carToIso(gridCols, i);
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.fillText("r" + i, (x2 + x1) / 2, (y2 + y1) / 2);
  }

  // Columns
  for (let i = 0; i <= gridCols; ++i) {
    const [x1, y1] = carToIso(i, 0);
    const [x2, y2] = carToIso(i, gridRows);
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.fillText("c" + i, (x2 + x1) / 2, (y2 + y1) / 2);
  }

  ctx.stroke();
}

function fillCell(x, y, color) {
  ctx.beginPath();
  ctx.moveTo(...carToIso(x, y));
  ctx.lineTo(...carToIso((x + 1), y));
  ctx.lineTo(...carToIso((x + 1), (y + 1)));
  ctx.lineTo(...carToIso(x, (y + 1)));
  ctx.fillStyle = "green";
  ctx.fill();
}

onmousemove = (evt) => {
  const {top, left} = canvas.getBoundingClientRect();
  const mouseX = evt.clientX - left;
  const mouseY = evt.clientY - top;
  const [gridX, gridY] = isoToCar(mouseX, mouseY);
  log({
    mouseX,
    mouseY,
    gridX,
    gridY
  });

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  fillCell(gridX, gridY, "green");
  drawGrid();
};

drawGrid();
pre { position: absolute }

<canvas id="canvas"></canvas>


text:
Q: $r(r-1)^2=1$, how to solve this polynomial analytically? I found this characteristic equation $r(r-1)^2=1$ in my homework Euler differential equation problem (page 669, again the book), $x^{3} y'''+xy'-y=0$, when I misread the problem as
$$x^{3} y'''+xy''-y=0$$
so this beast has characteristic equation that looks nightmarish at least here in WA. I am not sure whether I am missing some smart substitution to proceed, how would you solve the polynomial?
Please, keep the focus on the polynomial. Thanks for pointing out the err but I would like to know how to solve this kind of polynomials.

A: You can make the substitution
$$
z= \displaystyle \frac{1}{r-1}
$$
and obtain the equation:
$$z^3 - z - 1 = 0$$
This can be solved cleverly using the substitution $\displaystyle z = \frac{2 \cos \theta}{\sqrt{3}}$ (note: $\displaystyle \theta$ is allowed to be complex) giving rise to the equation
$$ \cos 3 \theta = \frac{3 \sqrt{3}}{2}$$
Thus we get the answer in terms of the complex function $\displaystyle \arccos$ (whose possible arguments range over all the complex numbers)
See here for an explanation of the method: Trigonometric and Hyperbolic Substitution to solve the cubic.
Of course, as Sasha points out, you probably are trying to solve the wrong equation in the first place.

A: Because the ODE you are solving is scale invariant, i.e. if $y(x)$ solves it, so does $y(\lambda x)$ for arbitrary $\lambda \not=0 $, we seek solution as $y(x) = x^r$. This leads to the characteristic equation:
$$
  0 =  r(r-1)(r-2) + r - 1 = r^3 - 3 r^2 + 3r -1 = (r-1)^3
$$
Because the root $r=1$ has triple multiplicity, the solution is logarithmic:
$$
    y(x) = x( c_1 + c_2 \ln(x) + c_3 \ln^2(x) )
$$

A: You could try using the cubic formula.


text:
Q: Android: Saving image from gallery and then loading into imageview I have an onclick that will allow a user to select a file from gallery like so:
case R.id.ColourCustom:
                customBorderChange();
                break;

private void customBorderChange() {
    final ImageView QPBackground = (ImageView) findViewById(R.id.QPBackground);
    menuHandler.removeCallbacks(menuTimer);
    menuHandler.postDelayed(menuTimer, 5000);
    bgHandler.removeCallbacks(runnableBG);
    bgHandler.postDelayed(runnableBG, 2000);
    Intent i = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, GALLERY_REQUEST);
    File file = getFileStreamPath("QuickPlayBG.png");
    if (file.exists()) {
        QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
    } else {
        String uri21 = "@drawable/bg_green";
        int imageResource21 = getResources().getIdentifier(uri21, null, getPackageName());
        QPBackground.setBackgroundResource(imageResource21);
    }
}

This sends you here:
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
    Uri selectedImageUri;
    if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && null !=
            data) {
        selectedImageUri = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImageUri,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        cursor.close();
    }
    try {
        Bundle extras = data.getExtras();
        Bitmap photo = extras.getParcelable("data");
        saveBGFile(photo);
    } catch (Exception e) {
        String errorMessage = "Make your mind up mate!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
    try {
        saveQPConfig();
    } catch (IOException e) {
        String errorMessage = "Saving failed";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

Which saves the file, using saveBGFile:
public void saveBGFile(Bitmap image) {
    FileOutputStream out = null;
    String filename = "QuickPlayBG.png";
    try {
        out = new FileOutputStream(filename);
        image.compress(Bitmap.CompressFormat.PNG, 100, out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The issue is with this line only:
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));

It doesn't load anything. If I change "QuickPlayBG.png" to another filename that I am using in another part of my app, it loads fine. Both files are created using the same method. I verified that "QuickPlayBG.png" exists.
Compiler gives me the following hint:
E/﹕ ReadStreamToBuffer : Qmage Stream read error!! required length 12 bytes, but red 0 bytes
E/﹕ isQmage : input SkStreamRewindable length is less than Qmage minimum size : 0

I think it has to do with the way I am saving the image, but I cannot see the fault myself. What could be the problem, that it is not loading the image?
Edit:
Here is the getThumbnail method I am using (works for another filename):
public Bitmap getThumbnail(String filename) {
    final Context context = this;
    String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    Bitmap thumbnail = null;

    if (thumbnail == null) {
        try {
            File filePath = context.getFileStreamPath(filename);
            FileInputStream fi = new FileInputStream(filePath);
            thumbnail = BitmapFactory.decodeStream(fi);
        } catch (Exception ex) {
            Log.e("getThumbnail() !exist", ex.getMessage());
        }
    }
    return thumbnail;
}

A: Use this short and sweet code for this. use intent of gallery.
1.declaire variable.
private static int RESULT_IMG = 1;
String imgString;

2.call intent of gallery on onclick of button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);

3.onActivityResult to your code.
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
try {
    if (requestCode == RESULT_IMG && responseCode == RESULT_OK
                    && null != data) {
    Uri pickedImage = data.getData();
    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(pickedImage,
            filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    imgString = cursor.getString(columnIndex);
    cursor.close();

    //set bitmap to your imageview
    ImageView imgView = (ImageView) findViewById(R.id.imgView);
    imgView.setImageBitmap(BitmapFactory.decodeFile(imgString));
} else {
    Toast.makeText(this, "please select picture",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
    Toast.makeText(this, "error message", Toast.LENGTH_LONG)
                    .show();
    }
}


text:
Q: compactification What is the advantage when we extend a non-compact space as compact space. For example, one point compactification. I think it makes sense to make a non-complete space as a complete space. However, for one point compactification, we define a new topology. Would you give me any comment for this question. Thanks in advance.

A: It gives the advantage of embedding a space into a compact space.
For example let S be a locally compact Hausdorff space.  Then the
one point compacitification S' of S is a compact Hausdorff space,
hence normal, thus regular.  Since S is a subspace of a regular
space, S is regular.
How would you prove that locally compact Hausdorff spaces
are regular without using a one point compactification?


text:
Q: UiApp: Persistent login for non-gmail users I am attempting to implement a Google Apps Script web service which requires users to log in using an account set up on our system.
The users will not necessarily have a gmail account, and should not be required to create one.
The web service must run using as the script owner, as it is necessary for it to be able to write to a spreadsheet and other resources which do not have shared write permission.
I have managed to implement the login screen, with reasonably strong security -- but the problem I encounter now is that users must log back in every time they visit, and even if they hit the refresh button.
Any ideas on how to implement this?
Is there some way to store a cookie in the users browser, containing a session id?
Or is there some other method which can work?
Thanks in advance!
Josh

A: This is a very old post but as there is a solution, I think it is better to show it to help people with a similar need
Hi Josh,
I have developed such a system and there is indeed a way to do this.
You can indeed develop a cookie like system that is using the PrivateCache class: CacheService.getPrivateCache().
It works if the user reload the page or close it.
However with this solution when you close your browser it will not be possible to retrieve the information anymore.
Here are the functions that I use to prevent the problem you have underlined
Feel free to adapt them
function getCookie(){
  var cache=CacheService.getPrivateCache();
  var cached=cache.get("UserCookie");
  if(cached!=null){
    return Utilities.jsonParse(cached);
  }
  return -1;
}

function createCookie(data){
  var cache=CacheService.getPrivateCache();
  cache.put("UserCookie",Utilities.jsonStringify(data),1800);
}

function removeCookie(){
  var cache=CacheService.getPrivateCache();
  cache.remove("UserCookie");
}

Another way would be to use UserProperties. In this case it will work even if you close your browser... I just tried it
the functions to use are therefore:
function getCookie(){
  var cached=UserProperties.getProperty('UserCookie');
  if(cached!=null){
    return Utilities.jsonParse(cached);
  }
  return -1;
}

function createCookie(data){
    UserProperties.setProperty('UserCookie',Utilities.jsonStringify(data));
}

function removeCookie(){
  UserProperties.deleteProperty("UserCookie");
}

I hope it will help anyone...
Cheers
Nicolas

A: Persistent login are not possible with Apps Script as Apps Script can not interact with browser objects like cookies etc. Apps Script is intended to work only with Google Accounts.


text:
Q: Graphics appearing above text For some reason the graphics is rendered above the text. I'm using xelatex (with Chinese characters).
The relevant Chinese latex compiled using xelatex is on pastebin as for some reason stackexchange won't let me post some Chinese characters.
http://pastebin.com/21uAah13
It probably has something to do with the trimming being faulty. Any help would be much appreciated.

EDIT:
Removing all the other unnecessary packages, removing sections and substituting the Chinese characters with English:
\documentclass{article}
\usepackage[margin=0.5in]{geometry}
\usepackage{graphicx}

\begin{document}

AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
\begin{figure}[h!]
\includegraphics[trim={4cm 8cm 4cm 5.5cm},clip,height=8cm]{BotnetFamPie}
\end{figure}

\end{document}

Screenshot:

Without the trim and clip:


text:
Q: Spring REST @RequestMapping taking multiple media types I'm developing a REST API with Spring, and would like an API to handle POST requests with different media types, namely JSON form data in request body, or a JSON file sent through the request.
So when I have two separate methods with such signatures both work fine,
@RequestMapping(value = "/configuration" , method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String setConfiguration(@RequestPart MultipartFile file)

@RequestMapping(value = "/configuration" , method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}
public String setConfiguration(@RequestBody Configuration configuration)

The handling logic of both methods are almost the same, so I'm trying to use one method to absorb both kinds of data format with this code:
@RequestMapping(value = "/configuration" , method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public String setConfiguration(@RequestPart MultipartFile file, @RequestBody Configuration configuration)

However an error response will be returned as,
{"timestamp": 1443744180124,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.springframework.web.multipart.MultipartException",
  "message": "The current request is not a multipart request",
  "path": "/v1/testconfiguration"
}

Wondering if I have some fundamental misunderstanding of media type of REST and if this is doable how can I achieve it with Spring?

A: If they both work as separate methods then you are better off just doing it that way.
It is probably be neater and easier to read, there's no need to try and make optimisations like you are doing at the moment, not that I don't labour over my own code.

A: Although it has been more than 4 years already since this question was asked, putting an answer for people in same sort of problem in the future.
Since the Request Method is POST in both cases, @PostMapping can be used replacing @RequestMapping.
With @PostMapping it is possible to have multiple MediaTypes. For instance, below code should not cause any problems.
@PostMapping(value = "/configuration", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE })
public String setConfiguration(@RequestPart MultipartFile file, @RequestBody Configuration configuration)

NOTE: As the method parameters are different, @Mhowell's approach seems right.


text:
Q: Error deserializing yaml with yamldotnet - Property not found I'm using C#, YamlDotNet and following the example:
How to deserialize YAML with YAMLDotNet?
But I'm getting the follow error:
Exception thrown: 'YamlDotNet.Core.YamlException' in YamlDotNet.dll
YamlDotNet.Core.YamlException: (Line: 1, Col: 1, Idx: 0) - (Line: 1, Col: 1, Idx: 0): Exception during deserialization ---> System.Runtime.Serialization.SerializationException: Property 'PlatForm' not found on type 'NAC21_Calculator.UserSoft'.
   at YamlDotNet.Serialization.TypeInspectors.TypeInspectorSkeleton.GetProperty(Type type, Object container, String name, Boolean ignoreUnmatched)
   at YamlDotNet.Serialization.NodeDeserializers.ObjectNodeDeserializer.YamlDotNet.Serialization.INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func`3 nestedObjectDeserializer, Object& value)
   at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
   --- End of inner exception stack trace ---
   at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
   at YamlDotNet.Serialization.ValueDeserializers.AliasValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
   at YamlDotNet.Serialization.Deserializer.Deserialize(IParser parser, Type type)
   at YamlDotNet.Serialization.Deserializer.Deserialize[T](IParser parser)
   at YamlDotNet.Serialization.Deserializer.Deserialize[T](TextReader input)
   at NAC21_Calculator.YamlImporter.Deserialize(String yamlName) in D:\UserInput.cs:line 124
   at NAC21_Calculator.UserInput.GenerateBut_click(Object sender, EventArgs e) in D:\UserInput.cs:line 68
The program '[20556] NAC21_Calculator.exe' has exited with code 0 (0x0).

The yaml file content is:
PlatForm: windows
Version: 10
    # Software Info
SOFTWARE:
    Software-01:
        NAME    : MFS2020
        VERSION : 1.12.2015
        Customized  : true
    Software-02:
        NAME    : DCS
        VERSION : 6
        Customized  : false

The object definition:
public class UserSoft
    {
        public List<string> PlatForm { get; set; }
        public List<string> Version { get; set; }
        public List<software> SOFTWARE { get; set; }

        public class software
        {
            public string NAME { get; set; }
            public string VERSION { get; set; }
            public string Customized { get; set; }

        }
    }

And performing the deserialization whe pressing a button with:
private void GenerateBut_click(object sender, EventArgs e)
        {
           UserSoft obj = YamlImporter.Deserialize("file_template.yml");

           Console.WriteLine("Platform: {0}", obj.PlatForm);
           Console.WriteLine("Version: {0}", obj.Version);

           foreach (var soft in obj.SOFTWARE)
                  Console.WriteLine("Software: {0}", soft);

            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }

 public class YamlImporter
    {
        public static UserSoft Deserialize(string yamlName)
        {
            StreamReader sr = new StreamReader(yamlName);
            string text = sr.ReadToEnd();
            var input = new StringReader(text);
            var deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build();
            UserSoft deserializeObject = deserializer.Deserialize<UserSoft>(input); /* compile error */
            return deserializeObject;
        }
    }

I'm new in C# and this issue is the only that is really blocking me.
Thanks in advance.

A: There are a few problems here.
Firstly, your PlatForm and Version properties are of type List<string>, but the value is just a string.
Secondly, your SOFTWARE property doesn't represent a list, but a map - the strings "Software-01" and "Software-02" are effectively keys within a map.
Thirdly, you've explicitly stated that you want to deserialize with a camel-case naming convention, but your YAML doesn't actually use that convention.
Here's a minimal, complete example with those aspects corrected:
using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.Serialization;

public class UserSoft
{
    public string PlatForm { get; set; }
    public string Version { get; set; }
    public Dictionary<string, software> SOFTWARE { get; set; }

    public class software
    {
        public string NAME { get; set; }
        public string VERSION { get; set; }
        public string Customized { get; set; }

    }
}

class Program
{
    static void Main(string[] args)
    {
        string text = File.ReadAllText("test.yaml");
        var deserializer = new DeserializerBuilder().Build();
        UserSoft deserialized = deserializer.Deserialize<UserSoft>(text);
        Console.WriteLine($"Platform: {deserialized.PlatForm}");
        Console.WriteLine($"Version: {deserialized.Version}");
        foreach (var pair in deserialized.SOFTWARE)
        {
            var value = pair.Value;
            Console.WriteLine($"{pair.Key}: Name={value.NAME}; Version={value.VERSION}; Customized={value.Customized}");
        }
    }
}

Output:
Platform: windows
Version: 10
Software-01: Name=MFS2020; Version=1.12.2015; Customized=true
Software-02: Name=DCS; Version=6; Customized=false

As an aside, I'd strongly recommend that you try to be consistent in your capitalization, and follow .NET naming conventions.


text:
Q: Heroku Application Error while user login Heroku Application Error appears when the user signed in with an email and password and the error removed when I set command $heroku restart
The error
code=H13 desc="Connection closed without response" method=POST
path="/doctor/login"


text:
Q: How to use Redis / Node.Js on a production server I get what Redis and Node.js are but i don't understand how to run them on a live server. Locally its an install and you use the command line to get them running but i don't know how to install them on a live server.
I've already browsed around a bit but im still confused and also isn't Node.JS a server itself so its like running a server on a server? wouldn't that have effects on performance and what not?
I'm just confused on how it would work, any explanation will be great.. thanks

A: There are different ways to run a node service. I strongly recommend docker to run everything but here is a short list of the most popular ones:

*

*https://www.docker.com/ https://hub.docker.com/_/node/

*http://pm2.keymetrics.io/

*https://www.npmjs.com/package/forever (seems like a bit outdated)

A: Redis & Node.js = Software
You install those on a physical machine, a computer. A node.js server is not a physical server, but an application that can handle HTTP requests. Normally, a node.js server runs on a port on a physical machine. So any HTTP requests sent to that port are handled by the node.js application. You can use a webserver, which is another piece of software that handles HTTP requests, like Nginx or Apache to manage multiple domains on a physical machine (the server). Redis also runs on a physical machine and listens on a specified port.
For example, I have a VPS with 4 websites on it managed by Nginx. Two of those websites are Laravel projects that connect to a MySQL server (on another machine) and to a Redis server on the same machine. The other two are node.js applications which don't need a database or Redis, so they just listen on their own ports and Nginx proxies all connections to their domainnames to those ports.
So you're not actually running a server on a server, but you're running software that handles certain things on a server.


text:
Q: EF Migration - One database, two projects We are using EF Code First with manual migration (AutomaticMigrationsEnabled = false;). The problem is that we need to share one database between two projects.
Project-A
---DbContext-A
---------Model1
---------Model2
---------Model3

Project-B
---DbContext-A
---------Model2
---------Model3
---------Model4

Some of the migration files are the same but some of them are different. For example: Project-B needs Model4 but Project-A doesn't..
Currently, If I update the database with one migration, DbContext will not work in other project.
What would be the best way to handle this scenario?

A: My feeling is that this is working against the intentions with migrations. I think that you should break out the DbContext, the entities and the migrations to a separate assembly that is shared between the two projects.
If that's not an option, you have to disable the compatibility check with the model. The compatibility check is done as part of the IDBInitializer.InitializeDatabase implementation, which is responsible for calling Database.CompatibleWithModel, so writing your own custom DB Initializer that does nothing would get you past that step. This also means that you take over the responsibility of ensuring that the database is compatible with the model. EF can't help you any more.


text:
Q: OSError [Errno 22] invalid argument when use open() in Python def choose_option(self):
        if self.option_picker.currentRow() == 0:
            description = open(":/description_files/program_description.txt","r")
            self.information_shower.setText(description.read())
        elif self.option_picker.currentRow() == 1:
            requirements = open(":/description_files/requirements_for_client_data.txt", "r")
            self.information_shower.setText(requirements.read())
        elif self.option_picker.currentRow() == 2:
            menus = open(":/description_files/menus.txt", "r")
            self.information_shower.setText(menus.read())

I am using resource files and something is going wrong when i am using it as argument in open function, but when i am using it for loading of pictures and icons everything is fine.

A: I received the same error when trying to print an absolutely enormous dictionary. When I attempted to print just the keys of the dictionary, all was well!

A: That is not a valid file path. You must either use a full path
open(r"C:\description_files\program_description.txt","r")

Or a relative path
open("program_description.txt","r")

A: In my case, I was using an invalid string prefix.
Wrong:
path = f"D:\Folder\file.txt"

Right:
path = r"D:\Folder\file.txt"

A: In my case the error was due to lack of permissions to the folder path. I entered and saved the credentials and the issue was solved.

A: I had the same problem
It happens because files can't contain special characters like ":", "?", ">" and etc.
You should replace these files by using replace() function:
filename = filename.replace("special character to replace", "-")

A: you should add one more "/" in the last "/" of path, that is:
open('C:\Python34\book.csv') to open('C:\Python34\\book.csv'). For example:
import csv
with open('C:\Python34\\book.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter='', quotechar='|')
    for row in spamreader:
        print(row)

A: In Windows-Pycharm: If File Location|Path contains any string like \t then need to escape that with additional \ like \\t

A: Just replace with "/" for file path :
   open("description_files/program_description.txt","r")

A: just use single quotation marks only and use 'r' raw string upfront and a single '/'
for eg
f = open(r'C:/Desktop/file.txt','r')
print(f.read())

A: Add 'r' in starting of path:
path = r"D:\Folder\file.txt"

That works for me.

A: I also ran into this fault when I used open(file_path). My reason for this fault was that my file_path had a special character like "?" or "<".

A: I had special characters like '' in my strings, for example for one location I had a file Varzea*, then when I tried to save ('Varzea.csv') with f-string Windows complained. I just "sanitized" the string and all got back to normal.
The best way in my case was to let the strings with just letters, without special characters!

A: For me this issue was caused by trying to write a datetime to file.
Note: this doesn't work:
myFile = open(str(datetime.now()),"a")
The datetime.now() object contains the colon ''':''' character
To fix this, use a filename which avoid restricted special characters. Note this resource on detecting and replacing invalid characters:
https://stackoverflow.com/a/13593932/9053474
For completeness, replace unwanted characters with the following:
import re
re.sub(r'[^\w_. -]', '_', filename)
Note these are Windows restricted characters and invalid characters differ by platform.

A: for folder, subs, files in os.walk(unicode(docs_dir, 'utf-8')):
    for filename in files:
        if not filename.startswith('.'):
            file_path = os.path.join(folder, filename)

A: In my case,the problem exists beacause I have not set permission for drive "C:\" and when I change my path to other drive like "F:\" my problem resolved.

A: import pandas as pd
df = pd.read_excel ('C:/Users/yourlogin/new folder/file.xlsx')
print (df)

A: I got this error because old server instance was running and using log file, hence new instance was not able to write to log file. Post deleting log file this issue got resolved.

A: When I copy the path by right clicking the file---> properties-->security, it shows the error. The working method for this is to copy path and filename separately.

A: I had faced same issue while working with pandas and trying to open a big csv file:
wrong_df = pd.read_csv("D:\Python Projects\ML\titanic.csv")
right_df = pd.read_csv("D:\Python Projects\ML\\titanic.csv")


text:
Q: Getting a piped curl command output to a variable in bash I'm attempting to monitor an output from a proxy server to troubleshoot issues, in order to do that I've created a bash script which uses curl, but I'm having trouble in getting the output in a variable.
I've tried different ways to escape and to use the variables, either using ticks or parentheses.
I was using this first, but wasn't working properly:
response=$(curl -k -x $i:1234 -U $u:$p -w $outputformat -s -o /dev/null $site | cut -d ' ' -f 2)

Thus changed it, and the code now looks like this:
response=$(curl\ -k\ -x\ $i:1234\ -U\ $u:$p\ -w\ \"HTTP\ Response:\ \%\{http\_code\}\ \-\ URL:\ \%\{redirect\_url\}\\n\"\ -s\ -o\ /dev/null\ $site\ \|\ cut\ -d\ \'\ \'\ -f\ 2)
if [ "$response" -eq 200 ]; then
   ((count200++))
   echo $count200 > $counter_200
else
   ((countx0x++))
   echo $count0x0 > $counter_x0x
fi

8/22 - Updated code as requested, I reverted back the code to what it was before and also following WaltDe's recommendation removed the -o option:
echo "Proxy: $i"
echo "Fetching site: $site"
outputformat="\"HTTP Response: %{http_code} - URL: %{redirect_url}\n\""
response=$(curl -k -x $i:$port -U $u:$p -w $outputformat -s $site | cut -d ' ' -f 2)
if [ "$response" -eq 200 ]; then
   ((count200++))
   echo $count200 > $counter_200
else
   ((countx0x++))
   echo $count0x0 > $counter_x0x
fi

This is the error message that I'm seeing:

./ptest.sh: line 80: curl -k -x *********:** -U : -w "HTTP Response: %{http_code} - URL: %{redirect_url}\n" -s -o /dev/null https://www.yahoo.com | cut -d ' ' -f 2: No such file or directory
./ptest.sh: line 82: [: : integer expression expected

8/22 Update - This is the issue I'm having now:

Proxy: ************
  Fetching site: https://www.yahoo.com
  html>
  id="atomic"

  (...)
   shortened for readability - html output
  (...)
  Response:: integer expression expected
  ./ptest.sh: line 83: [: Response:: integer expression expected

Could anyone shed some light as to what I'm doing wrong?

A: You need to remove the -o option that writes the output to a file, in your case /dev/null.  Here is your updated code that should work.
$ response=$(curl -k -x $i:1234 -U $u:$p -w $outputformat -s $site | cut -d ' ' -f 2)

Another way to check is to remove pipe and send your STDERR to /dev/null.  This will show you what is getting passed to your cut command.
You should see something if all is happy.
$ curl -k -x $i:1234 -U $u:$p  -s $site 2>/dev/null

If you don't get any output, then remove the STDERR redirect and echo the return code.
$ curl -k -x $i:1234 -U $u:$p  -s $site
$ echo $?
0

If the exit code is anything other then 0 you have an error.  You can find the error codes in the man page or this site has pretty good write up.
No to get the response code.
$ curl  -w "HTTP Response: %{http_code} - URL: %{redirect_url}\n"  -o /dev/null  -s http://yahoo.com/
HTTP Response: 301 - URL: https://yahoo.com/
$  curl  -w "%{http_code}\n"  -o /dev/null  -s http://yahoo.com/
301
$ response=$(curl  -w "%{http_code}\n"  -o /dev/null  -s http://yahoo.com/)
$ echo $response
301
$  curl  -w "%{http_code}\n"  -o /dev/null  -s http://yahoo.com/ | cut -d' ' -f3
301
$ response=$( curl  -w "%{http_code}\n"  -o /dev/null  -s http://yahoo.com/ | cut -d' ' -f3)
$ echo $response
301


text:
Q: Android BluetoothGatt setCharacteristicNotification only setting first characteristic I have been having trouble using two different characteristics at the same time through the same Bluetooth LE device. It only registers the first characteristic and not the second one. If I switch them around, it still registers the first in line, but not the second. Both the first and second characteristic need to be registered and received. If it helps, I am using a Samsung Galaxy S4 running 4.4.2.
Here is the section of the code that calls setCharacteristicNotification()
if (mBluetoothBeaconGatt != null && mBluetoothBeaconGatt.getService(UUID_CUSTOM_SERVICE) != null) {

        characteristicBracelet = mBluetoothBeaconGatt.getService(UUID_CUSTOM_SERVICE)
                .getCharacteristic(UUID_CUSTOM_BRACELET);

        characteristicBeacon = mBluetoothBeaconGatt.getService(UUID_CUSTOM_SERVICE)
                .getCharacteristic(UUID_CUSTOM_BEACON);

        if(characteristicBracelet != null) {
            Log.i(TAG, "Init Bracelet Characteristics");
            this.setCharacteristicNotification(characteristicBracelet,
                    true);
        }
        if(characteristicBeacon != null) {
            Log.i(TAG, "Init Beacon Characteristics");
            this.setCharacteristicNotification(characteristicBeacon, true);
        }
    }

setCharacteristicNotification
if (UUID_CUSTOM_BEACON.equals(characteristic.getUuid())) {
        if (mBluetoothBeaconGatt != null) {
            Log.i(TAG, "Enabling indication for beacon");
            mBluetoothBeaconGatt.setCharacteristicNotification(characteristic, enabled);
            BluetoothGattDescriptor descriptor = characteristic
                    .getDescriptor(UUID
                            .fromString(CustomGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor
                    .setValue((enabled) ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
                            : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
            mBluetoothBeaconGatt.writeDescriptor(descriptor);
        }
    } else if (UUID_CUSTOM_BRACELET.equals(characteristic.getUuid())) {
        if (mBluetoothBraceletGatt != null || mBluetoothBeaconGatt != null) {
            BluetoothGatt gatt = (mBluetoothBeaconGatt != null) ? mBluetoothBeaconGatt : mBluetoothBraceletGatt;
            gatt.setCharacteristicNotification(characteristic, enabled);
            BluetoothGattDescriptor descriptor = characteristic
                    .getDescriptor(UUID
                            .fromString(CustomGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor
                    .setValue((enabled) ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
                            : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);
        }
    }

The variables that get tested to see if they are null verify them as being not null.
If you need other information or this is a duplicate, please let me know.
Thanks for taking time to help.

A: You can't perform multiple bluetooth operations at the same time. Once you get a onDescriptorWrite, you can enable/disable your next characteristic:
private int index;
private boolean enabled;

private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        index++;
        setNotification();
    }
}

public void notify(boolean enabled){
    index = 0;
    this.enabled = enabled;
    setNotification();
}

private void setNotification(){
    BluetoothGattCharacteristic characteristic;
    switch(index){
        case 0:
            characteristic = mBluetoothGatt.getService(MY_SERVICE_UUID)
                        .getCharacteristic(UUID_CUSTOM_BRACELET);
            break;
        case 1:
            characteristic = mBluetoothGatt.getService(MY_SERVICE_UUID)
                        .getCharacteristic(UUID_CUSTOM_BEACON);
            break;
        default:
            return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
    descriptor.setValue((enabled) ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                        : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(desc);
}

Nice tutorial from NewCircle: https://newcircle.com/s/post/1553/bluetooth_smart_le_android_tutorial


text:
Q: After adding search bar, listview does not launch right html file I have been working on a project, in which i have a main activity in which i have listview and one search bar(edit text bar) and the onitemclicklistener of my listview passes the row position to a activity having webview and the webview opens html pages to their respective positions. i also have my listview items stored in arrays.xml
my problem starts here- my Listview Works file and opens respective activity on row click (when i dont use search bar and just scroll and click on row.)
but when i use the searchbar to search for an item (html page) for instance let it be "c" and i click on it , the listview DoesNot open the correct html page!. hope this is clear
 i found one solution here After filter a listview,how can I obtain the position of the first listview?
but i have no idea how do i implement this in my code.
here is my main activity
 package com.Sample.htmlOpener;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
private ListView list1;
private String array[] ;
EditText inputSearch;
ArrayAdapter<String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    inputSearch = (EditText) findViewById(R.id.inputSearch);
    list1 = (ListView) findViewById(R.id.ListView01);
    array = getResources().getStringArray(R.array.myArray);
    adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array);
    list1.setAdapter(adapter);
    inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
    int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub
    }
 });

  list1.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        Intent myIntent = new Intent(MainActivity.this,WebViewActivity.class);
        myIntent.putExtra("key",position);
        startActivity(myIntent);
    }
  });
}
}

and here is my webview activity
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewActivity extends Activity {
    WebView web;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        web = (WebView) findViewById(R.id.webView1);
        web.setWebViewClient(new myWebClient());
        web.getSettings().setJavaScriptEnabled(true);
        int pos = getIntent().getIntExtra("key",0);
        if(pos==0)
        {
            web.loadUrl("file:///android_asset/file.html");
        }
        else
        {
            web.loadUrl("file:///android_asset/file" + pos + ".html");
        }
      // similarly for 4 and 5 and so on.
    }

    public class myWebClient extends WebViewClient
    {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            view.loadUrl(url);
            return true;

        }
        @Override
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

        }
    }
}

A: The step by step procedure is provided here. You can follow this tutorial and easily understand about custom listview adapter plus search functionality using SQLite Database.
If you want to understand more about SQLite follow this.
hope you will solve your problem, but learning is must :)


text:
Q: Ember data find vs load When you use findQuery in ember-data, does it also load the model localy ? I can't make the following code to work :
App.MyModel = DS.Model.extend {

   name: DS.attr('string')
   didLoad: ->
    console.log('model loaded')
}

Now when I do something like :
objects = App.store.find(App.MyModel, [{name: "john"},{name: "jack"}])

The didLoad callback is not fired. When this callback is fired ?

A: To implement the query functionality you have to implement the findQuery method in your adapter. This method takes 4 arguments store, type, query, modelArray. When the server returns the data for the query, you have to invoke the load method on the modelArray to fill it with the query result. This method also loads the data into the store, see an example here: http://jsfiddle.net/pangratz666/5HMGd/.
App.store = DS.Store.create({
    revision: 4,
    adapter: DS.Adapter.create({
        find: Ember.K,
        findQuery: function(store, type, query, modelArray) {
            // expect server to return this array
            modelArray.load([{ id: 1, name: 'John'}, { id: 2, name: 'Jack'}]);
        }
    })
});

App.MyModel = DS.Model.extend({
    name: DS.attr('string'),
    didLoad: function() {
        console.log('model loaded', this.toJSON());
    }
});

// invoke query which loads the 2 models, and didLoad is called
App.store.find(App.MyModel, {});


text:
Q: gradle returns error wen i use android-donations-lib Im trying to add the lib Donations from android-donations-lib
and my app's gradle looks like this:
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
//    buildToolsVersion '21.1.2'
    buildToolsVersion '20.0.0'

    defaultConfig {
        applicationId "com.listoapp.listo"
        minSdkVersion 14
    //        minSdkVersion 18
    //        targetSdkVersion 18
            targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
         release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
            'proguard-rules.pro'
        }
    }

    productFlavors {
        google {
            buildConfigField "boolean", "DONATIONS_GOOGLE", "true"
        }
        fdroid {
            buildConfigField "boolean", "DONATIONS_GOOGLE", "true"
        }
    }
}

repositories { mavenCentral() }
dependencies {
    //    compile 'com.facebook.android:facebook-android-sdk:4.0.0'
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.parse.bolts:bolts-android:1.+'
    compile fileTree(include: 'Parse-*.jar', dir: 'libs')
    compile 'com.android.support:support-v4:21.0.+'
    compile 'com.github.clans:fab:1.3.0'
    //with menus --Doron
    compile 'com.afollestad:material-dialogs:0.7.2.0'
    //Dialogs --Doron
    compile 'com.github.rey5137:material:1.1.0'
    //for new design
    compile 'com.android.support:cardview-v7:21.0.3'
    compile 'com.melnykov:floatingactionbutton:1.3.0'
    //for add participant

    compile 'com.github.medyo:fancybuttons:1.2@aar' //for fb login button
    compile project(':facebook')
    compile files('libs/ParseFacebookUtilsV4-1.9.0.jar')
    compile 'com.github.amlcurran.showcaseview:library:5.0.0'
    compile project(':libraries:Donations')
}

However, every time i try to run the app it gives me the error:
Error:Execution failed for task ':app:dexFdroidDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_25\bin\java.exe'' finished with non-zero exit value 2

Does anyone have a clue on what this error is?
UPDATE:
I found the problam...i had to temove all traces of my previous billing system...thanks anyway :)


text:
Q: Limit with Multivariate L'Hospital's Rule I've got the following function:
$$ f(\eta_0,\eta_1,R,T) = \frac{\sum_{n=2}^\infty \left[ 1 - (1-\eta_0R)^n - (1-\eta_1T)^n + (1-\eta_0R-\eta_1T)^n \right] P(n)}{\left[ \sum_{n=1}^\infty \left[ 1-(1-\eta_0R)^n \right] P(n) \right] \left[ \sum_{n=1}^\infty \left[ 1-(1-\eta_1T)^n \right] P(n) \right]}, $$
where $P(n)$ is a discrete probability distribution over $n \in \mathbb{N}$, and also $0 < R,T,\eta_0,\eta_1 < 1$, and $R+T=1$ but $\eta_{0,1}$ are not related.
I'm reading a paper which states that
$$ \lim\limits_{\eta_0,\eta_1 \to 0} f(\eta_0,\eta_1,R,T) = \frac{\sum_{n=0}^\infty n(n-1)P(n)}{\left[ \sum_{n=0}^\infty nP(n) \right]^2}, $$
and they say that this can be obtained by "applying L'Hospital's Rule."
The question of multivariable versions of L'Hospital's Rule seems to be pretty complicated, so it's not clear to me what exactly the authors are referring to. It would also seem the problem is not as easy as approaching along one of the $\eta_{0,1}$ axes since setting either to zero immediately causes problems in the denominator. I tried to go along the path $\eta_0=\eta_1=\eta$ and then applying L'Hospital's rule on $\eta$, but that produced a big mess with no obvious way to simplify it down, and also that would only be the limit in a single direction, I suppose.
Any hints or ways to formally work this would be much appreciated.


text: Q: Can you truly explain multimode optical fiber in the ray picture? When I studied wave guides I understood multimode and single mode guides as consecuences of maxwell equations, latelly I have been reading about multimode fiber in a more technical context and it seems some people understand multimode fiber in the ray picture but I dont seem to understand how it is explained, I get that the bigger the core diameter the wider variety of angles it can accept and this intuitivelly correlates with multimode fiber but I don't think you can explain it in the ray picture (how can you see the change in $v$ number that signals the transition from single mode to multi mode?)


text:
Q: How to define bold, italic for fonts hosted in the cloud? I am using web fonts provided like this:
font-family:'Sabon LT W01 Roman';
font-family:'Sabon LT W01 Italic';

and would like to be able to use something like this in my css:
font-family: 'Sabon';
font-style: italic;

instead of
font-style: 'Sabon LT W01 Italic'

in my css.
Is there a way to achieve this? I am aware of the possibility to define bold/italic when using @font-face and linking to fonts directly, but this is not the case. The fonts are hosted at Fonts.com so I don't think I can use @font-face and specify font files unless I host them.
This is how I have set the styles up right now:
%font-serif {
  font-family:'Sabon LT W01 Roman', serif;
}

%font-serif-italic {
  font-family:'Sabon LT W01 Italic', serif;
  font-style: italic;
}

which forces me to use @extend %font-serif; instead of
@extend %font-serif;
font-style: italic;

A: How are you importing your fonts? direct link? if so you can still use font face:
@font-face {
  font-family: 'Sabon';
  src: local('Sabon'), local('Sabon'), url('http://link/font.woff') format('woff');
}

Then you could use it:
#block{
    font-family: 'Sabon';
    font-weight: bold;
}


text:
Q: calling -retain multiple times on the same object What happens when you call -retain on an object many times?  Is it OK to just release it once at when you're done using it?

A: Generally you need to release the object as many times as it is retained - this is why its called reference counting.  The holders of pointers to your object call -retain to keep it in memory.  It will only be deallocated once its been -release'd the correct number of times.  Retaining it more than necessary is therefore keeping memory allocated beyond its useful life - and is called a memory leak.  The Xcode Instruments tool has a memory leak analysis tool.
Here is a good description of Memory Management
I also agree with @Chris who comments above that this Answer describing how retain/release works is very good.


text:
Q: How can I run two different prefect projects on the same server? I have two different projects and I want to run both projects in separate urls.
For example, one project should run at 127.0.0.1:8080 while the other project should run at 127.0.0.1:8081
I created different docker-compose.yml for prefect containers and gave different ports.I created the containers but I can't access it except port 8080.
Is it possible to run two different prefect projects on the same server?

A: In my opinion, you should define port in docker compose file
Example:
service:
 container1:
    image: xxx
    container_name: xxx
    ports:
      - "8080:3307"

service:
 container2:
    image: yyy
    container_name: yyy
    ports:
      - "8081:3307"

A: Also, if you're just getting started with Prefect, it would be much easier for you to start with Prefect 2.0 - here are the docs. You could easily switch between both instances using Profiles https://orion-docs.prefect.io/concepts/settings/#configuration-profiles


text:
Q: Why in the world would I have_many relationships? I just ran into an interesting situation about relationships and databases. I am writing a ruby app and for my database I am using postgresql. I have a parent object "user" and a related object "thingies" where a user can have one or more thingies.  What would be the advantage of using a separate table vs just embedding data within a field in the parent table?
Example from ActiveRecord:
using a related table:
def change
    create_table :users do |i|
        i.text :name
    end
    create_table :thingies do |i|
        i.integer :thingie
        i.text :discription
    end
end
class User < ActiveRecord::Base
    has_many :thingies
end
class Thingie < ActiveRecord::Base
    belongs_to :user
end

using an embedded data structure (multidimensional array) method:
def change
    create_table :users do |i|
        i.text :name
        i.text :thingies, array: true # example contents: [[thingie,discription],[thingie,discription]]
    end
end
class User < ActiveRecord::Base
end

Relevant Information
I am using heroku and heroku-posgres as my database. I am using their free option, which limits me to 10,000 rows. This seems to make me want to use the multidimensional array way, but I don't really know.

A: what if users John and Ann have the same thingies? the records will be duplicated and if you decide to change the name of thingie you will have to change two or more records. If thingie is stored in the separate table you have to change only one record. FYI https://en.wikipedia.org/wiki/Database_normalization

A: Benefits of one to many:

*

*Easier ORM (Object Relational Mapping) integration.  You can use it either way, but you have to define your tables with native sql.  Having distinct tables is easier and you can make use of auto-generated mappings.

*Your space limitation of 10,000 rows will go further with the one to many relationship in the case that 2 or more people can have the same "thingies."

*Handle users and thingies separately.  In some cases, you might only care about people or thingies, not their relationship with each other.  Some examples, updating a username or thingy description, getting a list of all thingies (or all users).  Selecting from the single table can make it harding to work with.

*Maintenance and manipulation is easier.  In the case that a user or a thingy is updated (name change, email address update, etc), you only need to update 1 record in their table instead of writing update statements "where user_id=?".

*Enforceable database constraints.  What if a thingy is not owned by anyone?  Is the user column now nillable?  It would have to be in the single table case, so you could not enforce a simple "not nillable" username, for example.

There are a lot of reasons of course.  If you are using a relational database, you should make use of the one to many by separating your objects (users and thingies) as separate tables.  Considering your limitation on number of records and that the size of your dataset is small (under 10,000), you shouldn't feel the down side of normalized data.
The short truth is that there are benefits of both.  You could, for example, get faster read times from the single table approach because you don't need complicated joins.
Here is a good reference with the pros/cons of both (normalized is the multiple table approach and denormalized is the single table approach).
http://www.ovaistariq.net/199/databases-normalization-or-denormalization-which-is-the-better-technique/

A: Embedding a data structure in a field can work for simple cases but it prevents you from taking advantage of relational databases.  Relational databases are designed to find, update, delete and protect your data.  With an embedded field containing its own wad-o-data (array, JSON, xml etc), you wind up writing all the code to do this yourself.
There are cases where the embedded field might be more suitable, but for this question as an example I will use a case that highlights the advantages of a related table approch.
Imagine a User and Post example for a blog.
For an embedded post solution, you would have a table something like this (psuedocode - these are probably not valid ddl):
create table Users {
id int auto_increment,
name varchar(200)
post text[][],
}

With related tables, you would do something like
create table Users {
id int auto_increment,
name varchar(200)
}
create table Posts {
id auto_increment,
user_id int,
content text
}

Object Relational Mapping (ORM) tools:  With the embedded post, you will be writing the code manually to add posts to a user, navigate through existing posts, validate them, delete them etc.  With the separate table design, you can leverage the ActiveRecord (or whatever object relational system you are using) tools for this which should keep your code much simpler.
Flexibility:  Imagine you want to add a date field to the post.  You can do it with an embedded field, but you will have to write code to parse your array, validate the fields, update the existing embedded posts etc.  With the separate table, this is much simpler.  In addition, lets say you want to add an Editor to your system who approves all the posts.  With the relational example this is easy.  As an example to find all posts edited by 'Bob' with ActiveRecord, you would just need:
Editor.where(name: 'Bob').posts

For the embedded side, you would have to write code to walk through every user in the database, parse every one of their posts and look for 'Bob' in the editor field.
Performance: Imagine that you have 10,000 users with an average of 100 posts each.  Now you want to find all posts done on a certain date.  With the embedded field, you must loop through every record, parse the entire array of all posts, extract the dates and check agains the one you want.  This will chew up both cpu and disk i/0.  For the database, you can easily index the date field and pull out the exact records you need without parsing every post from every user.
Standards:  Using a vendor specific data structure means that moving your application to another database could be a pain.  Postgres appears to have a rich set of data types, but they are not the same as MySQL, Oracle, SQL Server etc.  If you stick with standard data types, you will have a much easier time swapping backends.
These are the main issues I see off the top.  I have made this mistake and paid the price for it, so unless there is a super-compelling reason do do otherwise, I would use the separate table.

A: Besides the benefits other mentioned, there is also one thing about standards. If you are working on this app alone, then that's not a problem, but if someone else would want to change something, then the nightmare starts.
It may take this guy a lot of time to understand how it works alone. And modifing something like this will take even more time. This way, some simple improvement  may be really time consuming. And at some point, you will be working with other people. So always code like the guy who works with your code at the end is the brutal psychopath who knows where you live.


text:
Q: Importing BBC Food Ontology in Protege 5.5 I'm trying to import BBC Food Ontology in Protégé version 5.5.0 and I've got the following error:

org.semanticweb.owlapi.io.OWLOntologyCreationIOException: Server returned HTTP response code: 406 for URL: https://www.bbc.co.uk/ontologies/fo/ at uk.ac.manchester.cs.owl.owlapi.OWLOntologyFactoryImpl.loadOWLOntology(OWLOntologyFactoryImpl.java:231) ...

I've also tried with the address of .ttl file https://www.bbc.co.uk/ontologies/fo/1.1.ttl and then got the following error:

org.semanticweb.owlapi.model.UnloadableImportException: Could not load imported ontology: http://www.bbc.co.uk/ontologies/provenance/ Cause: Server returned HTTP response code: 406 for URL: https://www.bbc.co.uk/ontologies/provenance

It seems that BBC Provenance Ontology which is a requirements for BBC Food Ontology couldn't be imported.
Additionaly, I've tried to import Food Ontology from the local .ttl file which was previously downloaded from the address https://www.bbc.co.uk/ontologies/fo/1.1.ttl. However, the same (above mentioned) error with Provenance Ontology occurred.

A: A 406 error means that the BBC server has checked the http headers that contain the formats that Protege would accept as a response to a GET on those URLs and it has inferred that it has no response available that fits those parameters. The accept headers set by Protege include a large number of text based formats, so I'm surprised the BBC server doesn't find at least one compatible option.
Using Accept:text/turtle in a Postman request I can obtain the turtle data from the URL; however, Protege should be including the same accept header in its request, so I cannot explain why that's not working.
Depending on the exact Protege build you're using, it's possible that it might be usong an OWLAPI version with bugs in the accept header creation. You can try and make sure you're using the latest build, or you can update the OWLAPI version Protege uses by downloading the latest owlapi-osgidistribution file (for the version 4 releases) from Maven Central and replace the owlapi bundle that's included in you Protege installation. These are drop in replacements, so if the problem is in the OWL API this might solve the issue for you.


text:
Q: example of when the likelihood function does not sum up, or integrate to $1$? Could someone please give an example of when the likelihood function does not sum up, or integrate to $1$? I have seen this question with the first answer but it really confused me - why are we integrating the likelihood function and not summing it up with the $\sum$ sign? Since it is a Bernoulli distribution (discrete). If someone could clarify my confusion and maybe provide more example(s), that would help I think.

A: The likelihood in the linked question is $$L(\theta)=P(X=x|\theta)=\theta^x(1-\theta)^{1-x}$$
Here $X$ is a Bernoulli RV, and the likelihood function is actually a probability mass function in terms of $x$. So, you can sum wrt $x$ and obtain $1$. However, likelihoods are typically for observing/estimating the parameter when the data is given, i.e. $x$'s. So, the variable in likelihood function is the parameter, i.e. $\theta$. And, since it is continuous, the answer integrates it with respect to $\theta$ and shows that it doesn't have to be $1$.


text:
Q: Deleting/Removing label widget on the window tkinter gui I have come up with a simple program that will Load Image to the window frame by clicking a button and also remove an existing one.
Problem: when I use the remove_image command it only removes the existing image leaving the label that holds it behind rather than removing the label with the image instead. Can anyone tell what I am doing wrong with my this code. please and thank you.
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
from tkinter import Label
import os
import sys
root = Tk()
root.title("Mole Tester")
root.geometry("800x500")
root.resizable(width=True, height=True)

optionframe = Frame (root, width=800, height=450, bg="light gray",
                     relief=SUNKEN)
optionframe.pack(side=BOTTOM)

load = Label(optionframe, padx=140, pady=125, bg="white", font=('Times new
             roman', 10, 'bold'), text="Import Image", relief=RAISED).place (x=10, y=10)

#Image Remove
def clear_label_image():
    brand_preview.image = None
    imagelabel.destroy()

#Image Load
def openfile():
    filename = filedialog.askopenfilename(title='open')
    return filename

def load_img():
    x = openfile()
    img = Image.open(x)
    img = img.resize((360, 270), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)
    imagelabel = Label(optionframe, width=360, height=270, image=img,
                       relief=RAISED).place(x=10, y=10)
    imagelabel.pack()

    loadbutton = Button(optionframe, padx=18, pady=1, bd=8, fg="black",
                        font=('arial', 10, 'bold'), text="Load Image", bg="gray",
                        command=load_img).place(x=18, y=320)
    removebutton = Button(optionframe, padx=30, pady=1, bd=8, fg="black",
                          font=('arial', 10, 'bold'), text="Remove", bg="gray",
                          command=clear_label_image).place(x=18, y=365)


text:
Q: Visual Basic Forms: how to make a button click interrupt a previous button click? Say i press button1 and this starts an infinite while loop. How do i make it so that if  button2 is pressed, it will pause the current action and do the code inside button2 firs before carrying on with the process in button1?

A: If the first button really is in an infinite loop, you can't. You might be able to make a button that would interrupt other code, but the event handler for that button can't ever fire because the first button is preventing your app from processing event messages.
So be careful not to create infinite (or even long-running) event handlers (of any type) on the default/UI thread.


text:
Q: Proving that a function is strictly monotonic Let $g$ be a function defined on the interval $[a,b]$ , $a,b>0$ such that: $g(x)=f(x)-kx^3$, $k>0$
--Knowing that the function $f$ defined as $|f(x)-f(y)|<k|x^3-y^3|,k>0$ is continuous prove that g is strictly monotonic on $[a,b]$
ATTEMPT :
I let $x_1,x_2\in[a,b]$ such that $x_1<x_2$ and I have to either prove that $g(x_1)<g(x_2)$ or
$g(x_1)>g(x_2)$. So: $g(x_1)=f(x_1)-kx_1^3$ and $g(x_2)=f(x_2)-kx_2^3$ and now taking the
difference of the two I got: $g(x_2)-g(x_1)=f(x_2)-f(x_1)-k(x_2^3-x_1^3)$ and since
$x_2^3>x_1^3$ then $-k(x_2^3-x_1^3)<0$ . Where I'm stuck at is determining the sign of $f(x_2)-f(x_1)$. I know that $f$ is defined to be of Lipschitz, but I don't know how that's going to help me. Thank you for any help before hand.

A: You have $x^3-y^3 = (x-y) (x^2+xy+y^2)$.
Then for $x \neq y$,  $|{f(x)-f(y) \over x-y } | < k (x^2+xy+y^2) $.
Now we have $g(x)-g(y) = f(x)-f(y) -k(x^3-y^3) = (x-y) ({f(x)-f(y) \over x-y } - k  (x^2+xy+y^2)) $.
Since $({f(x)-f(y) \over x-y } - k  (x^2+xy+y^2)) < 0$, we see that $g$ is strictly decreasing.

A: Recall that
$$|a-b|\ge|b|-|a|$$
Let $x<y$ then
$$|g(y)-g(x)|=|f(y)-f(x)-(ky^3-kx^3)|\ge k|y^3-x^3|-|f(y)-f(x)|>0$$
hence we have $g(y)>g(x)$ or $g(x)>g(y)$
Now let $$A=\{(x,y)\in [a,b]\times[a,b]\;|\; x<y\}$$
then $A$ is a connex of $\mathbb R^2$ and let the function $$h\colon A\rightarrow \mathbb R,\; (x,y)\mapsto \frac{g(y)-g(x)}{y-x}$$
then $h$ is continuous and then $g(A)$ is a connex of $\mathbb R$ hence an interval (doesn't contain $0$) hence $g$ is strictly monotone on $[a,b]$.


text:
Q: Embeded YouTube Question (Java/Scripting) First post here so let me know if something is done the wrong way, however.
I've never taken into account what it would actually take to do this, but to make a long story short, There's a section of my website that I'm creating for Class Work that I want to resemble "Rainymood.com"
RainyMood is a website in which there is a looping 30m audio file (which I have already) as well as "Daily Song Picks" that can play simultaneously with the rain ambiance to create peaceful sounds by simply attaching the youtube video you have in mind to the end of the URL
For example, changing "https://RainyMood.com" to "https://rainymood.com/watch?v=ZBrT97qJ-3w" changes the source of the embedded youtube video to play Sasuke's Theme from the Naruto OST
I've looked around for how to do this but I haven't found what I was looking for.
I have a basic understanding of Javascript but I'm not sure where to even begin with this one.

A: You can make a simple copy that's functionally similar to the one used on rainymood.com with just a few lines of HTML. All you need is an audio tag, source tag, and an iframe tag. Put your audio source in the source tag as shown, and place your embedded Youtube link in the iframe as shown.
Here's the code:
<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <audio controls loop>
       <source src="https://rainymood.com/audio1112/0.m4a" type="audio/mp4" />
    </audio>

    <iframe src="https://www.youtube.com/embed/ZBrT97qJ-3w" allowfullscreen="">.
    </iframe>
</body>
</html>

If you want to make your own audio player using Javascript, then take a look at this tutorial. Although it's for making a video player, the same concepts apply to controlling audio as well.


text:
Q: Найти число и перенести в другую часть строки Есть строка:

=1= Текст1

=2= Текст2

=3= Текст3

=2= Текст4

=1= Текст5

Нужно заменить на:

Текст1

Текст2

Текст3

Текст4

Текст5

То есть между равно предполагается идентификатор класса для легкого поиска и чтобы не путать его с другими числами в строке. Код может быть от 1 до 9. Вместо равно можно что-то другое придумать.
Возможно ли сделать такую замену с помощью replace()?

A:
\s*=(\d)=\s+(.+?)<\/p>

меняем на

$2

demo


text:
Q: Out of Stack Space & Requery Errors I've been modifying my Access DB to clean it up and make it more user friendly. As such, I've been changing the names on form labels and controls to include _lbl and _Ctrl instead of the generic names Access assigned them. Previously, I had three separate forms (ListingsForm, ListOffersForm, ListDetailsForm) that I could access by using buttons to call the form. Since the forms were directly related to the primary form (ListingsForm), I changed two of the forms into subforms. Now I keep getting errors when I try to add a record.
On the ListingsForm form, there is a control field for Property Address (Address_Ctrl). This control uses a combo box that is linked to a separate table called Properties. If the property address is not listed in the drop down box, it used to bring up the PropertyForm form to input new properties. After, it requeried to get the new list with the new record. After making the subforms and changing control names, I'm getting an error whenever I try to add a new property address.
Run-time error '2473':
The expression On Not in List you entered as the event property setting produced the following error. Out of stack space.
'Add Address Form Script
Private Sub Address_Ctrl_NotInList(NewData As String, Response As Integer)
    DoCmd.OpenForm "PropertyForm", , , , acFormAdd
    Call Address_Ctrl_AfterUpdate
End Sub

'Requery Address List Script
Private Sub Address_Ctrl_AfterUpdate()
     Forms!MLSListForm.Dirty = False
     Me!Address_Ctrl.Requery

End Sub

It highlights the Forms!MLSListForm.Dirty = False line. I've tried Me.Dirty = False but I get the same error. If I remove the line entirely, I get 'Run-time error '2118': You must save the current field before you run the Requery action.'
Having the forms as subforms helps with user-interface so I really do not want to go back to having three separate forms. Any help would be appreciated.

A: Normally, your comment Address_Ctrl_AfterUpdate() event handler,
And you can try this event handler:
Private Sub Address_Ctrl_NotInList(NewData As String, Response As Integer)
'
' add in Properties tables for NewData:
'   By calling SQL Server via ADO:
'   INSERT INTO Properties (City) (NewData)...
' Or
'
'
' Now NewData Exists, do this:
'....
' and then set new value and status:
'
   Response = acDataErrAdded
'
' here you can then modify new city:
'
  DoCmd.OpenForm "PropertyForm", , , "City='" & NewData & "'", acFormPropertySettings
'
End Sub

I've re-debugged in our Access Database VBA, with Response = acDataErrAdded,
Access will Requery automatically Address_Ctrl.Requery() After the Address_Ctrl_NotInList() returns.

A: So I finally got it working correctly. Turns out I had to set some default values for the controls in the form design. After that, it worked out just fine.