text:
Q: Backbone Collection garbage collection stopped by jquery ajax callbacks I've been messing with Chrome Heap profiler and some basic Backbone objects just to get an idea of garbage collection. I ran into some curious and confusing behavior.
Using a base page that has only jquery-1.7.2,underscore-1.3.3, and backbone-0.9.2 loaded.
If I run the following code from a Chrome (win/19) js console window the collection will  not be garbage collected. In the heap profiler, 'Object's retaining tree' it will list the 50 users and the circular references between the models and the collection, but it will also list 2 that say b in function() @234234. Expanding out those references the references look to be from jQuery's ajax callback handlers.
(function () {
    var collection = new Backbone.Collection();
    collection.url = '/api/users/';
    collection.fetch();

    setTimeout(function wtf() { $('#content').append($('
' + collection.models[0].get('name') + '
')); }, 3000);
})()

If I run the following code the collection will be properly garbage collected as expected. The difference is the last line where I make some random ajax call that seems to shift the jQuery ajax callbacks off the collection.
(function () {
    var collection = new Backbone.Collection();
    collection.url = '/api/users/';
    collection.fetch();

    setTimeout(function wtf() { $('#content').append($('
' + collection.models[0].get('name') + '
')); }, 3000);

    $.ajax({ url: '/api/users/' });
})()

Is this expected behavior or a bug or what? It'd suck if I have random objects hanging around because they had done ajax requests in the past.
Update: so I was testing this further and it appears to only affect the first or second instances. If I create a setinterval that creates a new collection and calls fetch every 1 second the first 1-2 instances created will remain in memory indefinitely (20min+) while all other instances created will be disposed properly.
If I call jquerys Ajax function and in the success handler hand the data to the new collection as a parameter at creation this behavior does not occur at all. All instances created are cleaned up properly.
It appears that the function Backbone.wrapError is part of the problem along with the wrapping of success.


text:
Q: Add supplementary information to error message I have tried to write a method that takes an error and returns it the same but with an exclamation mark added to the end of the message but there was a problem with the fact that the errors in java are immutable and because of limitations of generics its impossible to create new instance of error
by using new T(e, message) :
public static <T extends Throwable> T withExclamationMark(T error) {
    return new T(error.getMessage() + "!", error);
}

Is there any simple solution which doesnt require reflection etc?

A: You can do it with a BiFunction:
public static <T extends Throwable> T withExclamationMark(
        T error,
        BiFunction<String, T, T> factory) {

    return factory.apply(error.getMessage() + "!", error);
}

Then, you can use this method as follows:
RuntimeException original = new RuntimeException("Message");

RuntimeException decorated = withExclamationMark(original, RuntimeException::new);

System.out.println(decorated.getMessage()); // Message!

A: public static void main(String[] args) throws Exception {
    Throwable t = new Throwable("my message");
    Throwable t2 = withExclamationMark(t);
    t2.printStackTrace();
}

public static <T extends Throwable> T withExclamationMark(T error)
             throws Exception {
    Constructor c = error.getClass().getConstructor(String.class,
                                        Throwable.class);
    return (T) c.newInstance(error.getMessage() + "!", error);
}

A: If you want to aviod reflection at all costs, you will have to pay for this. The presented solution will sacrifice precision w.r.t. the type of the Throwable. To append something to the message, we will wrap the given Throwable in an Exception by deploying the constructor Exception(String, Throwable)
public static <T extends Throwable> Exception withExclamationMark(T t) {
    return new Excpetion(t.getMessage() + "!", t);
}

As I already mentioned, this method only returns instances of the class Exception, thus when you try to catch those Exceptions, you would have to check the cause:
try {
    ...
} catch (Exception e) { // let's assume you would normally catch an IOException here
    Exception cause = e.getCause();
    if ((cause != null) && (cause instanceof IOException) {
        IOException ioEx = ((IOExcpetion) cause);
        // handle excpetion
    } else {
        throw e; // or System.exit(42) or halt and catch fire or ...
    }
}

For a solution deploying reflection, please see @sanit's answer. Maybe a combination of both answers could lead to a satisfying solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to reduce document reads for Firestore I am using Firestore (I am new to this) for small web application. Currently, each time when I refresh or go to another page, the function retrieves all the documents in the Firestore. But the data that it retrieves does not change often,
Is there a way for me to retrieve all the data that will cost me little to no document reads?
I am currently using these function to retrieve the data
firebase
.firestore()
.collection("products")
.then((snapshot) => {
       snapshot.forEach((docs) => {
       });
});

firebase
.firestore()
.collection("products")
.where("prodID", "==", prodID)
.then((snapshot) => {
       snapshot.forEach((docs) => {
       });
});

A: It depends on your app.
But a way to reduce it would be to retrieve them from the cache.
According to the docs (https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Source) you can do something like
function getData() {
   firebase
   .firestore()
   .collection("products")
   .get({source: "cache"})
   .then((snapshot) => {
         if (!snapshot.exist) return getServerData()
         snapshot.forEach((docs) => {
       });
  });
}

function getServerData() {
   firebase
   .firestore()
   .collection("products")
   .get()
   .then((snapshot) => {
         snapshot.forEach((docs) => {
       });
  });
}


text:
Q: Coverting roman numeral exceptions to decimal For some class homework I need to create a program that converts roman numerals to decimal form. I can convert just fine as long as there are no exception characters such as IV or IX. How do I check for these exceptions? My attempt was to translate both the current character and the next one into decimal, then to compare them and if the next one (going right to left) is smaller to then subtract it. The problem is that I get out of bounds errors from this.
My current code is this:
Scanner keyboard = new Scanner(System.in);
    String roman;
    int decimal = 0;
    int number = 0;

    System.out.print("Enter a Roman Numeral to convert to decimal form: ");

    roman = keyboard.next();
    roman = roman.toUpperCase();

    for (int count = roman.length()-1; count >= 0; count--)
    {
      char numeral = roman.charAt(count);
      switch (numeral){
        case 'I':
        decimal = 1;
        break;
        case 'V':
        decimal = 5;
        break;
        case 'X':
        decimal = 10;
        break;
        case 'L':
        decimal = 50;
        break;
        case 'C':
        decimal = 100;
        break;
        case 'D':
        decimal = 500;
        break;
        case 'M':
        decimal = 1000;
        break;
        default:
        System.out.println("Error: Invalid character detected.");
        break;
      }
      number = number + decimal;
    }

    System.out.println("The decimal equivalent is: " + number);
    System.out.println("Later!");

I'm still a beginner and most of the information I see on this kind of problem uses advanced solutions that I simply don't understand. I know I need to compare the characters but I'm not sure how to do this in a way that won't eventually go out of bounds.
EDIT: Solved! After posting the question I was struck by insight and solved the problem myself. This code works but I would appreciate any insights into how to improve it!
Scanner keyboard = new Scanner(System.in);
    String roman;
    int decimal = 0;
    int number = 0;
    int last = 0;

    System.out.println("This program converts Roman Numerals to decimal form.");
    System.out.println("Note: Roman Numerals are I, V, X, L, C, D and M.");
    System.out.println("All letters entered will be treated as capitalized.");
    System.out.print("Enter a Roman Numeral to convert to decimal form: ");

    roman = keyboard.next();
    roman = roman.toUpperCase();

    for (int count = roman.length()-1; count >= 0; count--)
    {
      char numeral = roman.charAt(count);
      switch (numeral){
        case 'I':
        decimal = 1;
        break;
        case 'V':
        decimal = 5;
        break;
        case 'X':
        decimal = 10;
        break;
        case 'L':
        decimal = 50;
        break;
        case 'C':
        decimal = 100;
        break;
        case 'D':
        decimal = 500;
        break;
        case 'M':
        decimal = 1000;
        break;
        default:
        System.out.println("Error: Invalid character detected.");
        System.exit(0);
        break;
      }
      if (decimal >= last){
      number = number + decimal;
      }
      else {
      number = number - decimal;
      }
      last = decimal;
    }

    System.out.println("The decimal equivalent is: " + number);
    System.out.println("Later!");

A: Well, a decimal is ##.##, and an integer is ##, so you should probably change demical to num.
Set the number as you already do, and add a check after it for the exception character. But first ensure that it exists:
if(this character is not the first  &&  the previous character is an exception)
   adjust the number as necessary

This will avoid an out-of-bounds exceptions.


text:
Q: Convert mysqlcodes to mysqli Is it usefull to convert all my PHP codes from mysql to mysqli?
I mean will mysql be deleted? And is there a tool that converts my codes to mysqli? Or do I just have to change all i.e. mysql_query to mysqli_query?

A: Is it useful?
Yes, read Why shouldn't I use mysql_* functions in PHP? So if you plan on running your code in years to come, you should consider it.
Is there a tool?
This tool if often mentioned but I have never tried it and I think you would learn more by doing it manually. It also seems more complicated than doing it by hand if you're a beginner.
Changing all your mysql_query() function calls to mysqli_query() is not enough. The mysqli_query function requires that you pass a link identifier as the first argument wheareas with mysql_query "If the link identifier is not specified, the last link opened by mysql_connect() is assumed."
And of course it's not just the mysql_query calls you would have to change, but all mysql_* calls.


text:
Q: Vue - adding a Class-Name to a Component using a prop I would like to make a custom component in Vue with the following props:

*

*text = text to be displayed in the link.

*icon = identifier of the icon to be displayed next to the link.

< sidebar-link text="Home" icon="fa-home">

I have the following .Vue template for my component.
<template>

{{ text }}

</template>

Essentially I have the default Font-Awesome code in my template:

and I want add a class to my component by using it's prop.
<sidebar-link text="Home" icon="fa-home"></sidebar-link>

thanks.

A: If you want to add fa-home to your  you can pass it on the parent component like:
<sidebar-link text="Home" :icon="'fa-home'"></sidebar-link>

You can pass other icons like fa-plus, fa-blutooth .... instead
And use it inside your component as:

tbh: makes a little sense for me why you need to keep fa
You still need a prop maybe with default value of '' though
icon: {
  type: String,
  required: false,
  default: ''
}

A: So when your property icon is holding the value home you can use some class binding like the following (Thank god js expression are allowed within attributes in Vue.js):
v-bind:class="[{'fa': true}, icon ? 'fa-' + icon : '']"

or even shorter
:class="[{'fa': true}, icon ? 'fa-' + icon : '']"

This will result in
class="fa fa-home"


text:
Q: Is there a way to support schema evolution in avro4s Is there a way to read bytesArray via the AvroInputStream.binary api
and somehow specify the writer version ?
val in = new ByteArrayInputStream(bytesFromFile)
val input = AvroInputStream.binary[newClass](in)// old ?
val result = input.iterator.toSeq

in other words is avro4s support schema evolution with binary records ?

A:
Does avro4s support schema evolution with binary records?

No. Avro in general supports Schema Evolution when you provide it a schema, it can match against the name of the properties and their types. When there's no schema, it relays on the order of declarations both the serializing and deserializing side. If you modify your classes, you break compatibility.


text:
Q: insertion in linked list - I was reading Skeina's book. I could not understand this code. Basically what is the use of double pointer. And what is the use of *l = p? Can anyone please explain by diagram.
void insert_list(list **l, item_type x) {
    list *p; /* temporary pointer */
    p = malloc(sizeof(list));
    p->item = x;
    p->next = *l;
    *l = p;
}

A: You shouldn't call it a "double pointer" because that would be a pointer to a double.  It is a pointer to a pointer, and it is used to allow the function to alter the value of an argument which happens to be a pointer.  If you're familiar with C#, it's like an out argument.  In this situation the l argument used to get both IN and OUT behavior, but you may often see this used for output only.
Since this function returns type void it very well could have been written without the use of the pointer to a pointer like this:
list * insert_list(list *l, item_type x) {
{
    list *p; /* temporary pointer */
    p = malloc(sizeof(list));
    p->item = x;
    p->next = l; // note that this is not *l here
    return p;
}

This change would require the code that calls the function to update it's own handle to the list since the head of the list is what's being changed.

A: This function performs a very simple task: it inserts a list node at
the position for which it receives a pointer.  There is nothing
special about double pointers, they are just pointers to pointers.  They hold the address of a pointer, which contains the address of an object.
void **l contains the address of a list * pointer. *l retrieves
this address and *l = p stores it.
malloc is used to allocate a
list structure, p receives the address of the allocated structure.
The code is somewhat sloppy as p is not checked for NULL before
dereferencing it.  If malloc fails because of lack of memory, the
program will invoke undefined behaviour, hopefully stopping with a
segmentation fault or something potentially worse.
The node is initialized, its next pointer is set to the node pointed
to by the l argument, and finally the new node's address is stored
at the address passed as the l argument.  The effect is simple: the node is inserted at *l.
This method is clever ad it allows the same function to insert a new node anywhere is a list. For example:
list *head = NULL;
...
/* Insert a LIST_A node at the beginning of the list */
insert_list(&head, LIST_A);
...
/* insert a LIST_B element as the second node in the list */
insert_list(&head->next, LIST_B);
...
/* find the end of the list */
list *node;
for (node = head; node->next; node = node->next)
    continue;

/* insert a LIST_Z node at the end of the list */
insert_list(&node->next, LIST_Z);

The only tricky thing above is the concept of pointer itself, here is a simple overview:

*

*Memory can be conceptualized as a (large) array of bytes, addresses are offsets in this array.

*char variables by definition are single bytes,

*int variables occupies a number of bytes specific to the architecture of the system, typically 4 or 8 bytes in current hardware.

*Think of pointers as variables holding the address in memory of another variable. They need to be large enough to hold any valid address in the system, in current systems with more than 4 GB of physical and addressable memory, they are 64 bit long and occupy 8 bytes.

*There is a special address value NULL which represents no object and is used to specify that a given pointer does not point to any real object. The address 0 is used for this purpose. malloc will return NULL if it cannot allocate the memory requested, the return value should be tested, as storing a value at this address is forbidden and usually caught as an invalid access (segmentation fault).

This summary is purposely simplistic.  I used the term variable instead of object to avoid the confusion with OOP concepts.


text:
Q: A nonconstant doubly periodic function cannot be analytic I have been stuck on this problem for a long time:

A non constant $F(z)$ is such that $F(z+a)=F(z)$ and $F(z+bi)=F(z)$ where $a>0 $ and $b>0$ are given constants. Prove that $F(z)$ cannot be analytic in the rectangle $\{(x,y) : 0<x<a , 0<y<b \}$.

The problem is  under the section of Liouville's theorem: a bounded entire functions is constant. But how to apply this to a rectangle?

A: The problem as stated is false. As a counterexample, consider the function
$$
F(z)=\begin{cases}
1, & z=an + bmi\ \text{for}\ n,m\in \mathbb Z\\
0, & else.
\end{cases}
$$
It is analytic in the rectangle $(0,a)\times (0,b)$, because it is identically $0$ there. Also it is periodic as required.

A: The function can be extended on the whole plane as follows:
$$
G(z+na+imb) = F(z) \qquad n,m\in \mathbb Z
$$
to get an analytic bounded function.
added. The resulting function is bounded because it is periodic, hence its range $G(\mathbb C) = G(R) = F(R)$ where $R=[0,b]\times [0,b]$ is the given rectangle, and being $R$ compact and $F$ continuos, $F(G)$ is compact hence bounded. The resulting function is analytic because an analytic function in a point is uniquely determined by the values on a sequence of approximating points. Hence if $F$ is analytic and $F(z)=F(z+a)$ for some point $z$ in the left side of the rectangle, the extension in $F(z+a)$ coincides with the extension inn $F(z)$.
By Liouville Theorem the extended function is bounded and so must be the original function...
note. I assume that the function is analytic on the closed rectangle, which means that there is an open set containing the rectangle where the function has an analytic extension.


text:
Q: AWS S3 Stop Download Image automatically when browsed via URL I am uploading images to my S3 bucket via my Node.js Application. I have the following bucket policy.
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowPublicRead",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::bucket_name/*"
    }
  ]
}

When I go to the link of the file lets say its an image. It automatically downloads as a file and does not render in the browser. Any idea how to make it display in the browser without automatically force downloading the image in the browser?

A: Explicitly set the Content-Type of the object with image/<appropriate-subtype>.
var params = { Bucket: '', Key: '', ContentType: 'image/png',  ... }

The default Content-Type would be application/octet-stream, thus instead of rendering in the browser it is being downloaded.


text:
Q: Using Residue theorem to evaluate the integral Using Residue theorem to evaluate the integral:
$$\int_0^{\infty} \frac{x^2}{x^4 + 5x^2 +6}dx$$
I am using partial fraction to get:
$$\int_0^{\infty} \left( \frac{3}{x^2 +3} - \frac{2}{x^2+2} \right)dx$$
Then, next step, can someone show me how to use Residue theorem to evaluate the integral.

A: You just use partial fraction expansion again, for each of the quadratic terms.  We have
$$\frac{1}{x^2+3}=\frac{1}{i2\sqrt{3}}\left(\frac{1}{x-i\sqrt{3}}-\frac{1}{x+i\sqrt{3}}\right)$$
and
$$\frac{1}{x^2+2}=\frac{1}{i2\sqrt{2}}\left(\frac{1}{x-i\sqrt{2}}-\frac{1}{x+i\sqrt{2}}\right)$$
Can you finish from here?
SPOLIER ALERT:  SCROLL OVER THE SHADED AREA TO SEE THE REST OF THE ANSWER

First we note that the integrand is even and therefore we can write the integral of interest $I$ as $$I=\int_0^{\infty}\frac{x^2}{x^4+5x^2+6}dx=\frac12\int_{-\infty}^{\infty}\frac{x^2}{x^4+5x^2+6}dx$$  Next, we move to the complex plane and analyze the integral $$\oint_{C}\frac{z^2}{z^4+5z^2+6}dz$$where $C$ is the contour in the upper-half plane comprised of the real-line segment from $x=-R$ to $x=R$ and the semi-circle with radius $R$ and centered at the origin.  Using the Residue Theorem, we have $$\oint_{C}\frac{z^2}{z^4+5z^2+6}dz=2\pi i \left(\frac{-2}{2i\sqrt{2}}+\frac{3}{2i\sqrt{3}}\right)=\pi(-\sqrt{2}+\sqrt{3}) $$ Notice that as as $R$ goes to infinity, the contribution from the integral over $C_R$ vanishes while the integral over the real line segment is equal to twice the integral of interest as $R\to \infty$.  Therefore, we have $$I=\frac{\pi}{2}(\sqrt{3}-\sqrt{2})$$


text:
Q: Disabling the Cache - chrome I am making changes to my MERN app (on my mac).
Each time, I save, restart the server, and expect the changes to be recognised. A change could be a simple as adding another letter to a label in the html (although what i really want to see is changes to the CSS).
However, the typing changes aren't reflected when I render localhost 3000. I can't understand why. I have disabled the cache in the network tab on chrome. I can't figure out why these changes aren't populating. This is true even if I restart my computer.
How can I get the server restart to pick up changes?


text:
Q: Java Web Application Return Error HTTP 404 Not Found I am learning java with netbeans . I build web application for insert, update and delete operation. but when i run the application its always returns error 404 not found .
Here is the HTML Code that i want to run .
<!DOCTYPE html>

        <title>Add New</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Add New

            <form action="JSP/ManagerAddNew.jsp" method="post">
                Title:

                <input type="text" name="title" style="width: 200px">

                Description:

                <input type="text" name="description" style="width: 200px">

                Detail:

                <textarea name="detail" style="width: 400px; height: 200px"></textarea>

                Category:
                <select name="category">
                    <option value="World">World</option>
                    <option value="Tech">Tech</option>
                    <option value="Sport">Sport</option>
                </select>

                Image:

                <input type="text" name="image" style="width: 200px">

                <input type="submit" value="Submit">
            </form>

Here is the screen shot of the error message .

Here is my project structure .

Here is the screen of the server and the application has been deployed .

A: i don't know about GlassFish Server,but tomcat.
A JSP file under WEB-INF folder can't be visit by URL directly,you can visit it like this:
request.getRequestDispatcher("/WEB-INF/xxx.jsp").forward(request,response);

I'm not sure this way can solve the question under GlassFish,hope it can help you.

A: Whenever I have an error of this type, i have to reinstall the glassfish module.


text:
Q: Splitting a git repo at a commit hash and merge it later (rewrote the question with more context)
We are moving from Perforce to Git (likely GitLab). We have 1 repo. We don't want to carry our 25+ years of history to GitLab as it is pretty huge even after trimming off binaries. But developers would like to be able to seamlessly look at the history of a file across several commits and this would be lost if they only had access to the latest revision.
I am using git-p4 to migrate to a local git repo first.

*

*I can get the head revision only using git p4 --use-client-spec //depot .
If I push this to GitLab I get the single commit based on the head revision in Perforce.

*Or I can migrate along with certain amount of history in perforce as individual commits into git using _git p4 --use-client-spec //depot@4,6
If I push this into GitLab I get 3 commits.
Assuming commits (hashes) like for the full history of the repo:
6666
5555
4444
3333
2222
1111
If I followed #2 above, I would have commits 4444,5555,6666 in my local git repo and I can push these to GitLab as my active_source repo.
I could then create a new local repo with 1111,2222,3333 and push to GitLab as my archive_source repo.
All developers will check out the active_source repo and work on that. But some would need also the history in archive_source repo.
Can they somehow pull active_source repo on top of archive_source so that they can see the history all the way from 6666 to 1111 ?
All examples I found were about splitting the repo "along the length", but not at a certain commit and be able to stitch it back together for history.
Thank you,
-Sachin

A: I found an excellent blog post and the actual source in the git book to solve this issue. Instead of merely posting links to those I am now expanding the answer.
We basically split the history at a specific hash. Both historical and current will have the common hash (3333 in this example). Then we squash the current upto the parent of the common hash and discard the parents in the current.
This is done by a rebase and the parent of the common hash is a newly generated free-floating commit that we attach the current to. Historical and current can then be 2 different repos saved independently.
To put these together and view the total history, if needed, we knock off the new parent of the common hash and use git-replace to attach to the historical.
Steps

*

*We branch the repo at the hash 3333

git branch archive_source 3333

*Push it to remote

git init /users/myusername/historical_src
git add remote history /users/myusername/historical_src
git push history archive_source:main

*Now we squash the history of the "current" branch

> git commit-tree -m "For historic commits, run 'git replace <child-ID> > 3333'" "3333~^{tree}"
12345abcdf67890ghijk  << returned commit hash

*Now we rebase the current source onto this squashed commit hash. This will rewrite the hashes of the current repo (rewrite its history)

> git rebase 3333~ --onto 12345abcd  --rebase-merges

Done! You can check that the history is truncated by running git log
Now to reassemble at the developers machine:

*

*Fetch the archive data

> git remote add historical /users/myusername/historical_src
> git fetch historical

*Setup a branch:

> git branch history historical:main

*Connect the current and history together by replacing the common commit between the two.

> git replace 9876a 3333

The cleanup etc

> git replace -d 9876a
> git branch -d history
> git remote remove historical

I found the answer and a clear explanation in a recent article that I came across:
https://andrewlock.net/reducing-the-size-of-a-git-repository-with-git-replace/
This is based on: https://git-scm.com/book/en/v2/Git-Tools-Replace


text:
Q: What causes this \endcsname error? I am a beginner to LaTeX, and I don't understand what's going wrong here. I didn't change anything, and all of a sudden, the code won't run. Can you please help me?
) (./Final_Halper_410Latex.aux
! Missing \endcsname inserted.
<to be read again>
                   \protect
l.22 \@writefile
                {toc}{\contentsline {section}{\numberline {II}Methods}{2}{}}
?

The relevant lines of code are as follows:
\pdfoutput=1 % For pdflatex
\documentclass[aps,prd,floatfix,nofootinbib,twocolumn]{revtex4-1}

\usepackage{graphicx}% Include figure files
\usepackage{amsmath}
\usepackage{caption}

%Uncomment the two lines below if you are using BibTex
%\bibliographystyle{apsrev4-1}
%\renewcommand*{\bibfont}{\raggedright} %Removes strange justification problems in bibliography when using Bibtex and Revtex 4-1

\begin{document}
.
.
.
\section{Methods}


text:
Q: Why is xml.etree.ElementTree considered insecure? According to Creating a simple XML file using python, one of the simplest ways to generate an XML file in Python is to use Python's built-in ElementTree XML API.
However, the Python 3 documentation includes the following warning:

Warning: The xml.etree.ElementTree module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.

I had planned on using the ElementTree library to construct XML requests with user-inputted attribute values. However, I am now concerned about the security of my application.
For example, my application has a logon() function with arguments for a user-inputted username and password. These values are then used as XML attributes.
import xml.etree.ElementTree as ET

def logon(username, password):
    # Create XML logon request for external webservice
    root = ET.Element("xml")
    body = ET.SubElement(root, "Logon")
    body.set("Username", username)
    body.set("Password", password)

    return ET.tostring(root, encoding="UTF-8", method="xml")

Why is xml.etree.ElementTree considered insecure? Is it safe to use with user-defined XML attribute values?

A: According to the section 20.4.1. XML vulnerabilities of the Python documentation, xml.etree.ElementTree is vulnerable to the Billion Laughs attack and to the quadratic blowup attack.

billion laughs / exponential entity expansion
The Billion Laughs attack – also known as exponential entity expansion – uses multiple levels of nested entities. Each entity refers to another entity several times, and the final entity definition contains a small string. The exponential expansion results in several gigabytes of text and consumes lots of memory and CPU time.
quadratic blowup entity expansion
A quadratic blowup attack is similar to a Billion Laughs attack; it abuses entity expansion, too. Instead of nested entities it repeats one large entity with a couple of thousand chars over and over again. The attack isn't as efficient as the exponential case but it avoids triggering parser countermeasures that forbid deeply-nested entities.

As long as you don't parse maliciously crafted XML, you are safe.


text:
Q: how do i get index of an object in a custom class? I'm trying to an indexof method for a class that represents a list of objects.I would like to know the best approach. below is the code that I've come up with.
public int IndexOf(Product product)
    {

            Product p;
            for (int i = 0; i < products.Count; i++)
            {
                p = products[i];

                if (p == product)
                    return i;
            }
        return -1;
    }

A: If products is of type List<Product> you can just use the IndexOf() method of your collection:
public int IndexOf(Product product)
{
   return products.IndexOf(product);
}

A: I couldn't get .IndexOf() working for my problem, but I found the following solution worked a treat.
How to use IndexOf() method of List<object>


text:
Q: Path to location of npm run call I have a node script sitting at project/bin/index.js, and I added its execution command to package.json:
scripts: {
  "exec": "cd ./bin && npm -i --silent && node index.js"
}

I'm now able to run my node script from any location inside my project. The thing is that I want to do something depending on where I run this script, so I want to be able to get there the path telling from where I'm running my npm run exec. Is it possible? How can I do this?
__filename, __dirname, and process.cwd() return script path - project/bin.

A: It doesn't look like you can do this directly through npm scripts. My guess is that npm cds to the project directory before running the command (as also evidenced by the fact that you can do cd ./bin or node bin/index.js). Yarn won't even let you run a command unless you are in the same directory as package.json.
"scripts": {
  "exec": "npm i --silent && node bin/index.js $PWD"
}

index.js
console.log({
  __filename,
  __dirname,
  cwd: process.cwd(),
  execPath: process.execPath,
  pwd: process.env.PWD,
  argv: process.argv
});

shell env
Jasons-MBP-2:some-dir jason$ env
PWD=/Users/jason/Development/so/npm-run/some-dir

run
Jasons-MBP-2:some-dir jason$ npm run exec

> npm-run@1.0.0 exec /Users/jason/Development/so/npm-run
> npm i --silent && node bin/index.js $PWD

result
{ __filename: '/Users/jason/Development/so/npm-run/bin/index.js',
  __dirname: '/Users/jason/Development/so/npm-run/bin',
  cwd: '/Users/jason/Development/so/npm-run',
  execPath: '/Users/jason/.nvm/versions/node/v6.10.0/bin/node',
  pwd: '/Users/jason/Development/so/npm-run',
  argv:
  [ '/Users/jason/.nvm/versions/node/v6.10.0/bin/node',
    '/Users/jason/Development/so/npm-run/bin/index.js',
    '/Users/jason/Development/so/npm-run' ] }


text:
Q: ModuleNotFoundError: No module named '_pywrap_tensorflow' erro windows 10 I am trying to install Keras with Tensorflow. I have followed all steps from
here
I have installed CUDA 9 . cuDNN 7.i had problems intalling it with command provided on the site so i used
python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl

which i have found here on SO. Installation went fine, however when i tried test script ( provided on the tensorflow site ) i recieved error:

No module named '_pywrap_tensorflow

I have tried to check SO for answer but found nothing usefull, how can fix this?
thanks for help.

A: Regarding your issues you are installing cpu only and old MAC version of tensorflow which shouldn't work on windows.
You could try using the following command
python3 -m pip install https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-0.12.0-cp35-cp35m-win_amd64.whl

But I suggest you use Anaconda for the windows to install tensorflow and keras it has much less errors on windows, you can find a guide for it here https://github.com/antoniosehk/keras-tensorflow-windows-installation.


text:
Q: Traducir un SweetAlert2 sin refrescar la página (Javascript) Tengo este código Javascript dónde puedo cambiar traducir mi página sin necesidad de recargar:

var strings = {
    espanol: {
        lang: "Idioma",
        texto1: "Hola!"
    },
    english: {
        lang: "Language",
        texto1: "Hi!"
    }
}

$( ".espanol" ).on( "click", function() {
    localStorage.setItem("lang", "espanol");
    localizeStrings('espanol');
});
$( ".english" ).on( "click", function() {
    localStorage.setItem("lang", "english");
    localizeStrings('english');
});

var Lang = localStorage.getItem("lang") || "english";
localizeStrings(Lang);
function localizeStrings(strLang) {
    $(strings[strLang]).each(function(key, lang){
        $.each(lang, function(id, string) {
            $("#"+id).html(string);
        });
    });
}

<button type="button" id="lang">Idioma</button>

Hola!

Y dentro de otro archivo Javascript tengo un código que al terminar un proceso, saltaba un alert que reemplacé por un SweetAlert2:
Swal.fire({
  text: "Algo está mal!",
  icon: "warning",
  buttonsStyling: false,
  confirmButtonText: "Entiendo",
  customClass: {
    confirmButton: "btn btn-warning"
  }
})

Quiero saber si hay forma de traducir el SweetAlert sin refrescar simplemente asignando de alguna manera un ID y de ahí poder tomarlo con mi código ya mencionado?
Quiero traducir del sweetalert: text: "Algo está mal!", y el texto del botón: confirmButtonText: "Entiendo",
Muchas gracias de antemano.

A: Agrega las cadenas necesarias en el objeto:
let strings = {
    espanol: {
        lang: "Idioma",
        texto1: "Hola!",
        alertTxt: 'Algo está mal',
        alertBtn: 'Entendido'
    },
    english: {
        lang: "Language",
        texto1: "Hi!",
        alertTxt: 'Something is wrong',
        alertBtn: 'Got it'
    }
};

Crea una función para obtener la cadena a traducir:
function translate(str) {
    if(!strings.hasOwnProperty(Lang) || !strings[Lang].hasOwnProperty(str)) {
        // El idioma o la cadena a traducir (propiedad) no existe
        return str;
    }
    // Devolver traducción
    return strings[Lang][str];
}

Después usas la función para traducir las cadenas al crear la alerta, así no tienes que modificar elementos HTML que, por cierto, solo existen cuando se muestra la alerta:
Swal.fire({
  text: translate('alertTxt'),
  icon: "warning",
  buttonsStyling: false,
  confirmButtonText: translate('alertBtn'),
  customClass: {
    confirmButton: "btn btn-warning"
  }
});


text:
Q: List all packages on a Gentoo system, which were not recompiled since a date A system change (like gcc, perl, python, qt... update) can demand that many packages have to be rebuilt.
This ends often in a world rebuild with
# emerge --ask --emptytree --verbose @system
# emerge --ask --emptytree --verbose @world

In a world rebuild with 2000 packages it is likely, that the merge failed for tens or hundreds and one has to fix the problems.
Technically one could rebuild the world after fixing the problems, but this takes very long.
How can I list all packages which have not been successfully rebuilt since the day $DATE?
What I tried so far:
# create a sorted list with all packages built till $DATE=2017-05-30
qlop -ld 2000-01-01 -d $DATE | cut -d ">" -f 4 | sort

But this list contains

*

*all versions and not only the latest one

*packages which were removed from the system

*packages which have been rebuilt successfully after $DATE

A: Emerge eix
Then
eix-update
eix '-I*' --format '<installedversions:DATESORT>' | sort -n | cut -f2-3

will give you a list of installed packages (with slots if necessary), sorted by installation date. e.g.:
...
 15/11/17 12:34:51       net-misc/rsync
 15/11/17 12:35:29       dev-libs/libuv
 15/11/17 12:35:58       app-editors/vim-core
 15/11/17 12:36:32       dev-python/pycairo
 15/11/17 12:37:17       app-editors/vim
 15/11/17 12:37:49       dev-util/eric
Save this to a file, remove all packages emerged after your cutoff date, edit out the timestamps, and you have the list of packages to re-emerge


text:
Q: Datagridview cell decimale fromat during editing in c# window form I am creating an application in C# windows form and want to datagridview cell format as decimal like 0.00 during editing in datagridview cell. Given below event is helping me for this purpose but when i editing in new row then this generate an error "Additional information: Object reference not set to an instance of an object."
event is given below
 private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{

    if (e.ColumnIndex == 0 && e.RowIndex != this.dataGridView1.NewRowIndex)
    {
        double d = double.Parse(e.Value.ToString());
        e.Value = d.ToString("0");
    }
    if (e.ColumnIndex == 5 && e.RowIndex != this.dataGridView1.NewRowIndex)
    {
        double d = double.Parse(e.Value.ToString());
        e.Value = d.ToString("0.00");
    }
    if (e.ColumnIndex == 6 && e.RowIndex != this.dataGridView1.NewRowIndex)
    {
        double d = double.Parse(e.Value.ToString());
        e.Value = d.ToString("0.00");
    }
}

Please help me to resolve the issue.

A: Try this:
double d = (double)e.Value;

casting e.value to a double.
This page: https://msdn.microsoft.com/en-us/library/system.windows.forms.converteventargs.value(v=vs.110).aspx
suggests that that you check the DesiredType property before accessing the value:
if(e.DesiredType != typeof(string)) return;

A: private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{

    if (e.ColumnIndex == 0 && e.RowIndex != this.dataGridView1.NewRowIndex)
    {
        double d = double.Parse(e.Value.ToString());
        e.Value = d.ToString("0");
    }

    else
    {
        if (e.ColumnIndex == 2 && e.RowIndex == this.dataGridView1.NewRowIndex)
        {
            double precio = Convert.ToDouble("0");
            dataGridView1["Column7", e.RowIndex].Value = (precio.ToString());
        }
    }

}


text:
Q: Is there a way to make current class point to the new object that has just been read in Java Serializable? I am trying to read an object for a SocialNetwork Simulation. The read methods makes use of Java Serializable. The code looks like this:
public class SocialNetwork  implements Serializable{

// lots of fields

public SocialNetwork(){
//lots of inilization
}
    public void writethisObject() throws IOException{
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("Simulation.bin"));
            objectOutputStream.writeObject(this);
        }

        public void readfromObject(File f) throws IOException, ClassNotFoundException{
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(f));
            SocialNetwork newSocialNetwork = (SocialNetwork) objectInputStream.readObject();
            this = newSocialNetwork;
        }

}

However as you can see I am trying to make the current class point to the object that I just read by making this = newSocialNetwork. This gives me an error as expected. I can work around this by making each and every field of the current SocialNetwork class to the newSocialNetwork. However, I do not want to do that as there are tons of field in my class. And it would look very messy. I hope you have got the idea of what I am trying to do.

A: Since you cannot override this in Java and you want to have only one instance of your class use a Singelton Pattern:
public class SocialNetwork  implements Serializable{
    // lots of fields

    private static SocialNetwork myself = new SocialNetwork();

    private SocialNetwork(){ // private constructor
        //lots of inilization
    }

    public static SocialNetwork getInstance() {
        return myself;
    }

    public void writethisObject() throws IOException{...}

    public void readfromObject(File f) throws IOException, ClassNotFoundException{
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(f));
        myself = (SocialNetwork) objectInputStream.readObject();
    }

}

A: You can't do that, but instead you can declare a static method.
 public static SocialNetwork readfromObject(File f) throws IOException, ClassNotFoundException{
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(f));
            return (SocialNetwork) objectInputStream.readObject();

        }

A: We can use Singelton Pattern to achieve. Classes outside SocialNetwork will use use SocialNetwork.getInstance() to initialize the SocialNetwork. Here is the code
public class SocialNetwork  implements Serializable{

    // lots of fields
    private static SocialNetwork myself = null;

    private SocialNetwork(){
    //lots of inilization
    }

    public static SocialNetwork getInstance() {

        if (myself == null){
            myself = new SocialNetwork();
        }
        return myself;
    }

    public void writethisObject() throws IOException{
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("Simulation.bin"));
            objectOutputStream.writeObject(this);
        }

        public void readfromObject(File f) throws IOException, ClassNotFoundException{
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(f));
            SocialNetwork newSocialNetwork = (SocialNetwork) objectInputStream.readObject();
            myself = newSocialNetwork;
        }

}


text:
Q: FindFragmentByTag restricted to specific container I have an activity with two Fragment containers (R.id.first_column_container and R.id.second_column_container).
I'm using a fragment that can go in either containers (only one instance per container) and I need to access either one or the other.
As of now I'm using this method:
public static Fragment getFragmentByTag(FragmentActivity act, String tag) {
    return act.getSupportFragmentManager().findFragmentByTag(tag);
}

But when, as an example, I have an instance on both column and I need to access some method only on the second one I can't.
Is there a way to combine findFragmentById(containerId) and findFragmentByTag(tag), to make a findFragmentByTag(containerId, tag), that would search only between fragments in the specified container?
As of now the only solution I see is to use a different tag for each container, but I would avoid that.


text:
Q: Conformal mapping on unit disk Let $\mathbb{C}_{-}^r:=\mathbb{C}\setminus(]-\infty,-\frac{1}{r}])$, $~\mathbb{C}_{-}:=\mathbb{C}\setminus(]-\infty,0])$, $~\mathbb{D}:= \{z\in \mathbb{C}\mid |z|<1\}$ and $\mathbb{G}=\{z\in \mathbb{C}\mid Re(z)>0\}$
I have to find a conformal map from $\mathbb{C}_{-}^r$ to $\mathbb{D}$ for any $r>0$
My try:

*

*Apply translation $f_{1}(z):= z+\frac{1}{r} \Rightarrow f_{1}(\mathbb{C}_{-}^r) = \mathbb{C}_{-}$

*Apply $f_{2}(z)=\sqrt{z} \Rightarrow f_{1}(\mathbb{C}_{-})=\mathbb{G}$

*Apply $f_{3}(z)=\frac{z-1}{z+1} \Rightarrow f_{1}(\mathbb{G})=\mathbb{D}$

Therefore the conformal map $$f(z)=(f_{3} \circ f_{2} \circ f_{1})(z)=\frac{\sqrt{z+\frac{1}{r}}-1}{\sqrt{z+\frac{1}{r}}+1}$$ but the official answer is $$f(z) =\frac{\sqrt{rz+1}-1}{\sqrt{rz+1}+1}$$ What am I missing ?

A: The mapping $\varphi (z) =r\left(z+\frac{1}{r} \right)$ is also a biholomorphic mapping from $\mathbb{C}^r_- $ onto $\mathbb{C}_- $. So both the answers are good.


text:
Q: Написание запроса MySQL Таблица Messages имеет такую структуру:

from_login who_login - это логины пользователей.
Пытаюсь написать запрос, который выдал бы все диалоги пользователя 123(например).
Написал два запроса, но они выдают диалоги с повторами.
SELECT who_login FROM Messages WHERE from_login = '123' GROUP BY who_login
SELECT from_login FROM Messages WHERE who_login = '123' GROUP BY from_login

Подскажите как написать правильный запрос?

A: Не это?
SELECT who_login FROM Messages WHERE from_login = '123'
UNION
SELECT from_login FROM Messages WHERE who_login = '123'

A: SELECT id FROM Messages WHERE '123' in (from_login, who_login)


text:
Q: Custom Drawer using Reanimated 2 useSharedValue and useAnimatedStyle
I am trying to implement drawing navigation like in the image above using react native reanimated 2.
import React, { useState } from 'react'
import { Text } from 'react-native'
import { createDrawerNavigator } from '@react-navigation/drawer'
import Animated, { useSharedValue, interpolate, useAnimatedStyle } from 'react-native-reanimated'

import Screen1 from '../screens/screen1'
import Screen2 from '../screens/screen2'
import Screen3 from '../screens/screen3'

const Drawer = createDrawerNavigator()

const DrawerNavigator = () => {

const [translateX, setTranslateX] = useState(new Animated.Value(0))
//const translateX = useSharedValue(0)

const scale = Animated.interpolateNode(translateX, {
    inputRange: [0, 1],
    outputRange: [1, 0.8],
});

// const animatedStyle = useAnimatedStyle(() => {
//     const scale = interpolate(
//         translateX.value,
//         [0, 1],
//         [1, 0.8]
//     );
//     return{ transform: [{ scale }] }
// })

const animatedStyle = { transform: [{ scale }] };

return (
    <Drawer.Navigator drawerContent={ (props) => {
            setTranslateX(props.progress)
            // translateX.value = props.progress
            return <Text>Hello madan</Text>
        }} >
        <Drawer.Screen name="screen1">
            {() => <Screen1 style={ animatedStyle } />}
        </Drawer.Screen>
        <Drawer.Screen name="screen2" component={ Screen2 } />
        <Drawer.Screen name="screen3" component={ Screen3 } />
    </Drawer.Navigator>
)
}

I can achieved it by using code above. But, i am using Animated.Value. I want to use useSharedValue() and useAnimatedStyle hook from reanimated 2. I tried to implement that which can be seen in the code above which are commented. But, its not working. App crashes and give error in JSCRuntime file.


text:
Q: Hamburger rendering bug in CSS Can anyone help me flip the position of the hamburger menu and the text on the left. Tried doing it multiple times but failed. I have tried using Z-Index to change the position but didn't seem to help.
Final Image on my website is as attached. Any help would be highly appreciated.
I also want to change the hamburger from a normal bar to a circle icon. Would be great if I could get some assistance for what I described.
Code:

.moreoptions{
    padding-top: 0px;
    float: left;
    position: relative;
    margin-bottom: -10px;
}

.outer {
    overflow: hidden;
    position: relative;

}

.middle {
    margin: 0 auto;
}

label {
    top: 10px;
    display: inline-block;
    padding: 7px 10px;
    background-color: transparent;
    cursor: pointer;
    margin: 10px;
    z-index: 3;
    position: fixed;
}

.bar {
    display: block;
    /*background-color: #38618c;*/
    background-color: black;
    width: 30px;
    height: 3px;
    border-radius: 5px;
    margin: 5px auto;
    transition: background-color 0.4s ease-in, transform 0.4s ease-in,
    width 0.4s ease-in;
}

 More Options

A: Here are a couple of answers:

*

*The icon can be positioned on the left by simply re-arranging your HTML. See the below example code for how the HTML could be re-written.

*Unfortunately, z-index does not work in the way that you need. It only controls the stacking order of overlapping elements, and not the flow of layout. Wrapping your 'button' up in a single element that has floating or flex children is the way to go. Don't forget to clearfix if your use floats.

*I've included a minimal example of how you might transition from the hamburger icon to a close icon, see it on CodePen. To achieve a morph from a hamburger to a circle icon (guessing with an x in the middle?), there are many options, the most basic being stacking the two different icons, and transitioning opacity on toggle with CSS.

  <input type="checkbox" id="toggle" />

    More Options

Heading

input[type="checkbox"] {
  display: none;
}

h1 {
  text-align: center;
}

.navbar {
  padding: 8px 16px;
  background-color: #f7f7f7;
}

.btn {
  display: inline-block;
  padding: 6px 12px 6px 8px;
  line-height: 24px;
  border-width: 1px;
  border-style: solid;
  border-color: #ccc;
  background-color: #fff;
  color: #333;
  cursor: pointer;
  clear: both;

  transition: color 150ms ease,
    background-color 150ms ease,
    border-color 150ms ease;
}

.btn:hover {
  background-color: #ddd;
  color: #000;
  border-color: #999;
}

input[type="checkbox"]:checked + .btn {
  color: #fff;
  background-color: #555;
  border-color: #000;
}

.icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
  box-sizing: border-box;
  float: left;
}

.icon--menu {
  padding: 6px 4px;
}

.icon--menu > div {
  height: 2px;
  background-color: currentColor;
  transition: background-color 150ms ease,
    transform 200ms ease,
    opacity 200ms linear;
}

.icon--menu > div:not(:last-child) {
  margin-bottom: 3px;
}

input[type="checkbox"]:checked + .btn .icon--menu > div:nth-child(1) {
  transform:  translateY(5px) rotate(-45deg);
}

input[type="checkbox"]:checked + .btn .icon--menu > div:nth-child(2) {
  opacity: 0;
}

input[type="checkbox"]:checked + .btn .icon--menu > div:nth-child(3) {
  transform:  translateY(-5px) rotate(45deg);
}

A: To solve your immediate concern of positioning the hamburger to the left:
HTML:

More Options

CSS:
.moreoptions {
  padding-top: 0px;
  position: relative;
}

.outer {
  overflow: hidden;
  position: relative;
}

.middle {
  margin: 0 auto;
}

label {
  padding: 7px 10px;
  background-color: transparent;
  cursor: pointer;
  float: left;
  position: relative;
  top: -2px;
}

.bar {
  display: block;
  /*background-color: #38618c;*/
  background-color: black;
  width: 30px;
  height: 3px;
  border-radius: 5px;
  margin: 5px auto;
  transition: background-color 0.4s ease-in, transform 0.4s ease-in,
    width 0.4s ease-in;
}


text: Q: Fitbit Authentication using UIWebview iOS I'm trying to connect to Fitbit on my iOS native app. I'm using a uiwebview to display to login and authorization screen. If the user login using his/her Fitbit credentials it works fine, but if they try to login using Google or Facebook I'm having trouble. When using Google, there is a popup to login and once the user is authenticated, it tries to do a callback to the parent window but since I'm using a uiwebview it just shows a blank page. Same with Facebook. Anyone have dealt with this before? It works on Safari but I need to do it in-app to get the access code and all the data to link the account and send to the server. Any help?


text:
Q: Unable to connect to database in Openshift I'm running a scaled TinyTinyRSS cartridge, which includes PHP 5.3, a Web Load Balancer, Cron 1.4, and PostgreSQL 9.2.
When I go to the page, I am getting the error:

Unable to connect to database (as [username] to 5401f66a4382ec91770000e2-rmorabia.rhcloud.com, database rss):Unable to connect to database (as [username] to 5401f66a4382ec91770000e2-rmorabia.rhcloud.com, database rss):

By the way, the link to my app is here.
I'm not sure what the problem is. It worked at the beginning, and it hasn't been for the past few days. If you could tell me what information would be helpful to put here, that'd be great.
Possibly of interest, the PHP 5.3 cartridge has a "Idle" status. I was also unable to restart the app.

A: I would recommend a
rhc app-force-stop {appname}

and then
rhc restart -a {appname}


text:
Q: Bash pgrep regexp function I want to create a bash script which would check if the foo is already running and to run it if it's not.
Here is the code:
#!/usr/bin/env bash

function run {
 if ! pgrep $1;
 then
  $@
 fi
}
run foo

After executing the script it starts another instance of foo despite foo is already running.
pgrep foo returns process number so i can make the script kill it first and then start foo again but i want to know if this can be done as described on top.
What am i missing here?

A: A few improvements:
function run {
    if ! pgrep -x "$1" >/dev/null
    then
        "$@"
    fi
}
run foo bar "baz qux"

notes:

*

*quote all your variables. That will maintain any words containing whitespace.

*redirect the output from pgrep

*use the -x pgrep option to restrict the search for processes named "foo", as opposed to processes containing "foo"

You can shorten this to
run() { ! pgrep -x "$1" >/dev/null && "$@"; }

We could write pgrep -x "$1" >/dev/null || "$@" but that will return a successful exit status if the process is already running, and I think it makes more sense to return a failure status if the process cannot be launched.


text:
Q: Regex replace of special characters in JSON string not working I'm stumped...
http://codepen.io/anon/pen/rjjGEE
Why does the regex javascript string replace work for the string with special characters, but not the object converted to a string?
let regex = /[\t\r\n]/g

var directString = "{'name':{'first':' billy bob ','last':'\n\rjoe\tblow'}}"
console.log(directString.replace(regex, "a"));

//Output: "{'name':{'first':' billy bob ','last':'aajoeablow'}}"

let obj = {
      name: {
        first: " billy bob  ",
        last: "\n\rjoe\tblow"
      },

    }

let objAsString = JSON.stringify(obj);
let stringifiedString = objAsString.replace(regex, "a")
console.log(stringifiedString)

//Output: "{'name':{'first':' billy bob  ','last':'\n\rjoe\tblow'}}"

//??? Why isn't \n\r and \t being replaced????

A: When you use escapes like \n and \t in a string constant (like your first example), what you end up with is a string that contains the intended special characters (newline or tab).
When you JSON encode an object, however, what you end up with is a string that contains the escape sequences themselves, not the special characters. The work that JSON.stringify() does has to include making sure that a subsequent parse of the JSON will re-create the original values of all the string-valued object properties. Thus it turns the embedded special characters in the strings back into escape sequences. Your regular expression is looking for the special characters, not the escape sequences.

A: Do not attempt to manipulate JSON strings with regexp. Pain will follow.
Instead, do this:

var jsonString = String.raw`{"a": "foo\nbar\rbaz\tqux"}`;

var replaced = JSON.stringify(JSON.parse(jsonString, (key, value) =>
      typeof value === 'string' ?  value.replace(/[\t\r\n]/g, '') : value
    ));

console.log(replaced);


text:
Q: Deny access to the application for the role. Yii2 I have 2 applications: frontend and backend.
Users on frontend have role "client".
How do I disable access to the application backend users with "client" role. All other roles are allowed access. site/login on backend allow for all users.
I wrote the following code in my main.phpfile:
'as beforeRequest' => [
    'class' => 'yii\filters\AccessControl',
    'rules' => [
        [
            'allow' => true,
            'controllers' => ['site'],
            'actions' => ['login'],
            'roles' => ['?'],
        ],
        [
            'allow' => false,
            'roles' => ['client'],
        ],
    ],
    'denyCallback' => function () {
        return Yii::$app->response->redirect(['site/login']);
    },
],

I have error: ERR_TOO_MANY_REDIRECTS in chrome.

A: From the guide 'roles' => ['?']:

matches a guest user (not authenticated yet)

Since the user is logged in they are stuck in a redirect loop caused by the second rule and the denyCallback i.e.

*

*User is logged in but is of role client and is therefore not allowed.

*Since user has been denied access, redirect to site/login.

*See 1.

This can be fixed by omitting the roles element in your first rule:

If [role] is not set or empty, it means this rule applies to all roles.

HOWEVER THIS IS THE WRONG APPROACH
Users who are logged in but are of role client should be denied access to the backend. Sending them to login will not help since they are already logged in. The proper course of action is to send them to the frontend's error page.


text:
Q: Android Studio Emulator's screen has a trouble on Windows 11 I need help!!!
When I upgrade to Windows 11 and download the latest version Android Studio Dolphin | 2021.3.1, emulator has a trouble like below:
Trouble 1
Trouble 2
I can't post image because I don't have enough 10 reputations.
How I can fix it :<<


text:
Q: How can I connect the pipes? I'm playing Vella's first scene in act 2. I've recovered the helmet, but I can't find a way to connect the pipes.
I can't cut the hose from the bottom, and if I climb it, it won't let me cut from the top either. I can't find anything else around that I can use, nor can I use any other items.
I feel like I've tried every item/interactable combination - what am I missing?

A: You need to have Maintenance Panel 36 (the middle one) "open" (sticking out) before you can cut the hose from the top.
By cutting the bottom of the hose, you should have gotten a short hose segment.
To open maintenance panels, you have to use the small hose to connect two pipes from the left set.
I believe the correct setting is connecting the top and bottom hoses from the left set.


text:
Q: I import another file by `import 'models.dart';`, it can't be compiled I have defined many dart files in my project, and they imported another file by import:
controller.dart
import 'models.dart';

// dart code

app.dart
import 'models.dart';
import 'controller.dart';

// dart code

server.dart
import "app.dart";

main() {
  //
}

more dart files
But when I run server.dart, it reports error:
a library which is imported is missing a library directive: models.dart

What does that mean? Do I have to declare them all as libraries?
From the language specification, it says:
It is a compile-time error if the compilation unit found at the
specified URI is not a library declaration.

It seems we can only import a library, not normal files.
But if I define 2 simple files,
a.dart
import "b.dart";

main() {
   hello();
}

b.dart
hello() { print("hello!"); }

Then run a.dart:
dart a.dart

It can print hello!.
I get confused :(

A: Add library directive in each file that you want to import and all will be works fine.
In your case:
models.dart
library foo.models;
// dart code

controller.dart
library foo.controller;
import 'models.dart';
// dart code

app.dart
library foo.app;
import 'models.dart';
import 'controller.dart';

// dart code

server.dart
 // If not planned to be imported then the name may be omitted
library foo.bin.server;
import "app.dart";

main() {
  //
}

Remember that each library that will be imported by another library requires unique name.
The best way naming your libraries by prepending package name.
Eg.
The package name is "worker".
lib/worker.dart
library worker.worker

lib/work.dart
library worker.work


text:
Q: Display conky always only on LVDS screen I use the following settings in my .conkyrc to display a top bar on my laptop screen (LVDS).
background yes
update_interval 60
total_run_times 0
# Show umlauts
override_utf8_locale yes

# Font settings
use_xft yes
xftfont Noto Sans:style=normal:size=10
xftalpha 1

# Run in own window
own_window yes
own_window_class conky
own_window_type desktop

# Semi-transparent background
# http://th0th.me/log/conky-and-semi-transparency/
own_window_transparent no
own_window_argb_visual yes
own_window_argb_value 140

# Don't show in window lists and on all desktops
own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager
own_window_colour bcbcbc
double_buffer yes
draw_shades no
draw_outline no
draw_borders no
draw_graph_borders no
default_color 000000
alignment tl
maximum_width 1265
minimum_size 1265
#gap_x 10
gap_y 3
no_buffers yes
uppercase no
cpu_avg_samples 2

It is displayed as follows at the top of my screen:

Now when plugging in an external monitor, I want to restrict the conky bar always to just my internal LVDS screen instead of displaying it across both screens.

*

*Output of xrandr without an external monitor connected

*Output of xrandr with external connected and LVDS to the right

*Output of xrandr with external connected and LVDS to the left

Is it possible to tell conky to always stay on LVDS?

A: Yes. You need to set conky to display at the far left/right. The details will depend on whether the laptop screen is on the right or the left hand side. For example, in my setup, I have my laptop on the left and a VGA screen on the right (note the +1600 in the VGA's entry):
$ xrandr | grep -w connected
VGA-0 connected primary 1440x900+1600+0 (normal left inverted right x axis y axis) 408mm x 255mm
DP-3 connected 1600x900+0+0 (normal left inverted right x axis y axis) 344mm x 194mm

I want my conky to always appear on the right edge of my laptop's screen. I have therefore set up my .conkyrc like so:
gap_x 1365
gap_y 40

The gap_x parameter is the number of pixels from the left-most edge of your screen(s). Therefore, my conky always appears at the same place, irrespective of how many screens I have attached.

If the laptop can change position, you'll need something more sophisticated. For example, you could check whether there are two screens and then check if the laptop is on the left or right and edit your .conkyrc accordingly, then launch .conky. Something like:
#!/usr/bin/env bash

## Get the number of screens
screens=$(xrandr | grep -cw connected);

## If there's only one screen
if [ "$screens" -eq 1 ]
then
    ## Set the gap_x to ten pixels from the left.
    sed -i.bak 's/gap_x .*/gap_x 110/' ~/.conkyrc

## If there are more than one screens
else
    ## Get the offset of the laptop's screen
    pos=$(xrandr | grep LVDS1 | cut -d ' ' -f 4 | cut -d+ -f 2)
    ## Is the laptop on the left?
    if [ "$pos" -eq 0 ]
    then
        ## Set the gap_x to ten pixels from the left.
        sed -i.bak 's/gap_x .*/gap_x 10/' ~/.conkyrc
    else
        ## Use the offset to set conky's position accordingly.
        offset=$((pos+10));
        sed -i.bak "s/gap_x .*/gap_x $offset/" ~/.conkyrc

    fi
fi

killall -9 conky
conky &

If you start your conky using that script, it should position it correctly depending on your current setup. This may need some tweaking to fit your specific case, let me know if you need help with it.

A: Since version 1.10 you can use "xinerama_head = <nr>" in your conky.config to specify a specific output.
I had to use this to force conky onto my laptop panel when an external monitor is attached, as I make it my main monitor with my laptop on the left. So although the monitor has an x position of +1920, conky shows up on it without the xinerama_head option.


text:
Q: Looping through guild members with discord.py I have been attempting to make a bot that will give all users in my small guild (<50 members) a role.
I have had a tough time getting the bot to loop through all of the users in the server.
Currently it will output:
02/06/21 17:09:23: Successfully gave john_doe#1234 DJ role. (1 users!).
02/06/21 17:09:23: user john_doe#2234 gave all (1) users DJ role. (placeholder1).

Any advice?
Here is the part of the code I am working on:
    if message.content.startswith(prefix + "Give DJ ALL"):
        count = 0

        for member in message.guild.members:
            count = count + 1
            await member.add_roles(discord.utils.get(message.guild.roles, name = "DJ"))
            print(str(datetime.datetime.now().strftime("%x %X")) + ": " + "Successfully gave " + str(member) + " DJ role. (" + str(count) + " users!).")

        await message.channel.send("Successfully gave " + str(count) + " users DJ!")
        print(str(datetime.datetime.now().strftime("%x %X")) + ": " + "user " + str(message.author) + " gave all ("+ str(count) + ") users DJ role. (" + str(message.guild.name) + ").")

edit: yes i have enabled intents in my bot settings on the website
alonside this:
async def on_ready():
    intents = discord.Intents.default()
    intents.presences = True
    intents.members = True

A: Fixed by using proper syntax thanks to Łukasz Kwieciński.
code here:
client = discord.Client(intents = discord.Intents.all())


text:
Q: Nullable int not working as expected in LINQ (C#) The following works as expected (LINQ to Entities):
var topics = (from t in ctx.Topics where t.SubjectId == subjectId && t.ParentId == null select new { t.Title, t.Id }).ToList();

However, the following returns nothing:
int? parent = null;
var topics = (from t in ctx.Topics where t.SubjectId == subjectId && t.ParentId == parent select new { t.Title, t.Id }).ToList();

Topic.ParentId is a nullable int. It's easy to work around, but this puzzles me. Can anyone shed any light?

A: You are definately not the first person to observe this... interesting... behavior.
http://connect.microsoft.com/data/feedback/details/607404/entity-framework-and-linq-to-sql-incorrectly-handling-nullable-variables
In short, it's difficult to handle different ways of expressing null.


text:
Q: Extracting model equation from glm function in R I've made a logistic regression to combine two independent variables in R using pROC package and I obtain this:
summary(fit)

#Call: glm(formula = Case ~ X + Y, family = "binomial", data = data)

#Deviance Residuals:
#  Min       1Q     Median     3Q      Max
#-1.5751  -0.8277  -0.6095   1.0701   2.3080

#Coefficients:
#             Estimate  Std. Error z value Pr(>|z|)
#(Intercept) -0.153731   0.538511  -0.285 0.775281
#X           -0.048843   0.012856  -3.799 0.000145 ***
#Y            0.028364   0.009077   3.125 0.001780 **
#---
#Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

#(Dispersion parameter for binomial family taken to be 1)

#Null deviance: 287.44  on 241  degrees of freedom
#Residual deviance: 260.34  on 239  degrees of freedom
#AIC: 266.34

#Number of Fisher Scoring iterations: 4

fit

#Call:  glm(formula = Case ~ X + Y, family = "binomial", data = data)

#Coefficients:
#  (Intercept)       X            Y
#   -0.15373     -0.04884      0.02836

#Degrees of Freedom: 241 Total (i.e. Null);  239 Residual
#Null Deviance:      287.4
#Residual Deviance:  260.3        AIC: 266.3

Now I need to extract some information from this data, but I'm not sure how to do it.
First, I need the model equation: suppose that fit is a combined predictor called CP, could it be CP = -0.15 - 0.05X + 0.03Y ?
Then, the resulting combined predictor from the regression should may present a median value, so that I can compare median from the two groups Case and Controls which I used to make the regression ( in other words, my X and Y variables are N dimensional with N = N1 + N2, where N1 = Number of Controls, for which Case=0, and N2 = Number of Cases, for which Case=1).
I hope to have explained everything.


text:
Q: How to append datagridview to excel file using c# I am trying to export my datagridview contents to a excel file which exist in application.startuppath. The problem I am facing is that whenever I export my grid content to excel, it overwrites the previous content. What I would like to do is append to my excel file and not overwrite my existing content.
Here is my code:
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Open(Application.StartupPath+"excelfile.xls");
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
 {
   for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
     if (dataGridView1.Rows[i].Cells[j].Value != null)
      worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
     else
      worksheet.Cells[i + 2, j + 1] = "";
    }
 }
workbook.Close(SaveChanges: true);
app.Quit();

EDIT:
Updated code : thanks to @Alex Bell
int _offset = worksheet.UsedRange.Rows.Count;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
 {
  for (int j = 1; j < dataGridView1.Columns.Count; j++)
   {
    if (dataGridView1.Rows[i].Cells[j].Value != null)
      worksheet.Cells[i + 2 + _offset, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
    else
      worksheet.Cells[i + 2 + _offset, j + 1] = "";
   }
 }

Resolved my problem of appending data but another small problem is every time I update it leaves a blank row between old rows and new rows.

A: Pertinent to your case, you may use int _offset = worksheet.UsedRange.Rows.Count as row offset in your loop:
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
 {
   for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
     if (dataGridView1.Rows[i].Cells[j].Value != null)
      worksheet.Cells[i + 2 + _offset, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
     else
      worksheet.Cells[i + 2 + _offset, j + 1] = "";
    }
 }
Hope this will help. Regards,


text:
Q: find_in_batches: how to end at a particular id? I have a million records and I want to process 100k at a time through 10 different workers.
Documentation:

"You can control the starting point for the batch processing by
  supplying the :start option. This is especially useful if you want
  multiple workers dealing with the same processing queue. You can make
  worker 1 handle all the records between id 0 and 10,000 and worker 2
  handle from 10,000 and beyond (by setting the :start option on that
  worker)."

How to do the above when we can only supply the :start option but not a :end option.

A: find_in_batches will iterate through all the records and yield them to the block in batches.

"The size of each batch is set by the :batch_size option; the default
  is 1000."

So set a :batch_size of 100000, and then you will need to put in your code to assign each batch to your worker.  So something like this:
i = 0
Model.find_in_batches(batch_size: 100000) do |batch|
  # code to assign batch to worker i
  i += 1
end

A: Hooray for symmetry, there is now a finish param:

find_each(start: nil, finish: nil, batch_size: 1000, error_on_ignore: nil)
:finish - Specifies the primary key value to end at, inclusive of the value.

Pull request


text:
Q: jQuery count value of select option inside nested div In jQuery i would like to write a simple function to show an alert if the difference of sum of values selected inside select box is > 0, for each div of same class.
This is my html code:

    $(".Y").each(function( index ) {
     var positive = $(this).children('.Z').val();
     var negative = 0;

     $(this).children('.T').each(function( index ) {
      negative = negative + $(this).val();
     });

     var difference = positive - negative;

     if (difference > 0 ) {
      alert("Show something!");
     }
    });

      <select class="Z">
       <option value="0">0</option>
       <option value="1">1</option>
      </select>
      <select class="T">
       <option value="0">0</option>
       <option value="1">1</option>
      </select>
      <select class="T">
       <option value="0">0</option>
       <option value="1">1</option>
      </select>

      <select class="Z">
       <option value="0">0</option>
       <option value="1">1</option>
       </select>
      <select class="T">
       <option value="0">0</option>
       <option value="1">1</option>
      </select>
      <select class="T">
       <option value="0">0</option>
       <option value="1">1</option>
     </select>

My code is not working. Where i'm wrong? Some hint?

A: var difference = positive - negative;

if (differenze > 0 ) {
    alert("Show something!");
}

You spelled it differenze instead of difference.

A:

$(".Z, .T").on("change", function( index ) {
      var positive = $(this).parent().children('.Z').val();
      var negative = 0;

      $(this).parent().children('.T').each(function( index ) {
          negative = negative + $(this).val();
      });

      var difference = positive - negative;

      if (difference > 0 ) {
          alert("Show something!");
      }
  });

        <select class="Z">
            <option value="0">0</option>
            <option value="1">1</option>
        </select>
        <select class="T">
            <option value="0">0</option>
            <option value="1">1</option>
        </select>
        <select class="T">
            <option value="0">0</option>
            <option value="1">1</option>
        </select>

        <select class="Z">
            <option >0</option>
            <option >1</option>
        </select>
        <select class="T">
            <option >0</option>
            <option >1</option>
        </select>
        <select class="T">
            <option >0</option>
            <option >1</option>
       </select>

A: Thank you all for your help! The main problem, it's that i'm a stupid...
    negative = negative + $(this).val();

means append negative variable with $(this).val(). Not means do an algebraic sum.
Very ugly solution:
    negative = negative - -$(this).val();

Or much better:
    negative = negative + parseInt($(this).val());

Now it works!


text:
Q: JavaScript slidedown() [enter image description here][1]What do I need to modify in this function 'ShowDiv' to be animated. Example when the cntc div showsup to slide down slowly?
function toggle(ele) {
    var cont = document.getElementById('cntc');
    if (cont.style.display == 'block') {
        cont.style.display = 'none';
        document.getElementById(ele.id).value = 'Show DIV';
    }
    else {
        cont.style.display = 'block';
        document.getElementById(ele.id).value = 'Hide DIV';
    }
}

More Details:

The html file:

    <form id = 'cntc' style = 'display:none' action="https://formspree.io/f/moqpwpwp" method="POST">

                Email
                <input id = 'frmName' type = 'text'><button name = 'submit' class = 'btnSubmit' type="submit" target = '_blank'>Send</button>

                Message
                <textarea id = 'frmMessageBox'  name = 'message' cols = '40' rows = '3'></textarea>

    </form>

The js:
function toggle(ele) {
var cont = document.getElementById('cntc');
if (cont.style.display == 'block') {
    cont.style.display = 'none';
    document.getElementById(ele.id).value = 'Show DIV';
}
else {
    cont.style.display = 'block';
    document.getElementById(ele.id).value = 'Hide DIV';
}

}
[url=https://ibb.co/99xx4rJ][img]https://i.ibb.co/nsXX1LT/ss.png[/img][/url]

A: You can use a transition in css. Here's a working solution.

var container = document.getElementById("cntc");
function toggle(el) {
  container.classList.toggle('hide');
  el.innerText = container.classList.contains('hide') ? 'Show DIV' : 'Hide DIV';
}
.box {
      width: 450px;
      height: 100px;
      overflow: hidden;
      background: #D8E9F8;
      transition: all 0.4s ease-in-out;
    }
    .hide {
      height: 0;
    }

     Show DIV

        <form id = 'cntc' action="https://formspree.io/f/moqpwpwp" method="POST">

                    Email
                    <input id = 'frmName' type = 'text'><button name = 'submit' class = 'btnSubmit' type="submit" target = '_blank'>Send</button>

                    Message
                    <textarea id = 'frmMessageBox'  name = 'message' cols = '40' rows = '3'></textarea>

        </form>

A: You can use Jquery Animate Function to scroll to the div smoothly.

function toggle(ele) {
  var cont = document.getElementById('cntc');
  if (cont.style.display == 'block') {
      cont.style.display = 'none';
      document.getElementById(ele.id).value = 'Show DIV';

  }
  else {
      cont.style.display = 'block';
      document.getElementById(ele.id).value = 'Hide DIV';
      $('html,body').animate({
        scrollTop: $("#cntc").offset().top},
        'slow');
  }
}
#home {
    width: 100%;
    height: 1000px;
    background: #ccc;
}

#cntc {
    width: 100%;
    height: 1000px;
    background: #999;
}

<input id="btnToggle" type="button" onclick="toggle(this)" value="Show DIV">

Hi


text:
Q: target HTML 'name' attribute a rails form builder with Jquery I've created a multi-step form based off of the tutorial here. It integrates Jquery Validation in the process to make sure that the data is clean before it hits the server. The validation and multi-step form all work as desired, but since Jquery Validation targets the HTML name tags instead of the id I had to change them manually in order to get the validation to work.
rules: {
                      registrant_first_name: {
                        required: true,
                        minlength: 2,
                    },

                    ...
        },

And in the form helper:
<%= f.text_field :first_name, name: 'registrant_first_name', class: 'form-control' %>

Yet, while this works this sends my params out of the registrant controller and I'd need to re-configure the model to accept the new params. The form responds by rejecting the data and saying the fields are blank (which they technically are)
registrant_first_name: John
registrant_last_name: Doe
registrant_email: johndoe@msn.com

While I'm pretty sure I can fix this problem by simply re-configuring the registrants model to accept the parameters, I'm wondering is there a way to configure the Jquery Validation rules to target the name attribute generated by the forms helper? (currently it throws an error)
rules: {
                      registrant[first_name]: {
                        required: true,
                        minlength: 2,
                    },

                    ...
        },

And if not, is there any harm in configuring the model to allow these parameters that will no longer belong to the registrants hash?

A:
I'm wondering is there a way to configure the Jquery Validation rules to target the name attribute generated by the forms helper? (currently it throws an error)

Yes.  Simply surround the name with quotation marks.
rules: {
    'registrant[first_name]': {
        required: true,
        minlength: 2,
        ....

Documentation: Fields with complex names (brackets, dots):

"If your form consists of fields using names that aren't legal JavaScript identifiers, you have to quote those names when using the rules option"


text:
Q: Errors and accuracy not included in call: model - Random forest model I'm using random forest for the first time. I was wondering why after running the model I can't see all the statistics in the call. I expected to see also accuracy and OOB error, for instance.
rf <-randomForest(VWC~.,data=Data_All,
                  mtry=best.m, importance=TRUE,
                  ntree=500)
print(rf)

Call:
 randomForest(formula = VWC ~ ., data = Data_All, mtry = best.m,      importance = TRUE, ntree = 500)
               Type of random forest: regression
                     Number of trees: 500
No. of variables tried at each split: 41

          Mean of squared residuals: 4422.255
                    % Var explained: 49.43

I selected a few columns because it is a huge dataframe:
dput(Data_All[1:20, c(1, 8)])
structure(list(VWC = c(56.1, 50.6, 60.7, 40.1, 47.3, 52.8, 51.4,
44, 47.1, 51.9, 47.7, 51, 45.3, 49.3, 52.4, 51.8, 52.2, 49, 46.1,
44.4), vh_glcm_7 = c(0.910762965, 0.910106623, 0.91908574, 0.926299954,
0.945425676, 0.948440292, 0.948440292, 0.940617102, 0.938677993,
0.927837995, 0.928881178, 0.931472503, 0.927350345, 0.919106027,
0.917548344, 0.922729618, 0.93057993, 0.93057993, 0.931927558,
0.927018363)), row.names = c(NA, 20L), class = "data.frame")

A: For regression there is no accuracy, but rather MSE and R^2 (% Var), which are standard measures for regression, you should look into those if you do not know them yet.


text:
Q: Getting different answers for the same math when using different function, don't know why I am trying to center values around the mean of an entire column. I need to do this for an entire (large) data frame, so first I tried colMeans.
colMeans(data, na.rm = TRUE)
From this, I get an answer like 5.567 for the first column of my data set. However, I wanted to double check this. When I use the mean function
mean(data$first_column, na.rm = TRUE) I get 8.466 instead. When I calculate the mean in an excel sheet, I got something around 6.5.
I haven't been able to recreate this problem with a generated data set, so here is a
link to a GoogleDoc with the first two columns of my data set .
The end goal is to center the values around the mean for nearly every column in the data set, and I assumed I would do this with lapply(). But before I do that, I want to understand why I am getting so many different mean values. I assume it has to do with NAs or something, but I'm not quite grasping it.
Thanks in advance for your help.

A: After a lot of trying, here is the code I have. I am still getting mean values that are off, but colMeans() and mean() are both producing the same answer so I think it has something to do with the variable NA's that I have rather than the functions. I'm still examining that, but I figured out how to both replace the NAs with the mean value while centering other values around the mean. This post helped me figure it out, specifically @Itsa's code.
###center values first
center_asd_prep <- autgi %>% select(ID, Irritability, Other_Variables)
as.numeric(center_asd_prep$srs_tot_raw ) -> center_asd_prep$srs_tot_raw
center_asd_mean <- center_asd_prep %>% select(-ID, -Group.y) #remove categorical info
#replacing NA with mean while centering other values around the mean
center_asd_mean[] <- lapply(center_asd_mean, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
#adding ID info back
center_asd <- data.frame(center_asd_mean, ID = center_asd_prep$ID, Group = center_asd_prep$Group.y)
center_asd
I'll update this post if I figure out why I'm getting such high mean values, but I have 14 observations that have a high number of NAs, and I think that this is impacting the results because my N=218. Hypothetically, this code should work if anyone runs into the same problem as me.


text:
Q: Jquery tooltip absolute positioning I would like to fix the positioning of my Jquery tooltip in an absolute way. No matter where my mouse goes or what it hovers, the tooltip needs to appear at the place, as a function of a div. Say, the bottom left corner of a div. It's not so much of a tooltip as a static div. But I am not looking to convert the tooltip to a div.
Is it for example to set the tooltip so that the top left corner of the tooltip is set by a coordinate, which relates to a specific container div?
Here's a good jsfiddle if you need it.

A: If you know your tooltip content when preparing html, you can use css.
Here is an example. (Needs some work on styling)

.box {
  position: relative;
  width: 200px;
  height: 50px;
  margin-bottom: 70px;
  background-color: blue;
}

.tooltip {
  display: none;
  border: 1px solid black;
  padding: 10px;
  background-color: white;
  position: absolute;
}

/* here are your coordinates */
.box_tooltip_right .tooltip {
  left: calc(100% + 5px);
  top: 0;
}

/* here are your coordinates for bottom tooltip */
.box_tooltip_bottom .tooltip {
  left: 0;
  top: calc(100% + 5px);
  width: 100%;
  box-sizing: border-box;
  text-align: center;
}

.hoverbox:hover .tooltip {
  display: block;
}

I am tooltip bottom 1

    Tooltip bottom 1

I am tooltip bottom 2

    Tooltip bottom 2

I am tooltip right

  Tooltip right


text:
Q: How to 301 redirect URL with PHP parameters to root DIR in .htaccess? I have searched how to redirect url with parameters to root dir but I can't get it to work :(
This is what the .htaccess code looks like:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

RewriteEngine On
RewriteCond %{QUERY_STRING} id=1
RewriteRule ^phpnuke/modules\.php$ /? [L,R=301]

I have url such as "http://www.domain.com/phpnuke/modules.php?name=News&file=article&sid=60" and I want to redirect it to "http://www.diagonally.org/"

A: Try some thing like this
# For sites running on a port other than 80
RewriteCond %{HTTP_HOST}   !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST}   !^$
RewriteCond %{SERVER_PORT} !^80$
RewriteRule ^/(.*)         http://www.example.com:%{SERVER_PORT}/$1 [L,R]

A: Keep redirect rule before default WP rewrite rule and match correct query string:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} name=News&file=article&sid=60
RewriteRule ^phpnuke/modules\.php$ /? [L,R=301]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>


text:
Q: Jquery calculation through Inputs Add / Subtract OK... as I am new to JS so dont know how to get out of this. here is my form enter image description here
I am trying to catch the total security of bottles.
Total security = Quantity * 500
which is working fine, but when i enter number in empty bottles the calculation doesn't fits .It should subtract the amount (empty bottles) from total security. I am unable to do that somehow..
here is my code;
(function () {
      $('input[name="quantity"]').bind("focus blur change keyup", function ()
           $('input[name="total_amount"]').val($(this).val() * $("#pricevalue").val());
           $('input[name="total_security"]').val($(this).val() * 500);
                        });
                })();

The above code is working fine... code below is creating the problem

        (function () {

           $('input[name="empty_bottles"]').bind("on keyup", function () {

                          var value = $(this).val() * 500;

                           var test = $("#total_security").val() - value;
                           $("#total_security").val(test);

                        });
                })();

Thanks in advance

A: From what I gather:

*

*Total Security = (quantity * 500) - bottles

*Total Amount = quantity * price

If that's correct, then the below code should work.
$(document).on('input change',':input',function() {
  var quantity = $('[name="quantity"]').val() || 0;
  var price = $("#pricevalue").val() || 0;
  var bottles = $('[name="empty_bottles"]').val() || 0;
  $('[name="total_security"]').val((quantity * 500) - bottles)
  $('[name="total_amount"]').val(quantity * price);
});

Example: https://jsfiddle.net/mou9Ldmu/2/


text:
Q: chrome.tabs.highlight giving error "No tab at index" When calling chrome.tabs.highlight({'tabs': tabId}, function(){}); I'm getting this error:
Unchecked runtime.lastError while running tabs.highlight: No tab at index: 7355.

A: Another important thing (in addition of using the tab index) is to provide the windowId. This is not documented in the official chrome docs, but helps if a different window or inspector is active.
chrome.tabs.highlight({
  windowId: tab.windowId,
  tabs: tab.index
}, function () {});

A: chrome.tabs.highlight requires a tab index, not a tabId. You can convert a tabId into an index using chrome.tabs.get:
chrome.tabs.get(tabId, function(tab) {
  chrome.tabs.highlight({'tabs': tab.index}, function() {});
});

A: This function does not take tab IDs, but instead the tab indices (positions within the window)


text:
Q: How to get firstname from using this query? I am trying to fetch firstname from employeedetail table where the character string of firstname = 5, I am executing below code :
select firstname=(case when len(firstname) = 5 then firstname end) from employeedetail

it gives me what i want, but it giving me the null values as well, just because of character string value. Now i don't want these null values in my output. How can i do this?

A: Add where len(firstname) = 5 to your query.
This will help you avoid all rows where length of firstname column data is not 5 characters altogether.
Your problem arose as CASE statement did not have the ELSE part defined which resulted in NULL for all those case whose WHEN part was false.
If you want to handle the cases where firstname is longer or shorter than 5 characters another way, just add more when clauses to your case statement.

A: select firstname=(case when ISNULL(firstname,'')<>'' AND len(firstname) = 5 then firstname end) from employeedetail


text:
Q: Sequelize cyclic dependencies? Okay, so I attempted to create a hasMany/belongsTo relationship between two entities User and Submission, and got the classic Cyclic dependency found. users is dependent of itself. Dependency chain: users -> submissions => users
As with seemingly everyone else on the internet, I just put constraints: false on every relation. Like, every single one in the whole app.
I'm still getting the exact same error.
    User.associate = models => {
        User.hasMany(models.Submission, {
            onDelete: 'CASCADE',
            constraints: false
        })
    }

    Submission.associate = models => {
        Submission.belongsTo(models.User, {
            onDelete: 'CASCADE',
            constraints: false
        })
    }

Does anyone know what to do in this context? I obviously can't remove any more constraints. It's the world's most basic relationship, I cannot work out why Sequelize is throwing a tantrum.


text:
Q: Security in Restful web application in java I am working in restful web services . We are creating web services which is running in glassfish and we are calling these restful web services directly from our jsp deployed in tomcat . I have to make our web service secure such that no other person or organisation can hit(use) our web services from there application . Can you tell me how to do these ??????

A: one easy way is to transmit basic authentication information in every rest request and intercept each request on your rest backend. in your interceptor you try to get these information and check in your database if these information is correct.
to parse the auth information from your header do the following:
            // Get request headers
            final HttpHeaders headers = request.getHttpHeaders();

            // Fetch authorization header
            final List<String> authorization = headers.getRequestHeader(AUTHORIZATION_PROPERTY);
            // Get encoded username and password
            final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");
            // Decode username and password
            String emailAndPassword;
            try {
                emailAndPassword = new String(Base64.decode(encodedUserPassword));
            } catch (IOException e) {
                return SERVER_ERROR;
            }

            // Split username and password tokens
            final StringTokenizer tokenizer = new StringTokenizer(emailAndPassword, ":");
            final String email = tokenizer.nextToken();
            final String password = tokenizer.nextToken();

now you can use the Strings email and password as credentials that you can check against your database.
remember you must do this for every request before it reaches your webservice implementation. you should read about interceptors for this matter
regards


text:
Q: Fetching only selective fields using ElasticSearch RestHighLevelClient I am using RestHighLevelClient to fetch documents from ES storage.
.....
RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(60L));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.size(100);
sourceBuilder.query(QueryBuilders.matchQuery("id", id));
SearchRequest searchRequest = new SearchRequest("my-index");
searchRequest.scroll(scroll);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

Currently this fetches all fields, but I want to fetch only a specific field.
How can this be done using RestHighLevelClient.

A: You need to use the source filtering and pass the array of field names that you want to fetch, below request added on according to your example will fetch only title fields and exclude everything else in response.
RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(60L));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.size(100);
String[] includeFields = new String[] {"title"};
sourceBuilder.fetchSource(includeFields, null);
sourceBuilder.query(QueryBuilders.matchQuery("id", id));
SearchRequest searchRequest = new SearchRequest("my-index");
searchRequest.scroll(scroll);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);


text:
Q: GNAT Programming Studio: New project location browser freezes after attempting to make a bookmark I just installed GPS on Windows 10
In order to make browsing to my source file folder less annoying, I tried adding it as a bookmark in the folder browser accessed from the new project window.
When I right clicked on the folder and added it as a bookmark, the window blanked and froze. Now, every time I open the folder browser, it blanks and freezes. I uninstalled and reinstalled GPS, but it didn't help.
I can open projects, since it uses the default windows folder browser, and I can create projects if I type the folder path manually.
How can I fix GPS to make the folder browser not freeze?

A: I resolved the issue with help from Adacore customer support by removing the AppData\local\gtk-3.0\bookmarks file.