text:
Q: java code to launch jar by passing arguments to it I want to launch an jar file by passing two arguments to it from java code,what i have tried is:
File jarFile = new File("path/to/jar/file");
if ((jarFile).exists()) {
                String[] command = new String[5];
                command[0] = "java.exe";
                command[1] = "-jar";
                command[2] = jarFile + "";
                command[3] = "arg1";
                command[4] = "arg2";
                Process p = Runtime.getRuntime().exec(command);
                p.waitFor();
} else {
    System.out.println("File is not available");
}

code is perfect for launching jar,
But i want to launch jar file using 32 bit JVM as my drivers are 32 bit only.,And my machine contains both 32 bit and 64 bit JVM,in order to launch jar using 32 bit JVM i could have hard coded java.exe location like
command[0] = "C:\\Program Files (x86)\\Java\\jdk1.7.0_25\\bin\\java.exe"

but 1)what if the end user have installed java in some other location?
2)what if path environment variable contains 64 bit JVM location if i just give java.exe? I tried this below code but i am unable to pass arguments using this method
String command = {"rundll32 url.dll,FileProtocolHandler ", jarFile  + "" , arg1, arg2}
Process p = Runtime
                   .getRuntime()
                   .exec(command);

So is there any other way to launch jar file by passing arguments to it?

A: Use the argument '-d32', i.e.
 java -d32 -jar jarfile arg1 arg2.
java -help can be handy too.


text:
Q: SELECT only from 15 minutes back I would likt to  select text from chatlog which is max. 15 minutes old, but this doesn't work
What am i doing wrong?
My field "date" is 2013-01-04 22:50:53
 select user
 from chatlog
 WHERE date  >= DATE_SUB(CURDATE(),INTERVAL 15 MINUTE)
   AND  room = '".$roomId."'
   and user != 35
   and event_id IS NULL

Did also try <= instead of >=

A: CURDATE only has a date component (not time).  You need to use NOW() instead.

A: You need to use NOW():
SELECT `user`
FROM chatlog
WHERE date > NOW() - INTERVAL 15 MINUTE
    AND room = '" . $roomId . "'
    AND `user` != 35
    AND event_id IS NULL

A: Try this:
SELECT user FROM chatlog
     WHERE date  >= NOW() - INTERVAL 15 MINUTE
     AND  room = '".$roomId."'
     AND user != 35
     AND event_id IS NULL

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not overlay a image on Appbar of my screen. (React-Native, react-native-paper) I tried to overlap an image on Appbar Component and it's not happening.
Here is my code...
<View style={{flex: 1, backgroundColor: '#F6F8FB'}}>
        <Appbar.Header style={styles.appHeader}>
          <Appbar.BackAction />
        </Appbar.Header>
        <Image
          source={require('../../../resource/images/LivingRoom.png')}
          style={styles.imageStyle}
        />
</View>

Here is the CSS for the same.
  appHeader: {
    backgroundColor: '#184DB8',
    height: (15 / 100) * height,
    width: '100%',
    alignItems: 'flex-start',
  },
  imageStyle: {
    width: '100%',
    height: (25 / 100) * height,
    borderTopLeftRadius: 50,
    borderTopRightRadius: 40,
  },

I need Help!!

Like this Image

A: Try to add postion:'absolute to imageStyle.
imageStyle: {
    postion: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: (25 / 100) * height,
    borderTopLeftRadius: 50,
    borderTopRightRadius: 40,
  },

now you can play with image position by edit top.

A: Write </Appbar.Header> after the <Image> tag
<View style={{flex: 1, backgroundColor: '#F6F8FB'}}>
        <Appbar.Header style={styles.appHeader}>
            <Appbar.BackAction />
            <Image
               source={require('../../../resource/images/LivingRoom.png')}
               style={styles.imageStyle}
            />
       </Appbar.Header>

</View>

A: I have solved your problem by removing "flex: 1" from your view container. The result I got was the following:
Example
This is the code:
<View style={styles.header}>
  <Appbar.Header style={styles.appHeader}>
    <Appbar.BackAction />
  </Appbar.Header>
  <Image
    source={require('../../assets/room.jpg')}
    style={styles.imageStyle}
  />
</View>

And the styles:
  header: {
    flex: 0,
    backgroundColor: '#184DB8',
    shadowColor: 'transparent',
  },
  appHeader: {
    flex: 0,
    backgroundColor: '#184DB8',
    width: '100%',
    alignItems: 'flex-start',
    borderBottomWidth: 0,
    shadowColor: 'transparent',
  },
  imageStyle: {
    flex: 0,
    width: '100%',
    borderTopLeftRadius: 50,
    borderTopRightRadius: 40,
  }

(PS: sorry if my English writing is somewhat confusing, I'm learning it)
(PS2: I am new to the world of react and I couldn't remove the shadow that the header has, an apology)


text:
Q: First encounter of Sturm-Liouville problem I have been assigned to find a solution to a specific Sturm-Liouville problem as preparation for an upcoming interview. This is in fact the first time I've ever met this class of problems (being a second year mathematics student at university). Anyway I've done some research and had a good crack at the problem but I find myself not knowing whether anything I've done is right.
Here is the phrasing of the question:

Any linear second order ordinary differential equation can be written in the classical Sturm-Liouville form,
$$L(y(x))=\lambda w(x)y(x),\;x\in[a,b],\;(1)$$
in which the operator, $L$, is self-adjoint. Typically, $(1)$ will be subject to boundary conditions of the form,
$$A_1y(a) + B_1y′(a)=0,\;A_2y(b) + B_2y′(b)=0.\;(2)$$
The solution of $(1)$, subject to $(2)$, gives rise to an infinite set of eigenfunctions, $y_n(x)$, which are orthogonal with respect to one another and the weight function, $w(x)$. Each eigenfunction has an associated, real eigenvalue, $λ_n$.

The conditions we are given to work with are:

$$L = \frac{d^2}{dx^2} + 1,\;x ∈ [0, 1],$$
  $$w(x) = 1,$$
  $and,$
  $$y(0) = 0,\,y'(1) = 0.$$

I am asked to find the analytic solution to this particular Sturm-Liouville problem which I worked out to be:
$$y_n(x) = B_n\sin\left(\left(2n+1\right)\frac{\pi}{2}x\right),\;n\in\mathbb Z$$
where $B_n$ is undetermined.
I am asked to determine $B_n$ by imposing:

$$\int_0^1y_n^2(x)\,dx=1.$$

Using this I found that $B_n=\pm\sqrt{2},$ which troubles me because in all the examples I've looked at regarding Sturm-Liouville problems a situation like this (where the constants are ambiguous) has not arisen. So I am worried I have made an error somewhere leading up to this. Anyway the next task is to represent $g(x)=x$ as an infinite series using the previously found eigenfunctions over the domain $x\in[0,1].$
Now I searched online for a method to do this and found this document: Non-homogeneous Sturm-Liouville problems. Looking at the top of the second page they give a formula for finding the coefficients/weightings to express any function over $[0,1]$ as a series of eigenfunctions. Using this and my eigenfunctions I found that $$x=\frac{8}{\pi ^2}\sum_{n=1}^\infty\frac{(-1)^n}{(2n+1)^2}\sin\left(\left(2n+1\right)\frac{\pi}{2}x\right).$$
But I know this is completely wrong as I plotted this sum on MatLab to a sufficient number terms and it looked nothing like the function $g(x)=x$.
Now if you've read this far that is much appreciated and any help you could provide would be fantastic as I really would like to do well in solving this problem. Of course I will continue to research into this topic (I've even bought a textbook on Sturm-Liouville theory!) and will keep this post updated as necessary.

A: Notes on your solution:

*

*It might be worth noting that you can restrict $n$ to be a
non-negative integer, since any negative integer will reproduce a
solution you have already found.

*Typically the normalisation constant $B_n$ is chosen to be positive, since a negative one will just give negative values for coefficients later.  Essentially, the constant doesn't make much difference at all, so we pick a positive one for convenience's sake.

*From Sturm-Liouville theory we have that the eigenfunctions form a complete basis for the vector space of functions subject to the same boundary conditions, that is, any function $f$ with $f(0)=f'(1)=0$ can be written as a (probably) infinite linear combination of the eigenfunctions you've found. I'll try to explain what the coefficients should be instead of quoting a formula.

A Sturm-Liouville operator induces an inner product, essentially measuring the "angle" between two functions.  In this case $w(x)=1$ so I won't bother with the subscript $w$ that should really be there.  We define the inner product (think the generalisation of dot product) for this problem to be
$$\langle f,g\rangle = \int_0^1 f(x) g(x) dx$$
The useful parts about this are that the operator $L$ is self adjoint with respect to this inner product, namely that $\langle Lf,g\rangle = \langle f,Lg\rangle $, and that eigenfunctions with respect to different eigenvalues are orthogonal, that is if $Lf=\lambda_1 f$ and $Lg=\lambda_2 g$ with $\lambda_1 \ne \lambda_2$ then $\langle f, g \rangle = 0$.  (Both these facts are proved in the notes I gave you in the comments, but it might be useful to prove the first with your specific $L$ instead of the general case.
Now, we'd like to express $x$ in terms of the $y_n$ that you've found.  By completeness, $x = \sum_{n=0}^\infty c_n y_n$, for some undetermined $c_n$.  But look what happens if we take the inner product of both sides with $y_m$, for some $m$:
$$\begin{align}
x &= \sum_{n=0}^\infty c_n y_n \\
\langle x, y_m \rangle &= \sum_{n=0}^\infty c_n \langle y_n, y_m \rangle \\
\langle x, y_m \rangle &= c_m \langle y_m, y_m \rangle
\end{align}$$
I subtly used linearity of the inner product in there, which you should justify to yourself from the definition I gave above of the inner product.  Also, I used $\langle y_n, y_m \rangle = 0$ for $n \ne m$, which comes from orthogonality.  So almost all the terms of the sum have disappeared, save for the $\langle y_m, y_m \rangle$.  But you've already normalised the $y_m$ to set this equal to $1$! This means that we have a nice expression for $c_m$, which is $\langle x, y_m \rangle$.
Computing this integral on Wolfram Alpha because I'm lazy, we have $$c_n = \frac{4 \sqrt{2}}{(2n+1)^2 \pi^2}(-1)^n$$
$$x = \frac{8}{\pi^2}\sum_{n=0}^\infty \frac{(-1)^n}{(2n+1)^2} \sin\left(\frac{2n+1}{2} \pi x\right)$$
So it looks like the only mistake you made was missing out $n=0$ in the sum, since this solution does converge nicely to $x$ on $[0, 1]$.  Even if the bulk of this post didn't directly solve your problem, I hope it's given you a useful insight into Sturm Liouville theory.


text:
Q: Python gnupg: "No Pinentry" error during key deletion I'm building a python3 application, that generates a GPG key, asks for a passphrase and de/encrypts files. I want, that the correct passphrase input is required every start of the application.
Currently it seems, that the gpg-agent still holds the passphrase after the application is closed. A restart of the application does not require the correct passphrase to decrypt the data.
So I've had the idea to export the keys (public and private) into an ASCII armored file, import it on the start and deleting the keys again from the keyring, when the application closes. When I try to delete the keys (private key first, as described here at the documentation) and show the stderr of the resulting object, it shows me a "No Pinentry" Error.
I've written a short test program:
import gnupg
gpg = gnupg.GPG(gnupghome="testhome")
input_data=gpg.gen_key_input(name_email="vault@mydomain.com", key_type="DSA", subkey_type="RSA",passphrase="Test")
key = gpg.gen_key(input_data)
if not gpg.list_keys():
    print(key.stderr)
    exit()
status=gpg.delete_keys(gpg.list_keys(True)[0]['fingerprint'],secret=True, passphrase="Test")
print(status.stderr)

The last print statement shows this:
gpg: Hinweis: Keine voreingestellte Optionendatei '...testhome/gpg.conf' vorhanden
gpg: enabled debug flags: ipc
gpg: DBG: chan_5 <- OK Pleased to meet you, process 2103
gpg: DBG: connection to agent established
gpg: DBG: chan_5 -> RESET
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION ttytype=xterm-256color
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION display=:0
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION xauthority=/run/user/1000/gdm/Xauthority
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION putenv=XMODIFIERS=@im=ibus
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION putenv=GTK_IM_MODULE=ibus
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION putenv=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION putenv=QT_IM_MODULE=ibus
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> GETINFO version
gpg: DBG: chan_5 <- D 2.2.4
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION allow-pinentry-notify
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION agent-awareness=2.1.0
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION pinentry-mode=loopback
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> HAVEKEY A50FB634D9E33FEE1D9B8861A563F4C53BC20CD1
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> HAVEKEY A50FB634D9E33FEE1D9B8861A563F4C53BC20CD1
gpg: DBG: chan_5 <- OK
[GNUPG:] KEY_CONSIDERED 12E6713D592E3FA210EE05E9558B0205D1894962 0
gpg: DBG: chan_5 -> SETKEYDESC Möchten+Sie+den+ausgewählten+geheimen+OpenPGP+Schlüssel+wirklich+dauerhaft+entfernen?+(j/N)%0A%22Autogenerated+Key+<vault@mydomain.com>%22%0A2048-Bit+DSA+Schlüssel,+ID+558B0205D1894962,%0Aerzeugt+2019-07-03.%0A?
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> DELETE_KEY A50FB634D9E33FEE1D9B8861A563F4C53BC20CD1
gpg: DBG: chan_5 <- ERR 67108949 Kein Pinentry <GPG Agent>
gpg: Fehler beim Löschen des privaten Schlüssels: Kein Pinentry
gpg: DBG: chan_5 -> HAVEKEY 489F5816348DA3C7D2540D5748CD0AC1E4ACA459
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> SETKEYDESC Möchten+Sie+den+ausgewählten+geheimen+OpenPGP+Unterschlüssel+wirklich+dauerhaft+entfernen?+(j/N)%0A%22Autogenerated+Key+<vault@mydomain.com>%22%0A3072-Bit+RSA+Schlüssel,+ID+42CA4781026C931E,%0Aerzeugt+2019-07-03+(Hauptschlüssel-ID+558B0205D1894962).%0A?
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> DELETE_KEY 489F5816348DA3C7D2540D5748CD0AC1E4ACA459
gpg: DBG: chan_5 <- ERR 67108949 Kein Pinentry <GPG Agent>
gpg: Fehler beim Löschen des privaten Unterschlüssels: Kein Pinentry
gpg: 12E6713D592E3FA210EE05E9558B0205D1894962: delete key failed: Kein Pinentry
gpg: secmem usage: 224/65536 bytes in 1 blocks

Since the error message contains german, I will try to translate these passages correctly:
gpg: Notice: No preset options file '...testhome/gpg.conf' found
gpg: enabled debug flags: ipc
gpg: DBG: chan_5 <- OK Pleased to meet you, process 2103
gpg: DBG: connection to agent established
gpg: DBG: chan_5 -> RESET
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION ttytype=xterm-256color
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION display=:0
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION xauthority=/run/user/1000/gdm/Xauthority
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION putenv=XMODIFIERS=@im=ibus
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION putenv=GTK_IM_MODULE=ibus
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION putenv=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION putenv=QT_IM_MODULE=ibus
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> GETINFO version
gpg: DBG: chan_5 <- D 2.2.4
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION allow-pinentry-notify
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION agent-awareness=2.1.0
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> OPTION pinentry-mode=loopback
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> HAVEKEY A50FB634D9E33FEE1D9B8861A563F4C53BC20CD1
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> HAVEKEY A50FB634D9E33FEE1D9B8861A563F4C53BC20CD1
gpg: DBG: chan_5 <- OK
[GNUPG:] KEY_CONSIDERED 12E6713D592E3FA210EE05E9558B0205D1894962 0
gpg: DBG: chan_5 -> SETKEYDESC
Do you really want to delete the private OpenPGP subkey permanently? (y/N) Autogenerated+Key+<vault@mydomain.com>%22%0A2048-Bit+DSA+Key,+ID+558B0205D1894962,generated+2019-07-03.%0A?
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> DELETE_KEY A50FB634D9E33FEE1D9B8861A563F4C53BC20CD1
gpg: DBG: chan_5 <- ERR 67108949 No Pinentry <GPG Agent>
gpg: Error during deletion of the private key: No Pinentry
gpg: DBG: chan_5 -> HAVEKEY 489F5816348DA3C7D2540D5748CD0AC1E4ACA459
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> SETKEYDESC
Do you really want to delete the private OpenPGP subkey permanently? (y/N) Autogenerated+Key+<vault@mydomain.com>%22%0A3072-Bit+RSA+Key,+ID+42CA4781026C931E,generated+2019-07-03+(Main Key-ID+558B0205D1894962).%0A?
gpg: DBG: chan_5 <- OK
gpg: DBG: chan_5 -> DELETE_KEY 489F5816348DA3C7D2540D5748CD0AC1E4ACA459
gpg: DBG: chan_5 <- ERR 67108949 No Pinentry <GPG Agent>
gpg: Error during deletion of the private subkey: No Pinentry
gpg: 12E6713D592E3FA210EE05E9558B0205D1894962: delete key failed: No Pinentry
gpg: secmem usage: 224/65536 bytes in 1 blocks

I'm running Ubuntu 18.04, python3.6.7, gnupg version 2.2.4 (as shown by gpg.version)

A: I now solved the issue.
When deleting the secret key, GPG tries to invoke pinentry, which will display a graphical confirmation dialog. As here GPG is invoked from a python script, it seems, that it does not know of any graphical desktop, where it could show this dialog, so it gives out an error (at least that is my interpretation of the problem).
This can be solved, by telling the GPG object, to provide the option --yes to all gpg commands. This will deactivate the confirmation dialog. So I just changed the definition line of the GPG object to
gpg = gnupg.GPG(gnupghome="testhome",options=['--yes'])

Now the deletion of the secret key is executed without an error.


text:
Q: How to subtract row means from each row If I have a matrix or data frame genelike this:
    [,1] [,2] [,3] [,4]
[1,]    2   12    4   10
[2,]    3   14    3   9
[3,]    5   15    4   3
[4,]    8   6    12   18

And I already get the means of each row and each column by:
a <- apply(gene, 1, mean)
b <- apply(gene, 2, mean)

And now I want to subtract row means from each row and get this:
      [,1] [,2] [,3] [,4]
[1,]   -5   5    -3   3
[2,] -4.25 6.75 -4.25 1.75
[3,] -1.75 8.25 -2.75 -3.75
[4,]    -3   -5    1   7

which means the rowmeans of the new matrix is all 0.
How can I get this?

A: You can just use the function rowMeans
gene - rowMeans(gene)
        V1    V2    V3    V4
[1,] -5.00  5.00 -3.00  3.00
[2,] -4.25  6.75 -4.25  1.75
[3,] -1.75  8.25 -2.75 -3.75
[4,] -3.00 -5.00  1.00  7.00

A: Use sweep():
gene <- matrix(c(2,12,4,10,3,14,3,
                 9,5,15,4,3,8,6,12,18),
      byrow=TRUE,nrow=4)
gene2 <- sweep(gene, MARGIN=1, STATS= rowMeans(gene))

Subtracting the row means as suggested by @G5W works, but only because of an interaction between two underlying properties of R: (1) automatic replication of vectors to the appropriate length when operating on unequal-length vectors; (2) column-major storage of matrices.


text:
Q: How do you title a letter to a family surname? I am writing a letter to some family members and it is a thank you to a whole family. Would it be written as
Dear Smiths,?  Do I need an apostrophe, so it is Dear Smith's? What if it ends in an s like the surname 'Stokes'? Do you write Dear Stokes' or simply Dear Stokes, because Dear Stokeses seems wrong?
Thank you very much.


text:
Q: Can a Scanner have a slice receiver? The Scanner interface (https://golang.org/pkg/database/sql/#Scanner) makes it quite easy to configure how a type is deserialized by the database/sql API from data that has been read from a database.
I've used this in various ways to handle my own types, but I just tried reading a denormalised string list into a slice of strings, e.g.
type Roles []string

func (rs Roles) Scan(value interface{}) error {
    ...
}

It's normal for the Scan receiver to be a pointer to a zero-valued instance of the type. In the case I'm trying to write, it's a slice instead.
Is this possible?
If so, how is the size of the slice determined (it isn't known until the scanner starts parsing, e.g. by splitting an input string on commas or something similar) ?

A: Yes, this is possible, but you want to define the method on *Roles instead. Then you can grow the slice as needed.
func (rs *Roles) Scan(value interface{}) error {
    ...  check not nil
    ...  split string into words
    *rs = make(RosterRoles, len(words))
    ...  range across the words
}

The database/sql library will be using this something like
var rs Roles
err := rs.Scan("abc,def")
// rs contains []string{"abc", "def"}

Thanks to @Peter for this answer.


text:
Q: Multiple uncaught reference errors in promise not defined while trying to add data into the firestore database, and function running multiple times After user logs in, I am trying to display the data in firestore to the user. Upon logging in, the console sends out multiple uncaught (in promise) ReferenceError:l is not defined, le, is not defined, n is not defined.
Ignoring the error does not cause the program to break. Upon updating the document of the current user, the function runs itself multiple times rather than a single time. Can somebody please help me fix this problem. Thank you very much.
I am also getting an error:
"Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'ingredients')"
if it is a new user with no documents yet. how would I deal with this?

import { getAuth, onAuthStateChanged } from "firebase/auth";
import {
  doc,
  updateDoc,
  getDoc,
  arrayUnion,
} from "firebase/firestore";
import { db } from "../configs";
export default function Ingredients() {
  const [form, setForm] = useState("");
  const auth = getAuth();
  const [imgArr, setImgArr] = useState([]);

  useEffect(() => {
      onAuthStateChanged(auth, (user) => {
        if (user) {
          const uid = auth.currentUser.uid;
          const docRef = doc(db, "users", uid);

          //loads the user's ingredients from firebase upon login
          const getUsers = async () => {
            const data = await getDoc(docRef);
            setImgArr(data.data().ingredients);
          };

          getUsers();
        } else {
          //clear the ingredients array upon logout
          setImgArr([]);
        }
      });

  }, [auth]);

  function handleChange(e) {
    setForm(e.target.value);
  }
  async function getResponse() {
    const params = new URLSearchParams({ q: form });
    const response = await fetch(
      `https://edamam-food-and-grocery-database.p.rapidapi.com/parser?ingr=${params}`,
      {
        method: "GET",
        headers: {
          "X-RapidAPI-Key":
            "29a63a7413msh8378b61a2e11cf3p192e62jsn53d83f1651fe",
          "X-RapidAPI-Host": "edamam-food-and-grocery-database.p.rapidapi.com",
        },
      }
    );

    const data = await response.json();

    return {
      label: data.parsed[0].food.label,
      image: data.parsed[0].food.image,
      id: Math.random(),
    };
  }
  //upload data to firebase and update the array of ingredients to display
  const clickHandler = async (e) => {
    try {
      setForm(e.target.value);
      //get response from edamam api
      const newImg = await getResponse();
      //redefining uid and docRef because unable to figure out how to make them global
      const uid = auth.currentUser.uid;
      const docRef = doc(db, "users", uid);
      //updates firebase with new ingredient
      updateDoc(docRef, {
        ingredients: arrayUnion({ name: form, image: newImg.image }),
      });
      setImgArr([...imgArr, newImg]);
    } catch (err) {
      console.error(err);
    }
  };
  //returns array with image of ingredients
  const thingsElements = imgArr.map((thing) => (

  ));

  return (
    <div className={`${styles.container} px-5`}>
      <Heading heading="Ingredients" info="Search by etc" />
      <Form
        label="Search Ingredients..."
        onChange={handleChange}
        value={form}
        placeholder="Search Ingredients..."
        clicked={clickHandler}
        icon={faCamera}
      />

{thingsElements}

  );
}


text:
Q: Sails view structure Hi I created a sails app completely for api using. It doesn't has a view file, now I have a html, css, js directory structure, which I want to show as a front page of my app. My html directory structure is following.
   +-ApiDocumentationApp
    |
    -script
    |
    -css
    |
    -images
    |
    --index.html

Now I don't want to use any templating engine like jade or ejs. Also I don't want to change the directory structure to sailsjs', asset and view system. Is there any way I can do it inside sailsjs?

A: Whatever your reluctance may be, by far the easiest solution here is to place all of your assets (scripts, css, images and index.html) under the /assets folder of your Sails app, and remove the default / route in /config/routes.js.  Then your index.html file will be served up by Sails by default.
The alternative would be to modify the default Gruntfile.js (in Sails v0.9.x) or the individual Grunt tasks under /tasks/config (in Sails v0.10.x) to point directly to your top-level asset folders and files rather than ./assets.  It's do-able, but error prone and less sustainable!


text:
Q: Maths brain teaser. Fifty minutes ago it was four times as many minutes past three o'clock Fifty minutes ago it was four times as many minutes past three o'clock.
How many minutes is it to six o'clock..?
I have got the solution online but have doubts in it :
There are 180 minutes between 3 o'clock and 6 o'clock.

Call x the number of minutes to 6 o'clock.

Then it is 180 - x minutes past 3 o'clock and 50 minutes ago it was 130 - x minuted past 3 o'clock.

Using the 4 times as many minutes past three o'clock bit we can form the equation

130 - x = 4x and solve it
130 = 5x
x = 26 so yes it is 26 minutes.

According to me :
How it is 4x in above equation , it should be 4(180-x) , and new equation should be 130-x = 4(180-x) , because it says that it was 4 times as many minutes past 3:00 PM.
please explain. according to the solution if it is 4x on the RHS of the equation , then according to me the question is wrong , and should be written as :
Fifty minutes ago it was four times as many minutes to 6 o'clock.

A: The figure below may help explain (apologies for the sub-optimal formatting)

A: I think the question means $4$ times as many minutes to $6$ o' clock from now.

A:
it says
Fifty minutes ago it was four times as many minutes past three o'clock
IT means X
WAS means =
FOUR TIMES means 4 *
AS MANY MINS PAST 3 means 130-X
so equation becomes X=4*(130-X);
                    X=104 mins
How many mins past 3 = 130-X=130-104= 26mins
example If a Father's age is 2 times the age of Son and Son's age is 30yrs. then the equation will be
                  X = 2*30; X = 60yrs.
             Not 2X = 30;   X = 15yrs.
Hope this explains the above question.


text:
Q: Exclude Items in Iterator I searching for a best practice in the Iterator interface of PHP.
Imagine I have a Menu with different Items. For each of the Items I can turn on or off the visibilty. Do you know a good place to place this filter? I thought about the Iterator::rewind() Method to do a seperate loop but dislike the fact of looping through the items a second time.
I think I see the wood for the trees. Hope you can help.

A: Erm, can't you just use continue ?
$exclude=array(0,2,3,5);
$data=array('Item1','Item2','Item3','Item4','Item5','Item6');
foreach($data as $id=>$value){
   if(in_array($id,$exclude))continue;
   echo $value.' ';
}

Considering you have a visibility property you'd do something like if(!visible)continue;

A: Have a look at the abstrakt FilterIterator class. Would look something like
class MyFilterIterator extends FilterIterator {
  public function accept () {
    $current = $this->current();
    // Test, if it is valid
    return $boolean;
  }
}

$iterator = new MyFilterIterator($myInnerIterator);

This way you also separate the menu from the filter, what makes it easier to replace the filter, if you want to change it.

A: This iterator implementation will scann only visible items.
You can tune the class in order to parametrize the filter.
class myItem implements Iterator {

    private $position = -1;

    public function __construct() {
        $this->position = -1; // mean unknown position
    }

    function rewind() {
        $this->position = -1;
        $this->next();
    }

    function current() {
        return $this->array[$this->position];
    }

    function key() {
        return $this->position;
    }

    function next() {
        $p = $this->position+1;
        // skip invisible items
        while ( isset($this->array[$p]) && (!$this->array[$p]->visible)) $p++;
        $this->position = $p;
    }

    function valid() {
        return isset($this->array[$this->position]);
    }
}


text:
Q: Calling a function pointer passed to another function So I can't seem to get this simple function pointer to run without seg faulting
Here is what I am working with:
test.c:
 #include <stdint.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>

 typedef void (*lwpfun)(void *);
 static void indentnum(void * num);

 int main(int argc, char *argv[]){
    lwp_create((lwpfun)indentnum,(void*)42);

    return 0;
 }

 static void indentnum(void *num) {
    printf("Indent num: %d\n", *(int *)num);
 }

lwp.c
 #include "stdio.h"
 #include <stdlib.h>

 void lwp_create( void (*lwpfun)(void *), void *arg){
    (*lwpfun)(arg); //Seg faulting
 }

A: You're passing num as (void*)42, which is a garbage pointer, then casting and dereferencing it.  Either pass the address of an int variable or (less portably) cast it back to int.

A: Change:
lwp_create((lwpfun)indentnum,(void*)42);

to:
lwp_create(indentnum, &(int []){42});  // use of a C99 compound literal

or in C89:
int x = 42;
lwp_create(indentnum, &x);

Your first form does not a pass a pointer to an object with the int value 42 but a pointer formed with the conversion of 42 to a pointer value.

A: lwp_create((lwpfun)indentnum,(void*)42);

No need to cast here, but you should take the address of your function to make it a function pointer (logical, isn't it?)
lwp_create(&indentnum,(void*)42);

(it WILL work without address of operator, this is just for clarity)
Next problem here:
 static void indentnum(void *num) {
    printf("Indent num: %d\n", *(int *)num);
 }

If you really want an int casted to a void * passed in here, that doesn't make it magically a pointer -- so just cast back to int ((int) num). dereferencing it will of course crash, why should 42 be a valid pointer?
Then here:
 void lwp_create( void (*lwpfun)(void *), void *arg){
    (*lwpfun)(arg); //Seg faulting
 }

The argument should have the type lwpfun (you made that typedef for a reason, right?) ... you can call it just like you call a regular function. So try this:
 void lwp_create(lwpfun callback, void *arg){
    callback(arg);
 }


text:
Q: How to make a navigation drawer outside of the Appbar? I am trying to make a container which contains a navigation drawer and a search box. I don't want to use an Appbar. I achieved the search box, but I cannot make a navigation drawer without an Appbar. I want it to look like the google maps app.
I have tried using Row(), Scaffold(), Align(), etc. but I haven't been a able to achieve it.

A: Just use a Scaffold, add a Drawer and open it programmatically using ScaffoldState.openDrawer(). You don't have to add an AppBar if you don't want to.

A: for me I used this code Scaffold(drawer:Drawer(),body:InkWell(ontap(){ Scaffold.of(context).openDrawer();},child: const Icon(Icons.Menu,color:Colors.white))); and work very well.


text:
Q: Set watermark on an image and save it in an original quality I upload a photo on web site and I want to set a watermark on it and save it in original quality. For testing I create C# application.
class Class1
    {
        public static string GetContentType(String path)
        {
            switch (Path.GetExtension(path))
            {
                case ".bmp": return "Image/bmp";
                case ".gif": return "Image/gif";
                case ".jpg": return "Image/jpeg";
                case ".png": return "Image/png";
                default: break;
            }
            return String.Empty;
        }

        public static ImageFormat GetImageFormat(String path)
        {
            switch (Path.GetExtension(path).ToLower())
            {
                case ".bmp": return ImageFormat.Bmp;
                case ".gif": return ImageFormat.Gif;
                case ".jpg": return ImageFormat.Jpeg;
                case ".png": return ImageFormat.Png;
                default: return null;
            }
        }

        public static void AddWaterMark(string sourceFile, string destinationPath)
        {

            // Normally you'd put this in a config file somewhere.
            string watermark = "http://mysite.com/";

            Image image = Image.FromFile(sourceFile);

            Graphics graphic;
            if (image.PixelFormat != PixelFormat.Indexed &&
                image.PixelFormat != PixelFormat.Format8bppIndexed &&
                image.PixelFormat != PixelFormat.Format4bppIndexed &&
                image.PixelFormat != PixelFormat.Format1bppIndexed)
            {

                graphic = Graphics.FromImage(image);
            }
            else
            {

                Bitmap indexedImage = new Bitmap(image);
                graphic = Graphics.FromImage(indexedImage);

                // Draw the contents of the original bitmap onto the new bitmap.
                graphic.DrawImage(image, 0, 0, image.Width, image.Height);
                image = indexedImage;
            }
            graphic.SmoothingMode = SmoothingMode.AntiAlias & SmoothingMode.HighQuality;

            Font myFont = new Font("Arial", 20);
            SolidBrush brush = new SolidBrush(Color.FromArgb(80, Color.White));

            //This gets the size of the graphic

            SizeF textSize = graphic.MeasureString(watermark, myFont);

            // Code for writing text on the image.

            PointF pointF = new PointF(430, 710);
            graphic.DrawString(watermark, myFont, brush, pointF);
            image.Save(destinationPath, GetImageFormat(sourceFile));
            graphic.Dispose();
        }

    }

//And using
class Program
    {

        private static string file1 = "C:\\1.JPG";
        private static string file1_withwatermark = "C:\\1_withwatermark.JPG";
        static void Main(string[] args)
        {
            Class1.AddWaterMark(file1, file1_withwatermark);
        }
}

The resolution of file1 is 3648x2736, size - 4Mb.
The first thing I don't understand is why does the file1_withwatermark isn't with watermark?
And the second one is why does the size of the file1_withwatermark is 1Mb, however the resolution of it is  3648x2736 too! I want  to save file1_withwatermark in original quality, that is the size of file1_withwatermark must be about 4Mb.

A: Partial answer; Note that JPEG is a lossy compression method. As a result, you will lose actual image quality in the saved image versus the original.
This applies even if you save in a higher quality level, resulting in a larger file than the original.
This is not a huge problem for one or two instances of resaving the file, but just keep this in mind when you consider "quality" and file size of your edited JPEG compressed images.


text:
Q: 10GHz photodetector I am using a PIN photodiode (Eudyna ERP1402GT602L 10Gb/s PIN+TIA receiver). I superpose two unmodulated lasers. When I try to observe their frequency response (sweep from 0-10GHz). There are dips (ups and downs). Can you please suggest how to make it more smoother. What could be the reason for it?
Is it because of the PCB ?
Further information added:
My setup: I have two Turnable laser sources controlled from computer. Laser1 (Current freq. 193.3550 THz, Grid:50GHz, Ch. Nr. 34, Optical pwr. +8.10dBm, Freq. Shift 0 to +5 Ghz). Laser2 (Current freq. 193.3450 THz, Grid:50GHz, Ch. Nr. 45, Optical pwr. +13.5dBm, Freq. Shift 0 to -5 Ghz). Than there is a 3dB coupler that combines these two lasers. After that we have optical power attenuator (it outputs -12dBm). Which goes to this photodiode and I than connect it directly to Spectrum analyzer without any cables.
I sweep like I change the freq. shift of both lasers. One towards 0 to +5GHz and laser2 towards 0 to -5GHz in steps of 0.05 GHz. (total 100 steps). This is how I attain the upper (red) graph. I select MAX HOLD on spectrum analyzer. and the peak starts to move towards right as the freq. shift increases. (the peak you can see at the right most point at 10GHz freq shift right now.)
I have also tested two other photodiodes (made by earlier students/teachers/i don't know. They have flat output freq. shift response over the 0-10GHz. ) On left bottom corner you can see it's output picture.

A:
There are dips (ups and downs). ... What could be the reason for it? Is it because of the PCB ?

The dips and peaks repeat roughly every 500 MHz in your frequency domain plot,
That suggests you're looking for a feature in your design that has an electrical length of about 0.3 m (so that one round trip through it takes 2 ns).
This could be the cables connecting your PCB to the spectrum analyzer.
But I think it's more likely it's happening in the optical part of your system. If one of the optical fibers in your system is about 20 cm long, look there first. My first guess would be that the fibers between your laser and the combiner is about this length. In this case, back-reflections from the fiber end can feed back into the laser and change its output power.
As a quick test, bend a fiber tightly once or twice around your thumb to create a crude attenuator. If the ripples in your SA plot change, you've probably found the source of your problem.

Can you please suggest how to make it more smoother.

If the root cause is back-reflections into the laser, you need to reduce the back-reflections that are getting back to the laser. If you have not been careful with the type of fiber termination you use, this could be easy to fix. You'd just get the fiber re-terminated with a higher-quality finish, for example APC ("angled physical contact"), and be sure to use the same termination type for all fibers you mate it with.
If you're already using APC or UPC fiber terminations, and still need to reduce back-reflection, there are a few more steps you can take:

*

*Replace butt-coupled fiber connections with fusion splices

*Anti-reflection (AR) coatings on the fiber facets

*Add an optical attenuator in-line with the output fiber (but then be careful not to introduce new back-reflections at the input to the attenuator)

*Add an optical isolator in-line with the output fiber.

Probably your laser manufacturer has already used one of these methods to reduce this effect, and you're just seeing the residual after most of it has been dealt with. In that case your best solution might be to choose a different laser, for example using an isolator rather than an attenuation for this purpose. That will, however, likely cost more than what you have now.


text:
Q: Does the HttpClientCertificate return any "signed" data? I'm working on a research story involving web-based Smart Card authentication. We've managed to set up an environment that requires Smart Card PIN entry during the authentication process, but there's some disagreement about whether the resulting HttpClientCertificate includes any information representing a signature (i.e., some arbitrary data encrypted with the PIN/private key on the Smart Card).
Does anyone have experience dealing with signatures like this? I'm having real trouble finding examples describing any kind of web-based Smart Card/PIN authentication and then recording data from the HttpClientCertificate that would verify the signature.

A: HttpClientCertificate, as the name suggests, contains the certificate (typically following X.509). So it does not contain "arbitrary" data encrypted with the PIN/private key on the smartcard (I assume you are actually trying to refer to session authentication data).
The certificate consists of only static data, which is

*

*the public key that the certificate was issued for,

*some metadata (such as identifying information for the key pair, parameters of the public-key cryptosystem, validity periods, usage constraints, etc.), and

*a signature over that static data, which is either issued by a cerificate authority (in case a certificate authority issued the certificate) or created with the private key that corresponds to the public key in the certificate (in case of a self-signed certificate / CA root certificate, though this should not be the case for TLS client certificates).

So HttpClientCertificate neither contains the private key associated with the certificate nor any dynamic data signed by the private key in order to authenticate the TLS session.


text:
Q: Is there a tool for generating historical process oriented resource usage statistics like top output? I've seen many tools like collectd, systats etc for recording general usage statistics, but I would like to find a tool for generating a historical graph of system resource consumption of the top 10 processes running in a system at sample intervals.
Think of like running top and taking the top 10 processes and saving to and RRD database to see what programs are putting a certain system under load over time.
Perhaps it's just a matter of configuration of something like systats, so perhaps there are some examples online of this.


text:
Q: Changing CKEDITOR value removes event listener I have a page with several CKEDITOR fields, where I catch a click event.
When clicking a certain button, the field is cleared, which unfortunately also removes the event listener.
This seems to be a known issue.
I have tried solutions provided elsewhere, but I'm still stuck.
code:
var aInst = CKEDITOR.instances;
for (var key in aInst){
    CKEDITOR.instances[key].on('contentDom', function() {
        console.log('initial or change');
        this.editable().attachListener(this.document,'click', function(){
            console.log('iframe click');
        });
    });
}

clicking in the initial, unchanged field will get me the 'iframe click' log.
when
CKEDITOR.instances[cpdId+'_flip_text_input'].setData('');

is activated, I get the 'initial or change' log, but clicking in the field isn't caught anymore.
This is already a version changed to a solution elsewhere (not working for me), because originally this.editable().attachListener(this.document,'click', function(){ was simply this.document.on('click', function(){
CKEDITOR v4.6.2
JQuery v3.1.1

A: I solved it in a hacky way. First of all, I replaced
CKEDITOR.instances[key].on('contentDom', function() {

with
CKEDITOR.instances[key].on('instanceReady', function() {

so the original attaching of the listener happens only on loading the page.
I removed
CKEDITOR.instances[cpdId+'_flip_text_input'].setData('');

completely and replaced with my 'hacky' solution: I removed everything inside the wrapper around the editor and textarea, refilled it with the 'original' code, re-activated the ckeditor on it and then attached the listener, works like a charm:
(var reFill = original html with textarea)

$('#'+cpdId+'_flip_text').empty();
$('#'+cpdId+'_flip_text').html(reFill);
$('#'+cpdId+'_flip_text').find('textarea').ckeditor(function(){
    var CKedit = CKEDITOR.instances[cpdId+'_flip_text_input'];
    CKedit.editable().attachListener(CKedit.document,'click', function(){
        //stuff to do on click
    });
});


text:
Q: How to give input date field for registration form in android? I tried to give datepicker by following android studio tutorial.
This is my MainActivity.java
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(),"datePicker");
    }
}

DatePickerFragment.java looks like
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(),"datePicker");
    }
}

When i try to run the code the following error i got in cosole :::
Error:(18, 20) error: no suitable method found for show(android.support.v4.app.FragmentManager,String)
method DialogFragment.show(android.app.FragmentManager,String) is not applicable
(argument mismatch; android.support.v4.app.FragmentManager cannot be converted to android.app.FragmentManager)
method DialogFragment.show(FragmentTransaction,String) is not applicable
(argument mismatch; android.support.v4.app.FragmentManager cannot be converted to FragmentTransaction)
Finally my activity_main.xml looks like
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.acknotech.kiran.dateexample.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/pick_date"
        android:onClick="showDatePickerDialog" />

</LinearLayout>

where i made wrong?
Thanks & Regards

A: Add this in your layout file
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.geelani.datepicker.MainActivity">

<TextView
    android:id="@+id/date"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

<Button
    android:id="@+id/pick_date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Pick date"
    android:onClick="showDatePickerDialog" />

and add this to your activity
public class MainActivity extends AppCompatActivity {
private int mYear,mMonth,mDay;
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Button pickDate = (Button) findViewById(R.id.pick_date);
    final TextView textView = (TextView) findViewById(R.id.date);

    final Calendar myCalendar = Calendar.getInstance();
    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener()
    {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
          // myCalendar.add(Calendar.DATE, 0);
            String myFormat = "yyyy-MM-dd"; //In which you need put here
            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
            textView.setText(sdf.format(myCalendar.getTime()));
        }

    };

    pickDate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);

            // Launch Date Picker Dialog
            DatePickerDialog dpd = new DatePickerDialog(MainActivity.this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {
                            // Display Selected date in textbox

                            if (year < mYear)
                                view.updateDate(mYear,mMonth,mDay);

                            if (monthOfYear < mMonth && year == mYear)
                                view.updateDate(mYear,mMonth,mDay);

                            if (dayOfMonth < mDay && year == mYear && monthOfYear == mMonth)
                                view.updateDate(mYear,mMonth,mDay);

                            textView.setText(dayOfMonth + "-"
                                    + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
            dpd.getDatePicker().setMinDate(System.currentTimeMillis());
            dpd.show();

        }
    });

}

}

A: Try this, as picker has its own view that would pop up on using show and adding these values make it this as default date:
   // On the click of registration field:
   Calendar now = Calendar.getInstance()
   new DatePickerDialog(classname.this, date, now
                .get(Calendar.YEAR), now(Calendar.MONTH),
                now(Calendar.DAY_OF_MONTH)).show(); // this shows the picker

A: Here is an example to use DatePickerDialog:
final Calendar calendar = Calendar.getInstance();

dateFormat = new SimpleDateFormat("MM/dd/yyyy");

DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

            Calendar cal = Calendar.getInstance();
            cal.set(year, monthOfYear, dayOfMonth);// Selected Date Goes Here.

            // You Can Do Anything You Want Here

        }
    }, calendar.get(Calendar.YEAR)
            , calendar.get(Calendar.MONTH)
            , calendar.get(Calendar.DAY_OF_MONTH));


text:
Q: Security error when trying to convert canvas data to image I have a project, in which I'm recording video with filters (Instagram-like). In one moment, I received a task to make snapshot functionality. So, I decided to write the next algorithm: create <canvas> -> get its' context -> apply chosen filter -> draw filtered image. This is the code for it:
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');

canvas.width = cameraView.videoWidth;
canvas.height = cameraView.videoHeight;

context.filter = window.getComputedStyle(cameraView, null).filter || window.getComputedStyle(cameraView, null).webkitFilter;
context.webkitFilter = context.filter;

context.drawImage(cameraView, 0, 0, canvas.width, canvas.height);
let src = canvas.toDataURL();

Then, I've tried three methods to save it on desktop:
1.
let img = new Image;
img.width = canvas.width;
img.height = canvas.height;
img.crossOrigin = 'Anonymous';
img.src = src;

2.
let link = document.createElement('a');
link.setAttribute('href', src);
link.setAttribute('download', 'blablabla.png');
link.click();

3.
document.location.href = src.replace('image/png', 'image/octet-stream');

The second method didn't work at all and the other two methods gave me Security error: operation is insecure in console. So, I have read, that the problem is in headers and CORS. Then, I've set up an Apache server on my local machine, created .htaccess, echoed Header add Access-Control-Allow-Origin "*" to it. But security error is still here.
Also, at the start of the project, I've used Node.js Express server and tried to send headers from there, but it also didn't worked for me.
Also, there is other solution, html2canvas, but I prefer to use plain js and not to use extra libraries.
UPD: if I remove code, where I'm applying filter to context, everything works fine. I know that it's caused by restrictions for ambiguous image loads, but still hoping, that I can solve this problem.


text:
Q: how to connect two controllers I have these two controllers about stories and categories and they work alone. Now I want to add choosing a already created category when I add news. How should I connect them and how should I show all categories in new.html.erb with select tag?
class StoriesController < ApplicationController
  def index
    @stories = Story.all
  end

  def show
    @story = Story.find(params[:id])
  end

  def new
    @story = Story.new
  end

  def create
    @story = Story.new(params[:story])

    if @story.save
      redirect_to stories_path, :notice => "Your story was saved"
    else
      render "new"
    end
  end

  def edit
    @story = Story.find(params[:id])
  end

  def update
    @story = Story.find(params[:id])

    if @story.update_attributes(params[:story])
      redirect_to stories_path, :notice => "Your story has been updated"
    else
      render "edit"
    end
  end

  def destroy
    @story = Story.find(params[:id])
    @story.destroy
    redirect_to stories_path, :notice => "Your story has been deleted"
  end
end

class CategoriesController < ApplicationController
  def index
    @categories = Category.all
  end

  def new
    @category = Category.new
  end

  def create
    @category = Category.new(params[:category])

    if @category.save
      redirect_to categories_path, :notice => "Your category was saved"
    else
      render "new"
    end
  end

  def edit
    @category = Category.find(params[:id])
  end

  def update
    @category = Category.find(params[:id])

    if @category.update_attributes(params[:category])
      redirect_to categories_path, :notice => "Your category has been updated"
    else
      render "edit"
    end
  end

  def destroy
    @category = Category.find(params[:id])
    @category.destroy
    redirect_to categories_path, :notice => "Your category has been deleted"
  end
end

A: It's not that you need to connect the controllers together. You really just need StoriesController to query the category list, and place it into a class variable, so the view can utilize it.
class StoriesController < ApplicationController
  ...
  def new
    @categories = Category.all
    @story = Story.new
  end

A: You could try with:
# app/controllers/stories_controller.rb
def new
  @categories = Category.all
  @story = Story.new
end

# app/views/stories/_form.html.erb
<%= form_for @story do |f| %>
  #....
  <%= f.collection_select :category_id, @categories, :id, :title %>

A: Hey in the controller u can access only the title of the categories. make a array of titles of cattegories rather than the array of category objects.
    # app/controllers/stories_controller.rb
    def new
     @categories = Category.all.map(&:title)
     @story = Story.new
    end


text:
Q: Como eliminar una fila de una datatable mi pregunta es, como puedo hacer para eliminar la primera fila de un datatable por medio de un botón (fuera de la tabla)
me metí a ver ejemplos en la pagina de datatable pero no me funciona.
Muchas gracias

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            $320,800

            Cedric Kelly
            Senior Javascript Developer
            Edinburgh
            22
            2012/03/29
            $433,060

            Name
            Position
            Office
            Age
            Start date
            Salary

    <button id="aiuda" onclick="borrar()" class="Eliminar">Eliminar primera fila</button>

A: Puedes borrar la primera fila del tbody sin utilizar el plugin de DataTable asi:
function borrar () {

        var myTable = $('#example');

        myTable.find( 'tbody tr:eq(0)' ).remove();
    }

A: Utilizando la api de datatables podes hacerlo de la siguiente manera:
myTable.row(':eq(0)').remove().draw();

El beneficio de usarlo así es que rearma la tabla, por ejemplo es importante si tenes paginado.
EDIT
Solo a método de ejemplo agregue otro botón para diferenciar como borrar la primerísima fila de la tabla, de como borrar la primera fila de la pagina actual, a raiz de esto se evidencia mejor el tema del "rearmado" de la tabla nuevamente en cada remove() y las ventajas de utilizar la api si uno tiene paginado.
Te dejo un ejemplo:

var myTable = $('#example').DataTable({
  "pageLength": 2
});

function borrarPrimeraDeTabla () {
  myTable.row(':eq(0)').remove().draw();
}

function borrarPrimeraDePaginaActual () {
  myTable.row(':eq(0)', { page: 'current' }).remove().draw();
}

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            $320,800

            Cedric Kelly
            Senior Javascript Developer
            Edinburgh
            22
            2012/03/29
            $433,060

            juan Kelly
            Senior Javascript Developer
            Edinburgh
            22
            2012/03/29
            $433,060

            pedro Kelly
            Senior Javascript Developer
            Edinburgh
            22
            2012/03/29
            $433,060

            carlos Kelly
            Senior Javascript Developer
            Edinburgh
            22
            2012/03/29
            $433,060

            micho Kelly
            Senior Javascript Developer
            Edinburgh
            22
            2012/03/29
            $433,060

            Name
            Position
            Office
            Age
            Start date
            Salary

    <button id="aiuda" onclick="borrarPrimeraDeTabla()" class="Eliminar">Eliminar primera fila de toda la tabla</button>
        <button id="aiuda" onclick="borrarPrimeraDePaginaActual()" class="Eliminar">Eliminar primera fila de pagina actual</button>


text:
Q: numpy.cos works significantly longer on certain numbers TLDR:
numpy.cos() works 30% longer on a particular numbers (exactly 24000.0 for example). Adding a small delta (+0.01) causes numpy.cos() to work as usual.
I have no idea why.

I stumbled across a strange problem during my work with numpy. I was checking cache work and accidentally made a wrong graph - how numpy.cos(X) time depends on X. Here is my modified code (copied from my Jupyter notebook):
import numpy as np
import timeit
st = 'import numpy as np'
cmp = []
cmp_list = []
left = 0
right = 50000
step = 1000
# Loop for additional average smoothing
for _ in range(10):
    cmp_list = []
    # Calculate np.cos depending on its argument
    for i in range(left, right, step):
        s=(timeit.timeit('np.cos({})'.format(i), number=15000, setup=st))
        cmp_list.append(int(s*1000)/1000)
    cmp.append(cmp_list)

# Calculate average times
av=[np.average([cmp[i][j] for i in range(len(cmp))]) for j in range(len(cmp[0]))]

# Draw the graph
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.plot(range(left, right, step), av, marker='.')
plt.show()

The graph looked like this:

Firstly I thought it was just a random glitch. I recalculated my cells but the result was nearly the same. So I started to play with step parameters, with number of calculations and averages list length. But everything had no effect to this number:

And even closer:

After it, range was useless (it can't steps with floats) so I calculated np.cos manually:
print(timeit.timeit('np.cos({})'.format(24000.01),number=5000000,setup=st))
print(timeit.timeit('np.cos({})'.format(24000.00),number=5000000,setup=st))
print(timeit.timeit('np.cos({})'.format(23999.99),number=5000000,setup=st))

And the result was:
3.4297256958670914
4.337243619374931
3.4064380447380245

np.cos() calculates exactly 24000.00 on 30% longer, than 24000.01!
There were another strange numbers like it (somewhere around 500000, I don't remember exactly).
I looked through numpy documentation, through its source code, and it had nothing about this effect. I know that trigonometric functions use several algorithms depends on value size, precision etc, but it is confusing for me that exact numbers can be calculated way longer.
Why np.cos() has this strange effect? Is it some kind of processor side-effect (because numpy.cos uses C-functions that depends on processors)? I have Intel Core i5 and Ubuntu installed, if it will help for someone.

Edit 1: I tried to reproduce it on another machine with AMD Ryzen 5. Results are just unstable. Here is graphs for three sequential runs of the same code:
import numpy as np
import timeit

s = 'import numpy as np'
times = []
x_ranges = np.arange(23999, 24001, 0.01)
for x in x_ranges:
    times.append(timeit.timeit('np.cos({})'.format(x), number=100000, setup=s))

# ---------------

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(x_ranges, times)
plt.show()

Well, there is some patterns (like mostly consistent left part and non-consistent right part), but it differs a lot from Intel processors runs. Looks like it is really just special aspects of processors, and AMD behaviour is much more predictable in its indeterminism :)
P.S. @WarrenWeckesser thanks for ``np.arange``` function. It is really useful, but it changes nothing in results, as expected.

A: The slowness in computing the result for those special numbers may be related to exact rounding and table maker's dilemma.

To illustrate, suppose you are making a table of the exponential
  function to 4 places. Then exp(1.626) = 5.0835. Should this be rounded
  to 5.083 or 5.084? If exp(1.626) is computed more carefully, it
  becomes 5.08350. And then 5.083500. And then 5.0835000. Since exp is
  transcendental, this could go on arbitrarily long before
  distinguishing whether exp(1.626) is 5.083500...0ddd or
  5.0834999...9ddd.

Though, because of this reason the IEEE standard does NOT require transcendental functions to be exactly rounded, it is possible that the implementation of the math.cos function is hit by this problem while doing its best to compute the most accurate result and then figuring out that the effect is not worth the effort.
To demonstrate that this is the case for some number X one will have to compute the value of math.cos(X) with high precision and check its binary representation - the representable part of the mantissa must be followed by one of the following patterns:

*

*1 and a long run of 0's

*0 and a long run of 1's (when the value is computed with precision lower than required to accommodate all the 1's in the run, this case appears as the first one)

Therefore, the probability that a number will be a slow argument to a transcendental function is 1/2n where n is the maximal length of the above pattern seen by the algorithm after which it gives up trying to arrive at the exactly rounded result.

Demonstration highlighting the representable part of the mantissa for the IEEE 754 double precision case (where mantissa has 53 bits):
In [1]: from mpmath import mp

In [2]: import math

In [3]: def show_mantissa_bits(x, n, k):
   ...:     print(bin(int(mp.floor(abs(x) * 2**n)))[2:])
   ...:     print('^'*k)
   ...:

In [4]: mp.prec = 100

In [5]: show_mantissa_bits(mp.cos(108), 64, 53)
110000000100001011001011010000110111110010100011000011000000000
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In [6]: show_mantissa_bits(mp.cos(108.01), 64, 53)
101110111000000110001101110001000010100111000010101100000100110
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In [7]: show_mantissa_bits(mp.cos(448), 64, 53)
101000101000100111000010111100001011111000001111110001000000000
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In [8]: show_mantissa_bits(mp.cos(448.01), 64, 53)
101001110110001010010100100000110001111100000001101110111010111
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In [9]: show_mantissa_bits(mp.cos(495), 64, 53)
11001010100101110110001100110101010011110010000000000011111111
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In [10]: show_mantissa_bits(mp.cos(495.01), 64, 53)
11010100100111100110000000011000110000001001101100010000001010
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In [11]: show_mantissa_bits(mp.cos(24000), 64, 53)
11001000100000001100110111011101001101101101000000110011111111
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In [12]: show_mantissa_bits(mp.cos(24000.01), 64, 53)
10111110011100111001010101100101110001011010101011001010110011
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


text:
Q: How to calculate time difference between current and previous row in MySQL I have mysql table t1 like this :

What i want to do is do calculations between all rows and save the value in new coloumn called diff
TICKETID| DATENEW  | DIFF
16743     12:36:46   0
16744     12:51:25   15.  minute
16745     12:57:25   6.5  minute
..........
.......
etc

i know there are similar questions ,but ive tried all of the solutions
posted here with no success,so how to solve this query ???

A: To get the time difference in minutes between the current and previous row, you can use timestampdiff on datenow and the previous time, which you can get via subquery:
select ticketid, datenew,
    timestampdiff(minute,datenew,(select datenew from mytable t2
        where t2.ticketid < t1.ticketid order by t2.ticketid desc limit 1)) as diff
from mytable t1

Update
Here's another way using a variable to store the previous datenew value that might be faster:
select ticketid, datenew, timestampdiff(minute,datenew,prevdatenew)
from (
    select ticketid, datenew, @prevDateNew as prevdatenew,
      @prevDateNew := datenew
    from mytable order by ticketid
) t1

A: select
 t1.*
,coalesce(timestampdiff(MINUTE,t2.dt,t1.dt),0) as tdiff
from t t1 left join t t2
on t1.id = t2.id+1
order by t1.id

As you are only looking for a difference between the current row and the next, you can join on the next row and calculate the time difference in minutes.
Note: This assumes there are no missing id's in the table. You might have to change the join condition if there were missing id's.
SQL Fiddle: http://www.sqlfiddle.com/#!9/4dcae/15


text:
Q: glusterfs geo-replication - server with two interfaces - private IP advertised I have been trying to setup a geo replication with glusterfs servers. Everything worked as expected in my test environment, on my staging environment, but then i tried the production and got stuck.
Let say I have
gluster fs server is on public ip 1.1.1.1
gluster fs slave is on public 2.2.2.2, but this IP is on interface eth1
The eth0 on gluster fs slave server is 192.168.0.1.
So when i start the command on 1.1.1.1 (firewall and ssh keys are set properly)
gluster volume geo-replication vol0 2.2.2.2::vol0 create push-pem

I get an error.
Unable to fetch slave volume details. Please check the slave cluster and slave volume.
geo-replication command failed
The error is not that important in this case, the problem is the slave IP address
2015-03-16T11:41:08.101229+00:00 xxx kernel: TCP LOGDROP: IN= OUT=eth0 SRC=1.1.1.1 DST=192.168.0.1 LEN=52 TOS=0x00 PREC=0x00 TTL=64 ID=24243 DF PROTO=TCP SPT=1015 DPT=24007 WINDOW=14600 RES=0x00 SYN URGP=0

As you can see in the firewall drop log above, the port 24007 of the slave gluster daemon is advertised on private IP of the interface eth0 on slave server and should be the IP of the eth1 private IP. So master cannot connect and will time out
Is there a way to force gluster server to advertise interface eth1 or bind to it only?
I use cfengine and ansible to push configuration, so binding to Interface could be a better solution than IP, but whatever solution will do.
Thank you in advance.

A: GlusterFS has no notion of the network layer. Check your routes. If the next-hop for your geo-replication slave is on eth1, then gluster will open a port on that interface for the slave IP address.
Also make sure your firewall is configured to forward geo-replication traffic on this port.

A: I've encountered this issue but in a different context.
I was trying to geo-replicate two nodes which were both behind a NAT (AWS instances in different regions).
When the master connects to the slave via the public IP to check for volume compatability/size and other details, it retrieves the hostname of the slave, which usually resolves to something that only has meaning in that remote region.
Then it uses that hostname to dial back to the slave when later setting up the session, which fails, as that hostname resolves to a private IP in a different region.
My workaround for the issue was to use hostnames when creating the volumes, probing for peers, and establishing geo replication, and then add a /etc/hosts entry mapping slaves hostname which usually resolves to its private IP to its public IP, rather than it's private IP.
This gets you to the point where you establish a session, but I haven't had any luck actually getting it to sync, as it uses the wrong IP somewhere long the way again.
Edit:
I've actually managed to get it running by adding /etc/hosts hacks on both sides.


text:
Q: accept leading number in input field

<input type="number" name = "search_number" id="search_number"  pattern="[0-9]\d*"  class="form-control form-control-sm">

when adding number 00107 it takes only 107, is there any solution that it takes 00107 instead of 107 and if we input 107 it take it as 107 I don't want to add default 00 in input because database contain some data that don't contain 00. if anyone has any solution kindly answer me.

A: You can use text box with custom validation. Here isNumberKey only accept the number for each character

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

function show(){
  console.log(document.getElementById('test').value)
}
<input id="test" type="text" onkeypress="return isNumberKey(event)"/>

<button type="button" value="show value" onClick="show()">show value</button>


text:
Q: Using babelify in Gulp, importing css results to unexpected token "{" I'm importing a css in my jsx, and using gulp with browserify and babelify. Somehow I'm getting this error:
error screenshot
I have the following jsx which imports a css:
import '../../css/app.css';

function Square(props) {
    return (
        <button className="squares" onClick={props.onClick}>
          {props.value}
        </button>
        );
} ...

Then I have this in my gulp file:
var bundler = watchify(browserify(files[i], {
    debug : true
}).transform(babelify, {
    ignore : /\.([json]|[css])$/,
    presets : [ 'es2015', 'react', 'env' ]
}), {
    poll : true
}); ...

In my package.json file, I have thos config for browserify:
  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": [
            "es2015",
            "env",
            "react"
          ]
        }
      ]
    ]
  },

And I have the following dependencies:
  "devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-preset-env": "^1.5.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babelify": "^7.3.0",
    "browserify": "^14.4.0",
    "glob": "^7.1.2",
    "gulp": "^3.9.1",
    "gulp-cli": "^1.3.0",
    "gulp-exit": "0.0.2",
    "gulp-sourcemaps": "^2.6.0",
    "gulp-uglify": "^3.0.0",
    "vinyl-buffer": "^1.0.0",
    "vinyl-source-stream": "^1.1.0",
    "watchify": "^3.9.0"
  }

As you can see, I may have added more presets that I need, I'm really new to this and I thought that maybe babel doesn't know that it's looking at a css file and treats it as jsx.

A: I found out what I was missing, "browserify-css".
I changed my gulpfile into:
var bundler = watchify(browserify(files[i], {
    debug : true
}).transform(babelify.configure({
    presets : [ 'es2015', 'react', 'env' ]
})).transform(browserifyCss), {
    poll : true
});

A: I would be careful with importing CSS directly like this. It's actually a Webpack-specific feature, and not part of the ES6 spec to arbitrarily import static assets like that. You're now writing source code that directly depends on having browserify-css or webpack, and if you later decide to switch out build systems, it's going to be a hassle to refactor your code to do it the proper way (just including css in a link element in your html file like you would normally)


text:
Q: How to display private Google Calendar events on my localhost start page without a webserver? I'm practicing HTML/CSS/JS using localhost as a browser start page and I'd like to display the next 24 hours of my events from my Google Calendar.  However, it seems so far that a webserver (I used Python) needs to be running first.  Is there a simple way to just read these events via JavaScript?  Also, my calendar is not public.  I've checked all the documentation I could find and haven't found any solution.
I'm still learning, so I appreciate any help/suggestions you can give.  Thanks!

A: If you already have a python web server running for your application, you just have to authorize it to grab data on your behalf.
I recommend you go thru the Python Quickstart tutorial to learn how to authenticate and talk with the Google APIs.
Once you have that setup and running, you can then integrate those methods to your webserver logic.
This will depend on which library or framework you are using for your application.
Hope this helps!


text:
Q: Insert and delete from "associations table on EF model" I have to tables "ALUMNOS" and "MATERIAS". In SQL exist another table "ALUMNOS BY MATERIAS". I know this is not necessary in EF model, because exists the properties navigation. But how can insert or delete from this " associations table"??
Thanks in advance!!
Guille

A: The only way would be to remove the link between the Materia and Alumno objects before saving again. This way they are individual objects or only contain links that are required. This will set the mapping table correctly.

A: Created the tables and got the objects like you have got. To insert a new row, I do the following
StackExchangeExampleEntities exchangeExampleEntities = new StackExchangeExampleEntities();
        Alumno alumno = new Alumno() {AlumId = 2, Description = "aldesc"};
        Materia materia = new Materia() {materia_Id = 2, description = "mdesc"};
       materia.Alumnos.Add(alumno);// attach the relationship
       exchangeExampleEntities.Materias.Add(materia);
       exchangeExampleEntities.SaveChanges();

To Delete the mapping table, I clear down the collection in one side ( you can use either collection - Alumno or materia)
StackExchangeExampleEntities exchangeExampleEntities = new StackExchangeExampleEntities();
        Materia materiaFetched = exchangeExampleEntities.Materias.Single(m => m.materia_Id == 2);
        materiaFetched.Alumnos.Clear();
        exchangeExampleEntities.SaveChanges();

If you just want the mapping table to be used, then add a new entityframework file and then select only the mapping table( dont select any thing else). This will create entity just for this mapping table in the context.
Now you can use it like this:
 StackExchangeExampleEntities1 exchangeExampleEntities1 = new StackExchangeExampleEntities1();
        MateriaAlumono s = exchangeExampleEntities1.MateriaAlumonoes.First();
        Console.WriteLine(s.Alumuno_id);


text:
Q: ASP.NET MVC on IIS 7.5 - Error 403.14 Forbidden I'm running Windows 7 Ultimate (64 bit) using Visual Studio 2010 RC. I recently decided to have VS run/debug my apps on IIS rather than the dev server that comes with it.
However, every time I try to run an MVC app, I get the following error:

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory. Detailed

Error Information

Module    DirectoryListingModule

Notification  ExecuteRequestHandler

Handler   StaticFile Error

Code  0x00000000 Requested

URL   http://localhost:80/mySite/

Physical
Path  C:\myProject\mySite\

Logon Method  Anonymous Logon

User  Anonymous

I placed a default.aspx file in the directory and I received the following error:

HTTP Error 500.21 - Internal Server
Error Handler
"PageHandlerFactory-Integrated" has a
bad module "ManagedPipelineHandler" in
its module list

Are there any other steps I forgot to take to get this working?
Notes: I installed IIS 7.5 after installing VS 2010 RC. I used the built-in "Create Virtual Directory" button under the "Web" tab in the MVC project's "Properties" in Visual Studio 2010. I made sure that the application is using the ASP.NET 4 App Pool.
Below are the installed features of IIS I have.

A: Make sure you have is the following set in your web.config:
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

Better solution:
Even though above solution works absolutely fine, it can cause other problem as it runs all your registered HTTP modules on every request (even on every request of .jpg .gif .css .html .pdf etc) and it is obviously waste of resource. Instead
<system.webServer>
<modules>
  <remove name="UrlRoutingModule-4.0"/>
  <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" preCondition="" />
</modules>
</system.webServer>

Make sure preCondition attribute is empty means it will run on all requests. [Read more](http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html,"Read original post")

A: Also u can switch AppPool to Integrated mode. Thnx to Michael Bianchi (https://stackoverflow.com/a/7956546/1143515), I only want to underline that.

A: For me on an Azure Server 2012 R2 IIS 8.5 VM with an Asp.Net MVC 5 app (bin deployed MVC 5) I had to do the following from an elevated cmd prompt even though I had 4.5 already installed:
dism /online /enable-feature /featurename:IIS-ASPNET45

Source: http://support.microsoft.com/kb/2736284
I also brute force installed all IIS features with the following PowerShell:
import-module servermanager
add-windowsfeature web-server -includeallsubfeature

Source: http://www.iis.net/learn/install/installing-iis-85/installing-iis-85-on-windows-server-2012-r2
Now my app is working.

A: We had a MVC application moved to a new server. .NET 4 and MVC 3 was installed, but we still got "Error 403.14″. In this case, this meant that IIS did not understand that it was dealing with a MVC application, it was looking for the default page.
The solution was simple: HTTP Redirection was not installed on the server.
Server Manager – Roles – Web Server (IIS) – Roles Services – HTTP Redirection: Not installed. Installed it, problem solved.

A: Also if your app is precompiled you should have
PrecompiledApp.config
in the root folder of your app otherwise you could get HTTP Error 403.14 as well.

A: ASP.NET 4 was not registered in IIS. Had to run the following command in the command line/run
32bit (x86) Windows

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

64bit (x64) Windows

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Note from David Murdoch's comment:

That the .net version has changed
  since this Answer was posted. Check
  which version of the framework is in
  the %windir%\Microsoft.NET\Framework64
  directory and change the command
  accordingly before running (it is
  currently v4.0.30319)

A: Another reason why someone might get this error is if the file Global.asax is not in the root folder anymore.

A: Another possible solution, if you move around your global.asax, make sure the markup points to the correct MvcApplication class. Hopefully this will save someone in future.

A: I had used the WebDeploy IIS Extension to import my websites from IIS6 to IIS7.5, so all of the IIS settings were exactly as they had been in the production environment.  After trying all the solutions provided here, none of which worked for me, I simply had to change the App Pool setting for the website from Classic to Integrated.

A: I have met the same 404.14 problem suddenly. Finally the problem had been fixed by unchecking "precompile while publishing" in the publish profile settings.

A: I altered my default route at one point from:
routes.MapRoute(
"Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }

To:
routes.MapRoute(
"Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index" }

Which gave me your error. Glad someone mentioned routing because I probably would've been on this forever.

A: In my case ASP.NET 4.5 is not installed on the server so installing ASP.NET 4.5 fixed the issue.

A: You can solve this error by running cmd as admin
than

Do the same as in picture  for windows 32 bit
Just make changes in 64 bit as framework64 instead of framework only
Than go to iis and refresh the site
If u still got some error make changes in application pool

A: I had another problem that led to this issue.

*

*I had ensured my app pool was running .net 4 in integrated mode

*I had run aspnet_regiis.exe -i

*I had checked folder permissions were set correctly for the account running my app pool

None of these things worked.  It turned out that in my web.config under system.webserver > modules I had the following:
<remove name="WindowsAuthentication" />

Obviously this removed the windows authentication module which seemed to somehow knock everything off kilter.
I hope this helps someone, as this cost me most of an evening!

A: The UI is a bit different in the newer versions of Windows Server. Here is where you have to enable ASP.Net in order to get it working on IIS

A: I was also receiving this error and discovered that "HTTP Redirection" was not turned on in Windows Server. This blog post points this out as well: http://blogs.msdn.com/b/rjacobs/archive/2010/06/30/system-web-routing-routetable-not-working-with-iis.aspx

A: Adding another solution for this issue.
in my Global.asax.cs file I had disabled attempted php files from being consumed by the MVC pipeline using the following:
routes.IgnoreRoute( "{*php}" );
I had done these previously in a MVC2 project and it worked fine, but doing this in my MVC 3 app caused the issue reported above.

A: Yet another reason this can happen - your RouteConfig.cs or WebApiConfig.cs are invalid.
In my case, I had a route defined as such (note the parenthesis instead of curly brace):
...
routeTemplate: "api/(something}"
...

A: Please note for Windows 8 users you need to add/remove windows components and remove the version of .net reboot then re-install in order to register it with IIS. I presume this happens if you get .net 4.5 from visual studio and install IIS afterwards.

A: As strange as it may seem, reinstalling IIS was what has worked for me, with the following command run from inside the .net version folder:
aspnet_regiis.exe /i

When I first run this command, I begun getting the HTTP Error 403.14. But once I runned the command again it solved the problem.
Obs: Another thing I also did was to remove HTTP Redirect from the server features in Server Management screen before reiinstalling IIS. Maybe this also had an impact in solving the problem, but I am not sure. So, if reinstalling IIS still doesn't work, please try removing HTTP Redirect and try again. Hopefully it may work for you too.

A: One more thing to make sure you have is the following set in your web.config:
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

A: According to http://support.microsoft.com/kb/980368, try installing this KB for your system. If you are seeing 404s it might be because you don't have this update -- and the isapi module just isn't getting found and there's not a lot you can do about that without this!

A: To solve this problem without having to resort to 32 bit mode you will have to update the source code for this project
public static void RegisterUrlRoutesFromAttributes(RouteCollection routes)
{
    // Enumerate assembly for UrlRoute attributes.
    List<MapRouteParams> routeParams = new List<MapRouteParams>();
    AppDomain.CurrentDomain.GetAssemblies()
        .ToList()
        .ForEach(assembly => routeParams.AddRange(GetRouteParamsFromAttributes(assembly)));

I have raised this issue as a discussion on the discussion board at the IT cloud codeplex project.
http://itcloud.codeplex.com/discussions/262000

A: If you're running IIS 8.5 on Windows 8, or Server 2012, you might find that running mvc 4/5 (.net 4.5) doesn't work in a virtual directory. If you create a local host entry in the host file to point back to your local machine and then point a new local IIS website to that folder (with the matching host header entry) you'll find it works then.

A: This worked for me and it might be useful to another one.
Maybe all components required are not present or/and not all are registered correctly. In order to solve this, try to uncheck all options inside Control Panel -> Turn Windows features on or off -> Internet Information Services -> World Wide Web Services -> Application Development Features,   uncheck all options and recheck all then reset the IIS and check if the problem is solved.

A: I created a new namespace (and therefore folder) identical to the route to a controller (e.g. MvcApp/Test/SomeClasses.cs and MvcApp/Controllers/TestController.cs). This resulted also in a 403.14!

A: For me, the solution was to add the NuGet package Microsoft.AspNet.WebPages (plus it's Razor and Infrastructure dependencies) to my web project.
Infrastructure had to be forcefully reinstalled as it was not added as a reference at first.

A: In my case .NET CRL Version in Application pool prppertires was set to No managed code (do not know why).
Setting it to .NET CRL Version v4.0.30319 solved the problem.


text:
Q: JMS corrupting bytes message I'm sending a JMSBytesMessage that I'm reading in from a file. I can write byte array back out to a file with no issues. But if I sent it to the JMS queue and retrieve it and try to print it to a file, it's unreadable.
Files.readAllBytes(Paths.get(file.getPath()))

Files.write(filename, message.getBytes(), StandardOpenOption.CREATE);

I've encoded it to Base64, which makes it two KB larger after retrieving it from the queue, but doesn't make it into anything I can read. What don't I understand about BytesMessages?

A: Your code is ...strange or incomplete
How do you get the bytes from the JMS message? Is message the JMS BytesMessage you get from the queue?? There is no getBytes()method in class BytesMessage.
To get the bytes from a BytesMessage, do the following:
BytesMessage msg = ... // Obtain the message from the Q
byte[] data = new byte[(int) msg.getBodyLength()];
msg.readBytes(data);

Then to write the bytes to a file
Files.write(filename, data, StandardOpenOption.CREATE);


text:
Q: How can I uninstall python3.5.0 installed from source code? I installed python 3.5.0 from the source code available at python.org. How can I remove that installed package?

A: From this source
You can do :

*

*make clean removes any intermediate or output files from your source / build tree

*If you can, running make uninstall will work.

*The last option is you have to manually uninstall it. Running make -n install
Note : You must cd the file location where you make install

A: locate python3.5 | xargs sudo rm -rf $1

A: I think this will work. Try this.
pip uninstall python==3.5.0

However, if python comes with dependencies, do not uninstall them.


text:
Q: What did the Imperial Senate accomplish during its existence? The Imperial Senate was generally considered to be an ineffectual component of the Imperial government during its existence, since the Emperor has taken from the Senate most of its powers.
Nonetheless, did the Imperial Senate ever accomplish anything of consequence?

A: The Imperial Senate held relatively little power, and was mostly a facade. The senate solely existed to give the illusion of democracy to the citizens of the empire. In reality, the Emperor was completely in charge, though in both Canon and Legends, the senate held a little bit of power.
In canon: Essentially nothing. While we know that they could pass laws, it was the Emperor who had the final call, and rarely saw the senate's ideas through.
In Legends: Nothing Major. The senate had influence of the imperial budget, the judicial system, the legislative system, and possibly the military. The executive power held by the republic senate was stripped away. There were some laws passed by the senate, but the Emperor still had total control.
However: senators such as Leia Organa and Mon Mothma had some diplomatic immunity, which when combined with their connections to other political leaders, meant that they were in the perfect position to help the rebel alliance. In some sense, the oppressed senate helped form and guide the rebel alliance.


text:
Q: lxml findall() problem Just trying to make a simple program to get wikipedia's recentchanges and parse that XML file.
I stuck at the point where findall() not working. What I'm doing wrong?
import urllib2
from lxml import etree as ET

result = urllib2.urlopen('http://en.wikipedia.org/w/api.php?action=query&format=xml&list=recentchanges&rcprop=title|ids|sizes|flags|user|timestamp').read()

xml=ET.fromstring (result)

print xml[0][0][0].attrib # that works!

print xml.findall ('api/query/recentchanges/rc') # that don't!

A: I suspect the root node is the topic node, so it's looking for a node named "api" inside of the root node. If so, both of the following will work:
query/recentchanges/rc

/api/query/recentchanges/rc


text:
Q: What are the steps this JavaScript program takes Can someone please explain the steps this program takes and the order in which they are taken in order to produce the result "false"
function negate(func) {
  return function(x) {
    return !func(x);
  };
}
var isNotNaN = negate(isNaN);
show(isNotNaN(NaN));

A:   // 1. A function called "negate is declared
function negate(func) {  // 3. The "isNaN" function is received by negate().

  return function(x) {   // 4. A function is returned from the negate() call
    return !func(x);     //     that invokes the "isNaN" function, and returns
  };                     //     the logical opposite of its return value.

}

                  // 2. The built in "isNaN" function is passed to negate()
var isNotNaN = negate(isNaN);
 // 5. The function returned from negate() is assigned to the "isNotNaN" variable

         // 6. The "isNotNaN" function is invoked, and passed the "NaN" value.
show(isNotNaN(NaN));
 // 7. The result returned from "isNotNaN" is passed to the show() function.

The end result is that you have a function that returns the opposite of the isNaN function.
Seems like overkill when you can just call isNaN with ! yourself.
show( !isNaN(NaN) );  // gives the same result

A: *

*Defines negate() function.

*Sets variable isNotNaN to return of negate(isNaN).

*negate() returns a function, whilst keeping scope to func (in this case isNaN).

*Call show() with isNotNan(NaN) (passing not a number to negation of isNaN). Same as ( ! isNaN(NaN)).

A: The code defines a function "negate" that takes as a parameter another function. The "negate" function itself returns yet another function, one which returns the boolean opposite of the result of calling the parameter function on the parameter passed in.
Then the code defines a variable, "isNotNan", and sets it equal to the result of calling "negate" with a function (which we don't see here) called "isNaN".  Calling that function with the constant NaN is effectively the same as calling !isNaN(NaN), which is false because NaN is NaN.

A: when you call the function negate it creates a closure around the function you pass into it. so when you call isNotNaN it is actually running isNaN which has been enclosed within the function and then negates it with the boolean not operator "!".

A: function negate(func) {
  return function(x) {
    return !func(x);
  };
}
var isNotNaN = negate(isNaN);
show(isNotNaN(NaN));

Lets start from the top:
function negate( func )
{
  ...
}

Declares a function negate with a parameter func. The function returns an anonymous function:
function(x)
{
  return !func(x);
}

The anonymous function will execute the function provided in the original function's func parameter, but negate the return vaule.
Then isNotNaN is set as a function that will return true when the parameter is not NaN, and false when the parameter is NaN;
var isNotNaN = negate( isNaN );

Finally NaN is chucked into the function returning the expected result of false
show( isNotNaN( NaN ) );


text:
Q: Primary Constructor is not being compiled in C# 6.0 I am trying to write a simple example of the Primary Constructor new feature in C# 6.0 but I am not able to compile it.
I have changed the Language version to c# 6.0 but it still doesn't work.

public class Person (string fName, string lName)
{
    public string FName { get; private set; } = fName;
    public string LName { get; private set; } = lName;
}

How can I make it compile?

A:
I am trying to write a simple example of the Primary Constructor new feature in C# 6.0 but I am not able to compile it. I have changed the Language version to c# 6.0 but it still doesn't work.

That feature was cut.


text:
Q: Is it possible to use a plugin for a Framework class? I have written the plugin below but I can't seem to get it triggered.
<?php

namespace Vendor\ExtendedQuickSearch\Plugin;

use Magento\Framework\Search\Adapter\Mysql\Query\Builder\Match;

class QuickSearch
{
    public function beforeGetMatchQuery(
        \Magento\Framework\DB\Helper\Mysql\Fulltext $subject,
        $columns, $expression, $mode = self::FULLTEXT_MODE_NATURAL
    )
    {
        var_dump('Plugin1 - beforeGetMatchQuery');die;
    }
}

Any ideas?

A: in etc/area/di.xml update this things, it will work.
 <type name="\Magento\Framework\DB\Helper\Mysql\Fulltext">
    <plugin name="QuickSearch-plugin" type="Vendor\ExtendedQuickSearch\Plugin\QuickSearch" />
</type>


text:
Q: Price formula calculation for Doraemon Story of Season I am recording a list of sell price for items that has quality to aid my gameplay since I wasn't able to find a good price guide.
I noticed that:

*

*Everything have a base price at lowest quality (half star) and it will be a round number that ends with at least one zero.

*Everything that has same base price will have identical price for better quality.
(Ex: both Carp and Honey Bee have base price of 40, and they have same price for other quality)

Name
0.5⭐
1⭐
1.5⭐
2⭐
2.5⭐
3⭐
3.5⭐
4⭐
4.5⭐
5⭐

Carp
40
46
52
59
67
76
86
98
111
126

Honey Bee
40
46
52
59
67
76
86
98
111
126

*As the quality grows, the price of the item would go up exponentially.

Base on this I concluded that there must be a formula to calculate it all given a base price.
Now, the problem is I couldn't figure out the formula for the price even though I think I have a decent amount of data. Since I have Switch Edition and not the Steam one, I can't poke around with game file either.
I was thinking about formula like this:

But it's just not quite right. I still felt like this is just more or less a high school level math problem and I forgot most of my math class.
How do I find the formula given the data?


text:
Q: Python 3 Self replicating file into random directory - then running file I have a fun little script that i would like to make a copy of itself in a random directory - then run that copy of itself.
I know how to run files with (hacky):
os.system('Filename.py')

And i know how to replicate files with shuttle - but i am stuck at the random directory. Maybe if i could somehow get a list of all directories available and then pick one at random from the list - then remove this directory from the list?
Thanks,
Itechmatrix

A: You can get list of all dirs and subdirs, and shuffle it in random as follows:
import os
import random

all_dirs = [x[0] for x in os.walk('/tmp')]
random.shuffle(all_dirs)

for a_dir in all_dirs:
    print(a_dir)
    # do something witch each directory, e.g. copy some file there.

A: You can get a list of directories and then randomly select:
import os
import random
dirs = [d for d in os.listdir('.') if os.path.isdir(d)]
n = random.randrange(len(dirs))
print(dirs[n])

A: If you're on a Mac, there are a fair amount of hidden and restricted directories near the root. You can potentially run into errors with readability and writability. One way to get around that is to iterate through the available directories and sort all the no goes using the os module.
After that you can use the random.choice module to pick a random directory from that list.
import os, random

writing_dir = []
for directory in os.listdir():
   if os.access(directory, W_OK) # W_OK ensures that the path is writable
     writing_dir.append(directory)

path = random.choice(writing_dir)

I'm working on a similar script right now.