text:
Q: Conexão com dois bancos em c# Preciso realizar conexão com dois tipos de banco de dados, sendo eles: Oracle e Postegre.
Preciso ir no Oracle, gerar um spool com algumas consultas e subir esse spool no Postegre.
É possível realizar isso em C#?
Estou tendo muita dificuldade em encontrar conteúdo referente a este tema em fórum etc..
Posso este código para conexão ORACLE:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace aplicacao_fatura_devolvida
{
    class ConsultaBancoOra
    {
        //public Process Sqlpl { get; private set; }
        private string connection = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)" +
            "(HOST=xx.xx.xx.xxx)(PORT=xxxx))) (CONNECT_DATA=(SERVICE_NAME=xx))); User Id=xxxx; Password=xxxxxx";
        //Consulta ORACLE
        [Obsolete]
        public ConsultaBancoOra()
        {
            //String de Conexão
            OracleConnection ora = new OracleConnection(connection);
            //OracleCommand oraComand = new OracleCommand();
            //oraComand = ora.CreateCommand();
            //oraComand.CommandText = " select * from tb_003_ref_fd_dados_carga_base;";
            //oraComand.CommandTimeout = 15;
            //oraComand.CommandType = CommandType.Text;
            MessageBox.Show("Conexão realizada");
        }
        [Obsolete]
        public void AbrirConexaoOra()
        {
            OracleConnection ora = new OracleConnection(connection);
            ora.Open();
        }
        [Obsolete]
        public void FechaConexaoOra()
        {
            OracleConnection ora = new OracleConnection(connection);
            ora.Close();
        }
        public void ExecuteScriptOra(string Script, bool sequencial)
        {
            try
            {
                using (Process process = new Process())
                {
                    process.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
                    process.StartInfo = new ProcessStartInfo("Sqlplus", $@" -d "" host=xx.xx.xx.xxxx port=xxxxdbname=xxxxx user=xxxxpassword=xxxxx"" " + Script);
                    //process.StandardInput.WriteLine();
                    process.StartInfo.UseShellExecute = false;
                    process.Start();
                    if (sequencial)
                    {
                        process.WaitForExit();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }
    }
}


text:
Q: Finding the area of a implicit relation Let's say we have the function: $$x^2+y^2+\sin(4x)+\sin(4y)=4$$
I haven't taken Calculus III, in fact I'm just taking Calculus I. Since I learned how to find the derivative of implicit relations I was wondering if you can find the area of it.
Eventually I went into finding the area of closed shapes, and I found Green's Theorem.
How could you use Green's theorem to determine a contour path, use the line integral, and finally solve for the area of the closed implicit shape, such as $x^2+y^2+\sin(4x)+\sin(4y)=4$.
Is it also effective? Or could their be easier methods.

A: I offer three solutions using (as requested in your own answer) the Python's SciPy package - (1) a simple double integral technique, (2) a polar integral, and (3) a path integral using Green's theorem.  Of these, the second is certainly the best for reasons that we'll explore, the first is the easiest, and I only offer the third since it was specifically requested.  The correct value is approximately 12.711.
A double integral
Let $\chi$ be the characteristic function of the set.  That is,
$$\chi(x,y) = \left\{
\begin{array}{ll}
  1 & \text{if } x^2 + y^2 + \sin(4x)+\sin(4y)<4 \\
  0 & \text{otherwise}.
\end{array}\right.
$$
Then the area in question is
$$\int_{-3}^{3} \int_{-3}^{3} \chi(x,y) \, dx \, dy.$$
The bounds for the integral can be any numbers so that the resulting rectangle contains the region of interest but (from the perspective of a numerical integrator, the smaller the better.
We can implement this in SciPy as follows:
from scipy import sin
from scipy.integrate import dblquad
def f(x,y):
    if x**2 + y**2 + sin(4*x)+sin(4*y)<4:
        return 1
    else:
        return 0
dblquad(f, -3,3, lambda x: -3, lambda x: 3)

#Out: (12.707523995238732, 0.0006145836908579838)

Thus, the area should be (approximately) $12.7075$.  The second value is an error bound, which I wouldn't trust too much, since such bounds make assumptions on the smoothness of the integrand.  In fact, a warning message is issued.  Thus, while conceptually simple and easy to program for any implicitly defined region, this technique yields a result that is not particularly reliable.  Not too surprising, as we have a multi-dimensional integrand that is discontinuous on a somewhat complicated set.
Another way to check results like this is to examine the result in another system.  This can be done with a one-liner in Mathematica:
NIntegrate[Boole[x^2 + y^2 + Sin[4x] + Sin[4y] < 4], {x,-3,3}, {y,-3,3}]
(* Out: 12.6825 *)

The result differs significantly but, again, a warning message is issued and the result should be considered suspect.
A polar integral
Another approach is to use the polar expression for area:
$$\int_{\alpha}^{\beta} \frac{1}{2} f(\theta)^2 \, d\theta,$$
where $\alpha\leq\theta\leq\beta$ and (for a given $\theta$) $0\leq r\leq f(\theta)$.  In our case, $\theta$ runs from $0$ to $2\pi$ and, given a $\theta$, we must determine the distance of the corresponding point on the boundary of our region.

The radius $f(\theta)$ can be computed fairly easily for this region using a numerical equation solver; we are fortunate that the region displays sufficient regularity to allow this.  This scheme can be implemented in SciPy as follows:
from scipy import sin, cos, pi
from scipy.optimize import brentq
from scipy.integrate import quad
def f(r,theta): return (r*cos(theta))**2 + (r*sin(theta))**2 +
  sin(4*r*cos(theta))+sin(4*r*sin(theta)) - 4
def rr(theta): return brentq(lambda r: f(r,theta),1,3)
def integrand(theta): return 0.5*rr(theta)**2
quad(integrand, 0, 2*pi)

#Out: (12.710967450506423, 7.130808983545281e-08)

Note that there is no message issued and the error estimate is much better.  Not surprising, as we have an easily computed, continuous, one-dimensional integrand.  Also, it's easily implemented in Mathematica:
f[theta_?NumericQ] := r /. FindRoot[
  (r*Cos[theta])^2 + (r*Sin[theta])^2 +
    Sin[4 r*Cos[theta]] + Sin[4 r*Sin[theta]] == 4,
  {r, 1, 3}];
NIntegrate[f[theta]^2/2, {theta, 0, 2 Pi}]
(* Out: 12.710967451423258 *)

The difference between the two systems is on the order of $10^{-10}$.  The one disadvantage of this approach is that it is not very broadly applicable as the region needs to be amenable to a polar description.
Green's theorem
Finally, you can use Green's theorem as you propose.  While the integral is one dimensional, the only way to parametrize the boundary is to use interpolation.  Then, you're stuck computing a numerical derivative of the interpolation in the integrand, which leads to it's own problems.
At any rate, the idea behind this approach arises from Green's theorem
$$
\iint_{\Omega} \left(\frac{\partial Q}{\partial x}-\frac{\partial P}{\partial y}\right) \, dA
=
\oint_{\partial\Omega} P \, dx + Q \, dy
$$
with $Q(x,y)=x$ and $P(x,y)=0$ we get
$$\iint_{\Omega} 1 \, dA = \oint_{\partial\Omega} x \, dy.$$
Now, the integral on the left clearly represents the area of $\Omega$ and the integral on the right can be easily computed as
$$\oint_{\partial\Omega} x \, dy = \int_a^b x(t)y'(t)\,dt,$$
if we have a parametrization $(x(t),y(t))$ of the boundary of $\Omega$.  We can get that parametrization using interpolation.
To implement this in SciPy, first we'll generate an image of the region.
import matplotlib.pyplot as plt
import numpy as np

def f(x,y): return x**2 + y**2 + np.sin(4*x) + np.sin(4*y)
delta = 0.01
x = np.arange(-3,3,delta)
y = np.arange(-3,3,delta)
x,y=np.meshgrid(x,y)
z = f(x,y)
contour_pic = plt.contour(x,y,z,[4])

Calling plt.show() should generate the following image.

Now, we need the points in the image for interpolation.
xy = contour_pic.collections[0].get_paths()[0].vertices

The interpolation goes as follows
from scipy.interpolate import interp1d
t = np.linspace(0,1,xy.shape[0])
fx = interp1d(t,xy[:,0], fill_value=xy[0,0], bounds_error=False, kind='cubic')
fy = interp1d(t,xy[:,1], fill_value=xy[0,1], bounds_error=False, kind='cubic')

With these points, we can now compute the integral.
from scipy.misc import derivative
from scipy.integrate import quad

def integrand(t): return fy(t)*derivative(fx,t,0.002)
quad(integrand, 0,1)

# Out: (12.675772468194559, 0.05846541344794076)

The result does not look particularly close to the previous results, we have a poor error bound, and a warning message is issued.  None of this is surprising, as the integrand is much more complicated than the polar version.

A: Being a topic of 8 years ago with already a very detailed answer, I certainly don't have the ambition to write innovative things, it's to be understood as a corollary that could be useful to someone.

Wolfram Mathematica 13.0
Quite simply, by writing:
NIntegrate[Boole[x^2 + y^2 + Sin[4 x] + Sin[4 y] < 4],
           {x, -3, 3}, {y, -3, 3}, Method -> "LocalAdaptive"]

12.7111

that being a result without warnings is probably close to that exact (better to deepen).

Monte Carlo method
The basic idea is to bombard with 10^n balls the square of area $A_q$ which encloses the region of plane D of interest which goes from vertex (-3,-3) to vertex (3,3) and to count the m balls that also fall internally to D. The area of D is therefore estimated by $A_q\,m/10^n$. It goes without saying that a good pseudorandom real number generator is crucial here:
Table[m = 0; Do[{x, y} = RandomReal[{-3, 3}, 2];
      If[x^2 + y^2 + Sin[4 x] + Sin[4 y] < 4, ++m], {10^n}];
      36. m / 10^n, {n, 7}]

{14.4, 14.4, 12.636, 12.6972, 12.776, 12.6944, 12.7077}

or more efficiently:
Table[{x, y} = RandomReal[{-3, 3}, {2, 10^n}];
      36. Total@Boole@Thread[x^2 + y^2 + Sin[4 x] + Sin[4 y] < 4] / 10^n, {n, 8}]

{7.2, 12.24, 13.536, 12.708, 12.7224, 12.7193, 12.7109, 12.7112}

The calculated area is the better the larger it's n.

Discrete Fourier Transform + Gauss-Green theorem
First, I tabulate the coordinates of some points of the boundary proceeding counterclockwise:
f[x_, y_] := x^2 + y^2 + Sin[4 x] + Sin[4 y]

pts = ContourPlot[f[x, y] == 4, {x, -3, 3}, {y, -3, 3},
                  PlotPoints -> 100][[1, 1, 1]];

Through Discrete Fourier Transform, I determine a trigonometric fit of least squares to the data:
TrigFit[v_, m_, {x_, x0_, x1_}] := Module[{fc, fs, i, imax, j, n, t},
  n = Length[v]; imax = Min[m, Floor[(n - 1) / 2]]; t = 2 π (x - x0)/(x1 - x0);
  fc = Table[Sum[v[[j + 1]] Cos[2 π i j / n] / n, {j, 0, n - 1}], {i, 0, imax}];
  fs = Table[Sum[v[[j + 1]] Sin[2 π i j / n] / n, {j, 0, n - 1}], {i, 0, imax}];
  fc[[1]] + 2 Sum[fc[[i + 1]] Cos[i t] + fs[[i + 1]] Sin[i t], {i, 1, imax}]]

{x[t_], y[t_]} = TrigFit[pts, 100, {t, 0, 2 π}];

Finally, I calculate the area enclosed by this parametric curve using the Gauss-Green theorem:
NIntegrate[x[t] y'[t], {t, 0, 2 π}]

12.7106

If you want to check, it's also possible to superimpose the implicit curve on the parametric one:
Show[ParametricPlot[{x[t], y[t]}, {t, 0, 2 π}, PlotStyle -> Directive[Thick, Red]],
     ContourPlot[f[x, y] == 4, {x, -3, 3}, {y, -3, 3}, PlotPoints -> 100]]

where it's evident that they overlap perfectly, so the calculated area is very close to the exact one!

About the case mentioned in the comments x^2 + y^2 + Sin[4 x y] < 4 it's possible to face it with the same formulations just written and the area obtained is equal to 12.6323.

redpajama_set_name: RedPajamaStackExchange


text: Q: Перевод слов для обращения к api Всем вечер добрый, делаю приложение с погодой, подрубился к api openweathermap, но там города на английской, вопрос в том, как при вводе название города на русском, перевести его на английский, и отдать его api. Идей нет, кроме загрузки коллекции из названий городов на русском и на английском.


text:
Q: Does this negative unit testing make sense I have tests like that. Negative unit testing.
Does this test make sense? Is it not better to test only the expected exceptional scenarios?
[Test]
public void Get_Root_Units_By_Non_Existing_TemplateId()
{
// ARRANGE
ITemplateUnitDataProvider provider = new TemplateUnitDataProvider(_connectionString);
int templateId = -1;

// ACT
var units = provider.GetRootUnits(templateId);

// ASSERT
Assert.IsNotNull(units);
Assert.Count(0, units);
}

A: For me this test makes sense. You are checking that the SUT (Subject Under Test) returns an empty array if it hasn't found any records matching the input parameter.

A: In my opinion, unit tests are used to check your method's correctness. Handling incorrect input correctly is also something you want to test for.
Unit tests are meant to give you a sense of security about your code, so handling invalid input is certainly something I would test.

A: One good reason to wite fail test is any unit test is better than no unit test
writing fail test lets you know your system well what it should fail on else you have some other scenario's that you are not aware of


text:
Q: How to pass value outside the function in javascript? I want to use a variable value that is created inside a function to outside of that function. but it is showing undefined. actually I am getting ip address using api and want to use that ip address outside the function. Inside function,its working fine but outside it alerts undefined. Here is my code
<script type="text/javascript">
var userip;
    window.onload = function () {
        var script = document.createElement("script");

        script.type = "text/javascript";

        script.src = "https://jsonip.com/?callback=DisplayIP";
        document.getElementsByTagName("head")[0].appendChild(script);
    };
    function DisplayIP(response) {
        document.getElementById("ipaddress").innerHTML = "Your IP Address is " + response.ip;
        userip  = response.ip;
        alert(userip);  // alerts  ip address
    }
alert(userip); // alerts undefined. it should alert ip address

</script>

A: In your code:
var userip  = response.ip;

Get rid of var making it:
userip  = response.ip;

Beware, this makes it to the global scope. And it will be subjected to be accessed and modified by all. So, make sure you give a unique name.

A: Your code are executed in the same order it was written. Your script begin to request "https://jsonip.com/?callback=DisplayIP" at on load page, but your last "alert" are executed following your code order and at this time
"userip" has not a value. Its value is filled just when your request are finished. For this reason "alert" inside DisplayIP works and the last one not.
<script type="text/javascript">
    var userip;
    window.onload = function () {
        var script = document.createElement("script");

        script.type = "text/javascript";

        script.src = "https://jsonip.com/?callback=DisplayIP";
        document.getElementsByTagName("head")[0].appendChild(script);
    };

    function DisplayIP(response) {
        document.getElementById("ipaddress").innerHTML = "Your IP Address is " + response.ip;
        userip  = response.ip;
        alert(userip);
    }

    alert(userip);

    // Try this to understanding what I mean
    setInterval(_ => alert(userip), 1000);
</script>


text:
Q: WARNING:tensorflow with constraint is deprecated and will be removed in a future version I am following Tensorflow's tutorial on building a simple neural network, and after importing the necessary libraries (tensorflow, keras, numpy & matplotlib) and datasets (fashion_mnist) I ran this code as per the tutorial:
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

after running this code i received this warning message:

WARNING:tensorflow:From
  /Applications/anaconda3/envs/tensorfloe/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630:
  calling BaseResourceVariable.init (from
  tensorflow.python.ops.resource_variable_ops) with constraint is
  deprecated and will be removed in a future version. Instructions for
  updating: If using Keras pass *_constraint arguments to layers.

How do i fix this?
Your help is highly appreciated.

A: I had a similar warning when I was using tf.compat.v1.get_variable(...) and what I needed to do was to set the use_resource argument to False. Might help someone looking for a similar warning but doesn't look like the case with you though.

A: This is internal TensorFlow message, you can safely ignore it. It will be gone in future versions of TensorFlow, no actions from your side is needed.

A: Well it is a warning that some features are deprecated and will be removed in a future version. It is just for your information that what changes could occur.
Although, you can remove these warnings by
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

A: If you only want to filter the tensorflow logs, you can disable the logging with the following lines (tensorflow 2.2):
import tensorflow as tf
tf.get_logger().setLevel('ERROR')

A: if you want to remove it , you can do run twice for the line of code.


text:
Q: execve of /usr/bin/xfce4-terminal gives "Session manager variable not defined" I'm trying to have a process fork and run execve in the child process so that it will open a new terminal window and execute a custom command there.
The program I want to execute is gestore
These are the arguments I pass to execve:
char * argv_exec[5];
argv_exec[0]="/usr/bin/xfce4-terminal";
argv_exec[1]="--geometry";
argv_exec[2]="480x320";
argv_exec[3]="-x";
argv_exec[4]="./gestore";    // the program I want to execute in new window
argv_exec[5]=NULL;

char sess_m[80];
strcat(sess_m,"SESSION_MANAGER=");
strcat(sess_m,getenv("SESSION_MANAGER"));

char * envp[3];
envp[0]="DISPLAY=:0.0";
envp[1]=sess_m;
envp[2]=NULL;

and here I call execve:
if(pid_tv==0)
    if(execve(argv_exec[0],argv_exec,&envp)==-1) {...}

but I keep getting Session manager variable not defined.
Anyone has a suggestion on why this does not work or how could I do it better?

A: Some re-writing, both to show more idiomatic use of a process's environment (see environ(7)) and to demonstrate some ways to avoid hard-wiring array sizes: always a source of fence-post errors in C.
See code comments for some of the explanations/justifications.
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern char **environ;  /* see environ(7) */

int
main(void)
{
    char *argv_exec[] = {
        "/usr/bin/xfce4-terminal",
        "--geometry",
        "480x320",
        "-x",
        "./gestore",
        NULL };

    /*
     * Structure to drive search for a few variables present in
     * current environment, and construct a new, minimal, environment
     * containing just those values. Use the direct value from the
     * current process's environ variable to set "value" (the string
     * of the form "NAME=VALUE"). Just add more entries to nv to handle
     * more variables; the code below will adjust sizes.
     *
     * Any value missing in the environment will be an error.
     */
    struct {
        char *name;
        char *value;
    } nv[] = {
        { "DISPLAY", NULL },
        { "SESSION_MANAGER", NULL }
    };

    /* size new_envp to have one more entry than nv */
    char *new_envp[sizeof(nv) / sizeof(nv[0]) + 1];

    char **e;
    int i, error_flag;
    pid_t pid;

    /*
     * For each variable needed...
     */
    for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++) {
        /* ...search in current environment */
        for (e = environ; *e; e++) {
            size_t slen = strlen(nv[i].name);
            if (strncmp(*e, nv[i].name, slen) == 0 && (*e)[slen] == '=') {
                nv[i].value = *e;
                break;
            }
        }
    }

    /*
     * Check that we found all values, setting up new_envp as we go.
     */
    error_flag = 0;
    for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++) {
        if (nv[i].value == NULL) {
            (void) fprintf(stderr, "%s not set in environment\n",
                        nv[i].name);
            error_flag = 1;
        } else {
            new_envp[i] = nv[i].value;
        }
    }
    if (error_flag) {
        return 1;
    }
    new_envp[i] = NULL;

    /* very minimal fork/exec processing */

    pid = fork();

    if (pid == -1) {
        perror("fork");
        return 1;
    }
    if (pid == 0) {
        (void) execve(argv_exec[0], argv_exec, new_envp);
        /*
         * If execve succeeded, the invoked program has
         * replaced this process, and will either run or
         * (presumably) report its own errors. If we're
         * still in control, the execve failed, so print
         * an error and exit.
         */
        perror(argv_exec[0]);
        return 1;
    } else {
        if (wait(0) != pid) {
            perror("wait");
            return 1;
        }
    }

    return 0;
}


text:
Q: How to set multiple argument with postgress helm 3.0 I want to set slave.extraVolumes as below.
helm install my-db --set replication.enabled=true,slave.extraVolumes={"db-disk-1","db-disk-2"} bitnami/postgresql -n development

But it says a error
Error: expected at most two arguments, unexpected arguments: bitnami/postgresql

Already tested ways:
helm install my-db --set replication.enabled=true,slave.extraVolumes={db-disk-1,db-disk-2} bitnami/postgresql -n development
Error: expected at most two arguments, unexpected arguments: bitnami/postgresql

helm install my-db --set replication.enabled=true,slave.extraVolumes="db-disk-1\,db-disk-2" bitnami/postgresql -n development
Error: YAML parse error on postgresql/templates/statefulset-slaves.yaml: error converting YAML to JSON: yaml: line 115: could not find expected ':'

A: There are (at least) three things going on:

*

*the slave.extraVolumes is a list of Volume structures, so just providing two names won't get it done

*you are using characters that are meaningful to the shell without quoting them

*but in the end it doesn't matter because you cannot represent complex structures using only --set syntax, you'll need --values with either a file or a process substitution
helm install my-db \
   --set replication.enabled=true \
   --values <(echo '{
      "slave": {
        "extraVolumes": [
          {
            "name": "db-disk-1",
            "emptyDir": {}
          },
          {
            "name": "db-disk-2",
            "emptyDir": {}
          }
        ]
      }
   }') \
   bitnami/postgresql -n development

A: For others who come from Google with the error message and want to solve that, rather than the obscure postgresql-specific answer in the accepted answer, the problem is almost certainly mdaniel's point 2 ("you are using characters that are meaningful to the shell without quoting them"), at least for modern bash.
This answer explains what is going on - Stop shell wildcard character expansion? - and how to fix it. Here you need to escape just the curly brackets, so something like:
helm install my-db --set replication.enabled=true,slave.extraVolumes='{"db-disk-1","db-disk-2"}' bitnami/postgresql -n development

or
helm install my-db --set replication.enabled=true,slave.extraVolumes=\{"db-disk-1","db-disk-2"\} bitnami/postgresql -n development

Is what you need. The helm help is annoyingly silent on this.


text:
Q: Linux: set command for local variables I am trying to understand local/environment variables and export/set commands.
$ set FILEM="razrax"
$ echo $FILEM

$ FILEN="test"
$ echo $FILEN
test

Please explain why echo $FILEM returns empty string

A: You're confusing bash with csh.
In bash like in any Bourne-like shell, set is the command to set options (shell configuration settings like -f, -C, -o noclobber...) and positional parameters ($1, $2...).
set FILEM="razrax"

Sets $1 to FILEM=razrax.
$ set FILEM="razrax"
$ echo "$1"
FILEM=razrax

The syntax for variable assignment in Bourne-like shells is:
VAR=value

(no space allowed on either side of =).
ksh and some other Bourne-like shells (mksh, pdksh, zsh) can also assign array variables with set though:
set -A array value1 value2

zsh, bash, yash and newer versions of ksh use this syntax instead:
array=(value1 value2)

In contrast, in csh or tcsh, the syntax is:
set VAR = value
set array = (value1 value2)

(spaces around = optional).
In rc/es shells:
VAR = value
array = (value1 value2)

(spaces around = optional).


text:
Q: Python, Pygame Mouse events How would I assign the variables x, y to the x and y position, respectivly, of a the mouse pointer when it is pressed down (clicked).
Heres what I have thus far:
from pygame import*
init()
SIZE = (width, height)
screen = display.set_mode(SIZE)
position = 0
Running = True
while Running:
    for evnt in event.get():
         if evnt.type == QUIT:
             Running = False
         elif evnt.type == MOUSEBUTTONDOWN:
             position = evnt.pos

Currently, position is in the form (x position, y position).
How would I access the individual elements?
Thanks in advance.

A: position is a tuple so you can
position = evnt.pos
x = position[0]
y = position[1]

or
x, y = position

or even
x, y = evnt.pos

A: I have not used pygame in a while nor do i still have it so i can't test this code but I'm pretty sure its correct. first you test if the mouses left button is clicked
The get_pressed function returns three values for each button on a mouse i may be wrong thinking the first value returned is the value for mouse button one.
If the mouse is clicked, we proceed to get the mouses coords and store them.
if pygame.mouse.get_pressed()[0]
    cord = pygame.mouse.get_pressed()

Also, from what i understand pygame does not use a z value as the library is only a 2D library so this gives you a X, Y value.


text:
Q: Play WAV without delay? This code plays the WAV three times with a delay between each time.
How can I eliminate this delay?
import winsound
for x in range(0, 3):
    winsound.PlaySound(FileName + '.wav', winsound.SND_FILENAME)

A: The winsound module can't do this. You might be able to hack your way to a solution by setting the loop flag, sleeping for three times the duration, then stopping playback by calling winsound.PlaySound with no arguments, but you would have to make faulty assumptions surrounding the timing of things outside of your control.
How about pydub?
from pydub import AudioSegment
from pydub.playback import play
segment = AudioSegment.from_wav(FileName + '.wav')
play(segment * 3)


text:
Q: Angularjs RESTul Resource Request I am trying to make the request
....port/trimService/fragments/?fragment_name=:fragmentName

However if I try to make the "?fragment_name" a parameter, it breaks. As I am going to have more requests, my action with change so I cannot leave it in the url portion  of the resource.
angular.module(foo).factory('FragmentService', ['$resource',
function ($resource)
{
    var FragmentService = $resource('.../fragments/:action:fragmentName',
    {},
    {
        'getFragments':
        {
            method: 'GET',
            isArray: true,
            params:
            {
                fragmentName: "@fragmentName",
                action: "?fragment_name="
            }
        }

    });
    return FragmentService;
}
]);

As of right now, I have no idea what my URL is actually outputting.
EDIT: I changed my resource as /u/akonsu had mentioned below. I also added my controller as it is still not working correctly.
angular.module(foo).factory('FragmentService', ['$resource',
function ($resource)
{
    var FragmentService = $resource('.../fragments/',
    {},
    {
        'getFragments':
        {
            method: 'GET',
            isArray: true,
            params:
            {
                fragmentName: "@fragmentName",
            }
        }

    });
    return FragmentService;
}
]);

angular.module(foo).controller('FragmentController', ['$scope', 'FragmentService',
function ($scope, FragmentService)
{
    $scope.fragmentQuery = {
        fragmentName: 'a',
    };

    $scope.fragmentQuery.execute = function ()
    {
        if ($scope.fragmentQuery.fragmentName == '')
        {
            $scope.fragments = {};
        }
        else
        {
            $scope.fragments = FragmentService.getFragments(
            {
                fragmentName: $scope.fragmentQuery.fragmentName,
            });
        }
    };
    $scope.fragmentQuery.execute();

}

]);

A: Try omitting the query string altogether in the resource URL and just supply your fragmentName as a parameter to the action call. It should add it to the query string if it is not in the list of  URL parameters.
$resource(".../port/trimService/fragments/").get({fragmentName: 'blah'})


text:
Q: VBA to write data in cells very slow I have written a very straightforward script which writes data into excel cells.
Basically, this is a loop over an array and it writes data into specific cells or formulas.
The problem is that this part of the script is extremly slow.
Any ideas on how to improve thath?
Thanks.
    For j = 0 To i - 1
    'Insère nouvelle ligne
    Rows(startRow & ":" & startRow).Select
    Selection.Copy
    Rows(startRow + 1 & ":" & startRow + 1).Select
    Selection.Insert Shift:=xlDown

    'Insère données
    If roomType(j) <> "" Then
        Feuil3.Cells(startRow, 1).Value = roomName(j)
        Feuil3.Cells(startRow, 2).Value = roomSurface(j)
        Feuil3.Cells(startRow, 7).Value = roomPeople(j)
        Feuil3.Cells(startRow, 12).Value = roomPeople(j)
        Feuil3.Cells(startRow, 5).Value = dict.Item(roomType(j))
        Feuil3.Cells(startRow, 3).Value = roomHeight(j)

        Feuil3.Range("F" & startRow).Formula = "=IFERROR(IF($E" & startRow & "=Data!$A$55,,ROUNDUP($B" & startRow & "/VLOOKUP($E" & startRow & ",Data!$A$3:$E$55,4,FALSE),0)),)"
        Feuil3.Range("H" & startRow).Formula = "=$C$25"
        Feuil3.Range("I" & startRow).Formula = "=IF($E" & startRow & "=Data!$A$55,$B" & startRow & "*$E$55,(MAX(F" & startRow & ",G" & startRow & ")*H" & startRow & "))"
        Feuil3.Range("N" & startRow).Formula = "=IFERROR(VLOOKUP($K" & startRow & ",$M$22:$O$26,3,FALSE),)"
        Feuil3.Range("O" & startRow).Formula = "=IFERROR(IF(ISBLANK(M" & startRow & ")=TRUE,L" & startRow & "*N" & startRow & ",L" & startRow & "*M" & startRow & "*N" & startRow & "),)"
        Feuil3.Range("Q" & startRow).Formula = "=MAX(I" & startRow & ",O" & startRow & ")"
        Feuil3.Range("T" & startRow).Formula = "=IFERROR(MAX(R" & startRow & ",S" & startRow & ")/(B" & startRow & "*C" & startRow & "),)"
    End If

    startRow = startRow + 1
Next j
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

A: It is quicker to assign an array to a range of cells than to assign to individual cells in a loop. You could try sometihing like: Worksheets("MySheet").Range("A1:D100").Value = myArray. It is because communication between VBA and Excel takes some time. A little bit more on that here: VBA Excel large data manipulation taking forever
Also using Cells instead of Range is aboout 2.6 times faster. Here is a question on that: Range() VS Cells() - run times

A: I cut the script in pieces.
This part takes most of the time
    For j = 0 To i - 2
    Feuil3.Cells(startRow, 5).Value = dict.Item(roomType(j))
    Feuil3.Cells(startRow, 6).Formula = "=IFERROR(IF($E" & startRow & "=Data!$A$55,,ROUNDUP($B" & startRow & "/VLOOKUP($E" & startRow & ",Data!$A$3:$E$55,4,FALSE),0)),)"
    Feuil3.Cells(startRow, 8).Formula = "=$C$25"
    Feuil3.Cells(startRow, 9).Formula = "=IF($E" & startRow & "=Data!$A$55,$B" & startRow & "*$E$55,(MAX(F" & startRow & ",G" & startRow & ")*H" & startRow & "))"
    Feuil3.Cells(startRow, 14).Formula = "=IFERROR(VLOOKUP($K" & startRow & ",$M$22:$O$26,3,FALSE),)"
    Feuil3.Cells(startRow, 15).Formula = "=IFERROR(IF(ISBLANK(M" & startRow & ")=TRUE,L" & startRow & "*N" & startRow & ",L" & startRow & "*M" & startRow & "*N" & startRow & "),)"
    Feuil3.Cells(startRow, 17).Formula = "=MAX(I" & startRow & ",O" & startRow & ")"
    Feuil3.Cells(startRow, 20).Formula = "=IFERROR(MAX(R" & startRow & ",S" & startRow & ")/(B" & startRow & "*C" & startRow & "),)"

    startRow = startRow + 1
Next j


text:
Q: CSS Font Awesome v6 Icon won't align within pseudo element correctly I'm using Font Awesome v6. I've gotten the icons to appear as they should but I can't get them to align within the ::before element.
Here's an image showing how the icons are appearing:

The icons, as you can see, are appearing behind the before element (the circle). The box image indicating a missing image is where the icon should appear (the icon is clearly displaying on the screen so this is not a missing icon issue).
Here's my code (JSFiddle)
I've already used the Font Awesome pseudo elements feature on my site to customise the bullet points for a standard ul list and it worked fine. The only difference here is that I'm using the nth-of-type() selector. It works absolutely fine if I put anything but a Font Awesome unicode in the content.
I've looped through all of the positions and display options on 'Inspect Element' and can't get it to position correctly. The only thing that works is if I manipulate the svg element that is added by the Font Awesome library, which is a bit inconvenient.
I've tried to search Google for solutions but can't find anything except posts which are asking for help to get the images to display in the first place, which is obviously not my issue here.
Any help is appreciated, thanks.


text:
Q: Commit or handle rollback in stored procedure after insertions are done? Optimal way to handle an error in stored procedure that only makes inserts?
I have a procedure like this:
PROCEDURE INSERT_TO_TABLES (VAL1 IN NUMBER, VAL2 IN NUMBER, RESULT OUT NUMBER)
IS
BEGIN
    INSERT INTO TABLE_1 (A_COLUMN) VALUES (VAL1);
    INSERT INTO TABLE_2 (B_COLUMN) VALUES (VAL2);
    COMMIT;
END;

How could I make this stored procedure optimal enough to handle a rollback and raise an exception to catch from the application (C# try/catch) if only 1 of those inserts throws an error? Return out value true if everything is ok or false if an error happened?

A: SQLERRM and SQLCODE functions may be used :
CREATE OR REPLACE PROCEDURE INSERT_TO_TABLES (VAL1 IN NUMBER, VAL2 IN NUMBER, RESULT OUT
NUMBER, RESULT_ERR OUT VARCHAR2 )
IS
 v_err_code number         := SQLCODE;
 v_err_txt  varchar2(4000) := SQLERRM;
Begin
  Begin
    INSERT INTO TABLE_1 (A_COLUMN) VALUES (VAL1);
    INSERT INTO TABLE_2 (B_COLUMN) VALUES (VAL2);
   Exception When Others then
             RESULT_ERR := v_err_code||' '||v_err_txt;
  End;

  If ( nvl(v_err_code,0)<0 ) Then
    ROLLBACK;
  Else
    RESULT_ERR :='Committed with success...';
    COMMIT;
  End If;
End;


text:
Q: Extracting data from a JSON database (Python 3) I want to write a program that loads data from a JSON database into a Python list of dictionary and adds all of the number of times the mean temperature was above versus below freezing. However, I am struggling to extract information from the database successfully/ I am concerned my algorithim is off. My plan:
1) define a function that loads data from the json file.
2) define a function that extracts information from the file
3) use that extracted information to tally the number of times the temp was above or below freezing
import json

def load_weather_data(): #function 1: Loads data
    with open("NYC4-syr-weather-dec-2015.json", encoding = 'utf8') as w: #w for weather
        data = w.read()
        weather = json.loads(data)
        print(type(weather))
        return weather

def extract_temp(weather): #function 2: Extracts information on weather
    info = {}
    info['Mean TemperatureF'] = weather['Mean TemperatureF']#i keep getting a type error here
    return info

print("Above and blelow freezing")
weather = load_weather_data()
info = extract_temp(weather)
above_freezing = 0
below_freezing = 0
for temperature in weather: # summing the number of times the weather was above versus below freezing
    if info['Mean Temperature'] >32:
        above_freezing=above_freezing+1
    elif info['mean temperature']<32:
        below_freezing = below_freezing +1

print(above_freezing)
print(below_freezing)

If you have any ideas, please let me know! Thank you.

A: You are trying to extract temperature from the weather list one time before starting the loop when really you should be doing it for each temperature object in the loop. You haven't posted sample data, but I think that weather is a list and you are trying to use it as a dict. Below is a fix with a couple of other changes for tidiness.
import json

# fixed: call with filename so that the function works on other files
def load_weather_data(filename): #function 1: Loads data
    with open(filename, encoding = 'utf8') as w: #w for weather
        # fixed: fewer steps
        return json.load(w)

# fixed: not needed, doesn't simply anything
#def extract_temp(weather): #function 2: Extracts information on weather
#    info = {}
#    info['Mean TemperatureF'] = weather['Mean TemperatureF']#i keep getting a type error here
#    return info

print("Above and blelow freezing")

weather = load_weather_data("NYC4-syr-weather-dec-2015.json")
above_freezing = 0
below_freezing = 0

for temperature in weather: # summing the number of times the weather was above versus below freezing
    if info['Mean Temperature'] > 32:
        above_freezing += 1
    # fixed: capitalized above... so assuming it should be here too
    elif info['Mean Temperature'] < 32:
        below_freezing += 1

print(above_freezing)
print(below_freezing)


text:
Q: Query return empty result but data exist I'm using Slim with PDO with MySql for return a specific list of matches available in my database. My query is this:
SELECT m.*,
       t.name AS home_team_name,
       t2.name AS away_team_name
FROM `match` m
LEFT JOIN team t ON m.home_team_id = t.id
LEFT JOIN team t2 ON m.away_team_id = t2.id
WHERE (home_team_id = 117 OR away_team_id = 117) AND round_id = 488

if I execute this query I'll get a list of matches:

but inside the API developed with Slim I get an empty array. This is the method structure:
$app->get('/match/get_matches_by_team/{round_id}/{team_id}/{type}', function (Request $request, Response $response, array $args)
{
  $query = "SELECT m.*,
  t.name AS home_team_name,
  t2.name AS away_team_name
  FROM `match` m
  LEFT JOIN team t ON m.home_team_id = t.id
  LEFT JOIN team t2 ON m.away_team_id = t2.id
  WHERE ";

  switch($args["type"])
  {
    case "home":
          $query .= "home_team_id = :team_id AND ";
    break;
    case "away":
        $query .= "away_team_id = :team_id AND ";
    break;
    default:
        $query .= "(home_team_id = :team_id OR away_team_id = :team_id) AND ";
    break;
  }

  $query .= "round_id = :round_id";

  $sql = $this->db->prepare($query);
  $sql->bindParam("team_id", $args["team_id"]);
  $sql->bindParam("round_id", $args["round_id"]);
  $sql->execute();

  $result = $sql->fetchAll();
  return $response->withJson($result);
});

what I did wrong?
Thanks in advance for any help.
UPDATE
If I do echo $query; return; I'll get:
SELECT m.*,
t.name AS home_team_name,
  t2.name AS away_team_name
  FROM `match` m
  LEFT JOIN team t ON m.home_team_id = t.id
  LEFT JOIN team t2 ON m.away_team_id = t2.id
  WHERE away_team_id = :team_id AND round_id = :round_id

supposing to pass away, if instead I pass all I'll get:
SELECT m.*,
t.name AS home_team_name,
  t2.name AS away_team_name
  FROM `match` m
  LEFT JOIN team t ON m.home_team_id = t.id
  LEFT JOIN team t2 ON m.away_team_id = t2.id
  WHERE (home_team_id = :team_id OR away_team_id = :team_id) AND round_id = :round_id

UPDATE 2
Method updated with proposed hints
$app->get('/match/get_matches_by_team
/{round_id}/{team_id}/{type}', function (Request $request, Response $response, array $args)
{
  $query = "SELECT m.*,
  t.name AS home_team_name,
  t2.name AS away_team_name
  FROM `match` m
  LEFT JOIN team t ON m.home_team_id = t.id
  LEFT JOIN team t2 ON m.away_team_id = t2.id
  WHERE ";

switch($args["type"])
   {
    case "home":
          $query .= "home_team_id = :home_team_id
    AND ";
        break;
        case "away":
            $query .= "away_team_id = :away_team_id AND ";
        break;
        default:
            $query .= "(home_team_id = :home_team_id OR away_team_id = :away_team_id) AND ";
        break;
      }

      $query .= "round_id = :round_id";

      $sql = $this->db->prepare($query);
      $sql->bindParam("home_team_id", $args["team_id"]);
      $sql->bindParam("away_team_id", $args["team_id"]);
      $sql->bindParam("round_id", $args["round_id"]);
      $sql->execute();

      $result = $sql->fetchAll();
      return $response->withJson($result);
    });

A: yours:
 $sql->bindParam("team_id", $args["team_id"]);
 $sql->bindParam("round_id", $args["round_id"]);

try this, the params might be needed to be formatted differently
$sql->bindParam(":team_id", $args["team_id"], PDO::PARAM_INT);
$sql->bindParam(":round_id", $args["round_id"], PDO::PARAM_INT);

or
$sql->bindParam(":team_id", $args["team_id"]);
$sql->bindParam(":round_id", $args["round_id"]);

A: When the default switch is selected, you are trying to bind a value with the same parameter marker (in your case :team_id) twice. In order for this to work you have to turn on emulation mode in PDO.
http://www.php.net/manual/en/pdo.prepare.php

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.


text:
Q: geolocating an IP address I'm looking to geolocate my  server requests by continent.
Basically, after doing some initial research, it seems that there are 3 approaches: 1) using the geolocation provided by browsers (but I think noone seriously click "Yes" when the browser is asking permission to use geolocation); 2) getting a list of IP addresses, putting that list in a database on your server and then every time a request comes in, read from this DB; I'd hate to have have to hit the DB at every request. 3) make an HTTP call to an external server to get the location; that could even be slower than 2).
Basically, I don't really care to know exactly where the users are, I just need to know which continent they're on: North Armerica, Europe...
Is there a way to do this that doesn't require any user interaction and doesn't require reading a DB on every request? When I go to www.intel.com I get automatically rerouted to the French site; how do they do that?
Thanks for your suggestions.

A: There are some free and some commercial database that can tell you from the ip, where is coming from.
The free database from maxmind [*]: http://dev.maxmind.com/geoip/geolite
and two commercial:
http://www.ip2location.com
http://www.maxmind.com
In this site you can also find asp.net examples on how you can use that data, but also they have other free services that you can use and see where the use is come from.
Get api samples together with the database from: http://www.maxmind.com/download/geoip/
If only the country is what you need for then this database file
http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip
contains only the country, and is small compared with the rest.
How this works in few words: The database is in format of:
"1.20.0.0","1.20.255.255","18087936","18153471","TH","Thailand"
"1.21.0.0","1.21.255.255","18153472","18219007","JP","Japan"
"1.22.0.0","1.23.255.255","18219008","18350079","IN","India"
"1.24.0.0","1.31.255.255","18350080","18874367","CN","China"

the long numbers are the translation of the ip. So you read the IP of your user and then with a function you convert it to long and then you search the database, where is this long number fits.
public long addrToNum(IPAddress Address)
{
    byte[] b = BitConverter.GetBytes(Address.Address);

    if (b.Length == 8)
        return (long)(((long)16777216 * b[0]) + ((long)(65536 * b[1])) + ((long)(256 * b[2])) + b[3]);
    else
        return 0;
}

So if you add them in database then you index the database on this long numbers and look where the ip is in as:
Select TOP 1 * from GeoIPCountryWhois WITH (NOLOCK) Where @myIpToLong BETWEEN begin_num AND end_num

Its good to cache the result on a session variable and not search again and again on every page request.
[*] A big thanks to maxmind that still release the free database together with the commercial.

A: I've used this to geolocate IP addresses before when they requested access to my firewall. Not sure if this is what you're looking for, but it may help.
http://www.geobytes.com/iplocator.htm

A: It seems that you'd prefer second variant, but you don't need to hit the DB on every request - just cache the result in cookie, for example.
And a little bit of insanity - just to make you think about cost of extra DB request: you can convert some geo-DB (look for Aristos' answer) for your needs. Every IP can be converted to Int64 and you can make continent ranges, while converting DB to your format. For example, 0-10000 would be North America, 10000-20000 - Europe, 20000-30000 - North America again and so on, and the only task after such converting is to spot the IP in these ranges.
But you'll have to make a huge work to perform such converting and don't forget that it would be really big butthurt headache to renew it: IP-base isn't constant.
So, DB request + caching, probably, is the best option.


text:
Q: Decode MIME Message and display on ASP.Net I have multipart mail message MIME stored in SQL database. I want to retrieve and display it on the ASP page. I tried decoding it manually but it was not so accurate. There are many types of encoding base64, Iso, printedQuotable etc.
Is there easy way of decoding MIME messages in C#?

A: Try out this
http://www.codeproject.com/Questions/163362/How-To-decode-mime-format-in-asp-net
Let me know if you want more..


text:
Q: How to run concurrent AP Scheduler jobs? I'm attempting to run multiple AP Scheduler jobs in my program (both interval and cron), but when I add multiple interval jobs with different intervals they all execute at the shortest interval. For example, if I add one job with a frequency of 30 seconds and one with 15 seconds, both will execute every 15 seconds.
My code is below. How do I properly run these two jobs on separate intervals?
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ProcessPoolExecutor

executors = {
             'default': {'type': 'threadpool', 'max_workers': 20},
             'processpool': ProcessPoolExecutor(max_workers=5)
            }
job_defaults = {
                'coalesce': False,
                'max_instances': 3
               }
sched = BackgroundScheduler(executors=executors, job_defaults=job_defaults, timezone="EST")

sched.start()
sched.add_job(lambda: module.handle(self.profile, mic), 'interval', id=module.__name__, seconds=15)
sched.add_job(lambda: module2.handle(self.profile, mic), 'interval', id=module2.__name__, seconds=30)
atexit.register(lambda: sched.shutdown(wait=False))

A: You add 2 jobs
sched.add_job(lambda: module.handle(self.profile, mic), 'interval', id=module.__name__, seconds=15)
sched.add_job(lambda: module2.handle(self.profile, mic), 'interval', id=module.__name__, seconds=30)

with dublicate ID's of id=module.__name__. Do you need to specify ID's by yourself? Apscheduler can do it for you.

A: This turned out to be an issue with the lambda that I was using. I removed the lambda by adding the args parameter like below.
sched.add_job(module.handle, 'interval', args=[self.profile, mic], id=module.__name__, seconds=15)
sched.add_job(module2.handle, 'interval', args=[self.profile, mic], id=module.__name__, seconds=30)


text:
Q: How to open a linux directory from browser using php? i am new to php, and i would like to know how to open a directory using php.
i've tried the following codes, but nothing happened
 exec('nautilus /home/');
 exec('sudo nautilus /home/');
 $command='nautilus /home/';
 system($command);

i am using Centos 6.4

A: Try with opendir() php function.

A: Try pcmanfm /home it will open a Directory in Linux. or Explorer in Windows


text:
Q: How to add Custom Titlebar with Button on top of Tabs in Android I have a Tabhost in Android. I now want to know how can i put Custom Titlebar on top of it with button on right. Below is my code :
++++++++++++++++++++++++++
+                +++++++ +
+                +++++++ +
++++++++++++++++++++++++++
+           +            +
+           +            +
++++++++++++++++++++++++++

support.xml
    <?xml version="1.0" encoding="utf-8"?>
    <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:padding="5dp" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="5dp" />
        </LinearLayout>

    </TabHost>

Support.java
public class Support extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.support);
        Bundle bundle = getIntent().getExtras();

        TabHost tabHost = getTabHost();
        TabHost.TabSpec spec;
        Intent intent;

        intent = new Intent().setClass(this, TestListView.class);
        spec = tabHost  .newTabSpec("some_things")
                        .setIndicator("Info")
                        .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, TestListView.class);
        spec = tabHost  .newTabSpec("top_things")
                        .setIndicator("Log")
                        .setContent(intent);
        tabHost.addTab(spec);

        tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 85;
        tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 85;
    }
}

A: Pass a drawable to set indicator
.setIndicator("Log",getResources().getDrawable(R.drawable.image_log));

you may also pass a seletor id to getDrawable().
here is a good Tutorial


text:
Q: How to pass value of radio button which is clicked to Spring MVC controller? I am using Spring MVC controller in one of my project.
Below is my JSP code in which it will show three radio button. One is Insert, second radio button is Update and third radio button is Delete.
Once I click Insert radio button, it shows two text box next to Insert radio button, and same thing with other two radio button as well. Here is my jsfiddle

<form method="post" action="testOperation">

    <input type="hidden" name="name" id="dynamicName">
    <input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert

 <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update

 <input class="changeAction" type="radio" name="tt" value="Delete" div-id="delete"/> Delete

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

Below is my method in Controller code -
   @RequestMapping(value = "testOperation", method = RequestMethod.GET)
    public Map<String, String> testOperation() {
        final Map<String, String> model = new LinkedHashMap<String, String>();
        return model;
    }

    @RequestMapping(value = "testOperation", method = RequestMethod.POST)
    public Map<String, String> testOperations(@RequestParam String name,
                                              @RequestParam String node,
                                              @RequestParam String data) {
        final Map<String, String> model = new LinkedHashMap<String, String>();

        System.out.println(name);
        System.out.println(node);
        System.out.println(data);

        return model;
    }

Problem Statement:-
Suppose I click Insert radio button and type Hello in the first text and World in the second text box, then I will hit the submit button, and after that I am seeing Hello value in node variable and World value in data variable which is correct.
But somehow, name variable is coming as empty instead of that it should show insert value as I have clicked insert radio button.
And same thing should happen to update and delete radio button..
Any thoughts what wrong I am doing?

A: Replace Your Javascript by this. It worked for me.
$(document).ready(function(){
    $(".changeAction").on("click", function(){
        $('.changeable').html('')
        var divId = $(this).attr("div-id");
        $("#dynamicName").val(divId);
        divId = "#"+divId;
        var myInput = ' Node  <input type="text" name="node" size="20" />  Data  <input type="text" name="data" size="100"/>'
        $(divId).html(myInput);
    })
})

here is jsfiddle http://jsfiddle.net/EGJk8/5/

A: Change the code as,
From ,
@RequestParam String name

To ,
@RequestParam String tt

Because you have mentioned the name of the radio button as tt . So can't get the value like Insert , Update , Delete .


text:
Q: Using a DataServiceContext with custom annotations When using the an instance of the DataServiceContext class to materialise objects from an odata endpoint where the endpoint exposes some custom annotations, how does one get hold of the annotations data. I can't see any obvious extensibility points.

A: Custom annotations aren't exposed as a first-class concept on the DataServiceContext, but you can access them by hooking into the client response processing pipeline. This code will run after every entity is finished being read:
context.Configurations.ResponsePipeline.OnEntryEnded(
    entryArgs => DoSomething(entryArgs.Entry.InstanceAnnotations));

Internally, the WCF Data Services Client uses a lower-level library called ODataLib (aka Microsoft.Data.OData on NuGet). The response and request pipelines allow you to dip into that lower level to get extra information when you need it, but you still get all the conveniences of using the full-fledged WCF Data Services client library. The classes like ODataEntry, ODataFeed, etc. that you work with on the processing pipelines are all part of the ODataLib API.


text:
Q: Magento: edit quantity and update price of bundle option in quote item I am working with Magento bundle products that contain hidden bundle options that need to have the quantity updated programmatically. A problem arises when the bundle quantity is edited from the shopping cart. I have a button set up to submit the bundle quote item to an updateLineItemAction() method in my own CartController to handle the update of the hidden bundle option.
The updateLineItemAction() method locates the hidden bundle option and assigns the updated quantity to the "selection_qty_X" and "product_qty_X" properties, where X is the ID of the bundle option. Values in the "info_buyRequest" are also updated. After saving the quote item, there's a redirect to the cart to show the updated cart values.
The updated quantity is displayed correctly in the cart, and the hidden bundle option has the correct quantity assigned. The problem is that the bundle item price has not updated to reflect the updated quantity on the hidden bundle option. I did something similar to this in Magento 1.1.x and it worked fine. Doing this now in 1.4.1.2, the price is not automatically updated when the quote item is saved. I've tried saving the quote and the cart again after updating the item, but that doesn't seem to have any effect.
What is the proper way to recalculate the price for a quote item when subitems have had the quantity changed? Is there a better way to change the quantity of a quote item bundle option so that the price of the bundle item is updated correctly?

A: The solution for my case was to update the quantity values of the selections as noted in my original post, and also to adjust the quantity assigned to the bundle item associated with the hidden bundle option. This last step was not necessary in versions prior to Magento 1.4.


text:
Q: How to return value that is in a relation of specific index. If value came from input Let's say that input fag is informasjonsvitenskap in list(FagKode), if that is true i want it to print the values in karak that has the code INFO, like INFO100,INFO132 and INFO233. And if input fag is økonomi i want it to print the values in karak the has the code ECON. i also have a function, def legg_til(). thats will allow me to add an element in the list 'emner'. then the question will be. How to make it find the value that is in relation to input fag and print the specific value. :/
print('\nVelkommen til karakterprogrammet Infinitux\n')
print('----------------------------')

print('1: Emneliste','2: Legg til emne','3: Sett karakter','4: Karaktersnitt','5: Avslutt',sep='\n')
print('----------------------------')

emner = ['INFO100','INFO132','INFO233']
FagKode = [['informasjonsvitenskap','INFO'],['økonomi','ECON']]
karak = [['INFO100','C'],['INFO132','B'],['INFO233','C'],['ECON218','A']]

def start():
    global meny
    global fag
    meny = int(input('Tast inn ønsket valg (press 0 for meny): '))

    if meny == 1:
      valg_fag = input('Press Enter for å velge fag/emner (Skriv "alle" for å vise alle fag/emner)\n: ')

    if meny == 1 and valg_fag == 'alle':
      for i in karak:
        print(*i)

    elif meny == 1 and valg_fag == '':
      fag = input('- Fag: ')
      emnenivå = int(input('- Nivå: '))
      try:
        if fag in FagKode[0] and emnenivå in range(1,1000):
          ???????
          ???????
        else:
          print('Du har gjort noe feil!')
      except ValueError:
          print('NEI')

def legg_til():
    global meny
    global fag
    if meny == 2:
      add = input('Nytt emne:  ')
      emner.append(add.upper())

def karakter(): # Sletter/Setter ny karakter
    global meny
    if meny == 3:
      valg_emne = input('Emne: ')
      slett = input('Karakter (<enter> for å slette): '+karak==valg_emne)

    if meny == 3 and valg_emne in emner and slett == '':
      for i in range(len(karak)):
        if karak[i][0] == valg_emne:
          del karak[i][1]
        start()

    if meny == 3 and valg_emne in emner:
      pass

    if meny == 3 and valg_emne in emner and slett == 'HEI':
      for i in range(len(karak)):
        if karak[i][0] == valg_emne:
          print(karak[i][1])

def snitt():
  pass

def programslutt():
  global meny
  if meny == 5:
    print('Takk for nå, velkommen igjen!')
  else:
    ('Feil verdi')

start()
legg_til()
karakter()
programslutt()

Thanks for opinions in advance :)

A: Try this.
Make the variables FagKode and karak as dictionaries.
and try to get the values as follows.
return karak.get(FagKode.get(input(fag)))

or this for list.
for i, j in FagKode:
    if i==input(fag):
        for k, l in karak:
            if k==j:
                return l
return "Not Found"


text:
Q: call Matlab from C++ on Ubuntu I'm trying to call Matlab function from C++ (for NS-3) in Eclipse IDE on Ubuntu 18.04. I used Matlab Library Compiler to compile the .m file into a C++ Shared Library. How do I call the function correctly?
The corresponding MATLAB Runtime has been installed and configured. At first it can't find "mclmcrrt.h", I copied the /usr/local/MATLAB/R2018b/extern/include folder and changed the library header to include "./include/mclmcrrt.h". Then the IDE can find the header files correctly.
A C++ script to test the library as follows:
/* C = A+B */
#include <iostream>
#include "libtestAdd.h"

using namespace std;

int main(){
    double A[] = {1};
    double B[] = {2};
    int nargout = 1;

    mwArray input_A (1,1,mxDOUBLE_CLASS,mxREAL);
    input_A.SetData(M,1);
    mwArray input_B (1,1,mxDOUBLE_CLASS,mxREAL);
    input_B.SetData(K,1);
    mwArray C (1,1,mxDOUBLE_CLASS,mxREAL);

    if (!mclInitializeApplication(NULL,0)){
        std::cerr << "Could not initialize the application properly."
                  << std::endl;
        return -1;
    }
    libtestAddInitialize();
    testAdd(nargout, C, input_A, input_B);
    libtestAddTerminate();

    return 1;
}

The Matlab function is C=A+B.
The .m file has been compiled into a C++ Shared Library ("libtestAdd.so" and "libtestAdd.h"). The C++ script try to call the "testAdd" function from the library.
Matlab Runtime has been correctly installed. /etc/profile has been changed to export the follows path to LD_LIBRARY_PATH environment variable:
/usr/local/MATLAB/MATLAB_Runtime/v95/runtime/glnxa64:/usr/local/MATLAB/MATLAB_Runtime/v95/bin/glnxa64:/usr/local/MATLAB/MATLAB_Runtime/v95/sys/os/glnxa64

The error messages as follows:
~/Desktop/libtestAdd/for_testing$ cd "/home/csrl/Desktop/libtestAdd/for_testing/" && g++ main.cpp -o main && "/home/csrl/Desktop/libtestAdd/for_testing/"main
/tmp/ccyFn7iq.o: In function `main':
main.cpp:(.text+0xde): undefined reference to `libtestAddInitialize'
main.cpp:(.text+0xf4): undefined reference to `testAdd(int, mwArray&, mwArray const&, mwArray const&)'
main.cpp:(.text+0xf9): undefined reference to `libtestAddTerminate'
/tmp/ccyFn7iq.o: In function `mwException::mwException()':
main.cpp:(.text._ZN11mwExceptionC2Ev[_ZN11mwExceptionC5Ev]+0x46): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::mwException(char const*)':
main.cpp:(.text._ZN11mwExceptionC2EPKc[_ZN11mwExceptionC5EPKc]+0x5a): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::mwException(error_info*, bool)':
main.cpp:(.text._ZN11mwExceptionC2EP10error_infob[_ZN11mwExceptionC5EP10error_infob]+0x61): undefined reference to `ref_count_obj_addref_proxy'
main.cpp:(.text._ZN11mwExceptionC2EP10error_infob[_ZN11mwExceptionC5EP10error_infob]+0x7a): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::~mwException()':
main.cpp:(.text._ZN11mwExceptionD2Ev[_ZN11mwExceptionD5Ev]+0x36): undefined reference to `ref_count_obj_release_proxy'
/tmp/ccyFn7iq.o: In function `mwException::what() const':
main.cpp:(.text._ZNK11mwException4whatEv[_ZNK11mwException4whatEv]+0x25): undefined reference to `error_info_get_message_proxy'
/tmp/ccyFn7iq.o: In function `mwException::raise_error()':
main.cpp:(.text._ZN11mwException11raise_errorEv[_ZN11mwException11raise_errorEv]+0x2a): undefined reference to `mclcppGetLastError_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::mwArray(unsigned long, unsigned long, mxClassID, mxComplexity)':
main.cpp:(.text._ZN7mwArrayC2Emm9mxClassID12mxComplexity[_ZN7mwArrayC5Emm9mxClassID12mxComplexity]+0x52): undefined reference to `mclGetMatrix_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::~mwArray()':
main.cpp:(.text._ZN7mwArrayD2Ev[_ZN7mwArrayD5Ev]+0x26): undefined reference to `ref_count_obj_release_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::SetData(double*, unsigned long)':
main.cpp:(.text._ZN7mwArray7SetDataEPdm[_ZN7mwArray7SetDataEPdm]+0x2b): undefined reference to `array_ref_set_numeric_mxDouble_proxy'
collect2: error: ld returned 1 exit status

A: You need to link with the .so file. Add it to the end of your compile command.


text:
Q: should ldexp round correctly I'm a bit surprised with MSVC ldexp behavior (it happens in Visual Studio 2013, but also with all older versions at least down to 2003...).
For example:
#include <math.h>
#include <stdio.h>
int main()
{
    double g=ldexp(2.75,-1074);
    double e=ldexp(3.0,-1074);

    printf("g=%g e=%g \n",g,e);
    return 0;
}

prints
g=9.88131e-324 e=1.4822e-323

The first one g is strangely rounded...
It is 2.75 * fmin_denormalized, so i definitely expect the second result e.
If I evaluate 2.75*ldexp(1.0,-1074) I correctly get same value as e.
Are my expectations too high, or does Microsoft fail to comply with some standard?

A: While the question does not explicitly state this, I assume that the output expected by the asker is:
g=1.4822e-323 e=1.4822e-323

This is what we would expect from a C/C++ compiler that promises strict adherence to IEEE-754. The question is tagged both C and C++, I will address C99 here as that is the standard I have in hand.
In Annex F, which describes IEC 60559 floating-point arithmetic (where IEC 60559 is basically another name for IEEE-754) the C99 standard specifies:

An implementation that defines __STDC_IEC_559__ shall conform to the
  specifications in this annex. [...] The scalbn and scalbln
  functions in <math.h> provide the scalb function recommended in the
  Appendix to IEC 60559.

Further down in that annex, section F.9.3.6 specifies:

On a binary system, ldexp(x, exp) is equivalent to scalbn(x, exp).

The appendix referenced by the C99 standard is the appendix of the 1985 version of IEEE-754, where we find the scalb function defined as follows:

Scalb(y, N) returns y × 2N for integral values N without computing 2N.

scalb is defined as a multiplication with a power of two, and multiplications must be rounded correctly based on the current rounding mode according to the standard. Therefore, with a conforming C99 compiler ldexp() must return a correctly rounded result if the compiler defines __STDC_IEC_559__. In the absence of a library call setting the rounding mode, the default rounding mode "round to nearest or even" is in effect.
I do not have access to MSVC 2013, so I do not know whether it defines that symbol or not. This could even depend on a compiler flag setting, such as /fp:strict.
After tracking down my copy of the C++11 standard, I cannot find any reference to __STDC_IEC_559__ or any language about IEEE-754 bindings. According to the answer to this question this is because that support is included by referring to the C99 standard.

A: This happens because during the ldexp calculation the 2.75 gets truncated to 2, which happens because at that small of a denormalized number the bits that represent the '.75' part get shifted off the end of the representable number and disappear.  Whether this is a bug or designed behavior can be debated.
When calculating 2.75*ldexp(1.0,-1074) normal rounding happens, and the 2.75 becomes 3.
EDIT: ldexp should round correctly, and this is a bug.

A: OP results do not fail to comply with the C spec as that spec does not define the preciseness of calculations.
OP result may have failed IEEE 754, but it depends on the rounding mode in use at the time, which is not posted.  Yet OP's reports 2.75*ldexp(1.0,-1074) worked as expected implying at that time, the expected rounding mode was in effect.
Using printf("%la",x) aids in seeing clearly what is happening near the limits of double.
I would expect g to "round to nearest - ties to even" with the result of 0x1.8p-1073 - which did occur with gcc on windows.
Ideally g would have the value of 0x1.6p-1073
0x0.0p-1073 Zero
0x0.8p-1073 next higher double DBL_TRUE_MIN
0x1.0p-1073 next higher double
0x1.6p-1073 ideal `g` answer, but not available as a double
0x1.8p-1073 next higher double

To be fair, it could be a processor bug - it has happened before.

Ref
double g=ldexp(2.75,-1074);
printf("%la\n%la\n", 2.75,ldexp(2.75,-1074));
printf("%la\n%la\n", 3.0 ,ldexp(3.0 ,-1074));
double e=ldexp(3.0,-1074);
printf("%la\n%la\n", g,e);
printf("%la\n%la\n", 9.88131e-324, DBL_TRUE_MIN);
printf("g=%g e=%g \n",g,e);

0x1.6p+1
0x1.8p-1073
0x1.8p+1
0x1.8p-1073
0x1.8p-1073
0x1.8p-1073
0x1p-1073
0x1p-1074
g=1.4822e-323 e=1.4822e-323


text:
Q: Additional custom build directories .targets file I have defined some custom build rules to use a custom version of Qt (DAZ Studio SDK) in my Visual Studio Projects using the ones from https://code.google.com/p/xr-qt-msvc/source/browse/#svn%2Ftrunk%2Fmsvc-10.0 .
I am currently struggling since the line
<CommandLineTemplate>$(DAZSDKDIR)\bin\$(Platform)\moc.exe [QtMocNoWarnings] [QtCoreLib] [QtShared] [QtThread] [QtUnicode] [QtLargeFile] [QtKeywords] [QtOpenGLLib] [QtNoDebug] [QtGuiLib] [Inputs] -o$(IntDir)%(QtMocFilename).cpp
&& cl.exe $(IntDir)%(QtMocFilename).cpp [QtCommandLine] /c /Fo"$(IntDir)%(QtMocFilename).obj"</CommandLineTemplate>

(Notice the cl.exe called on the output MOC)
The fact is that I am not able to pass to cl.exe the include directories I have specified using AdditionalIncludeDirectories.
Is there any way to pass them to the cl compiler?

A: I found the problem.
Instead of using "Additional Include Direcotries", the user must use the V++ Directories tab.


text:
Q: How can I ensure that auth.dll can be loaded? I'm trying to use crypto++ in c++ clr class library.
The problem is that I get an error as I run the app, but it builds successfully.
Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly 'auth.dll' or one of its dependencies. A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A)
   at ConsoleApp52.Program.Main(String[] args)

This error only occurs when I include anything from crypto++
#include "dll.h"
#include "sha.h"
#include "filters.h"
#include "hex.h"

If I remove the following lines, it works.
I've tried copying the cryptopp.dll to the bin/x64/Debug and bin/Debug, but it did not resolve the issue.
What else do I need to include? Am I Missing something?
Dependecies:

A: Error code 0x8007045A most often means 32/64 bit DLL incompatibility.
If you're using native DLLs with managed code, make sure to use 64-bit versions on a 64-bit OS.


text:
Q: I want to prioritize which record to select from multiple records which have same ranking The table structure to solve
| **Email** |  **Product name** |  **price** |    **Creatdt**   |
|R@gmail.com| ABC               | 9.99       |05/07/19 12:30:21 |
|R@gmail.com| efg               | 12.99      |05/07/19 12:30:21 |
|R@gmail.com| xyz               | 15.99      |05/07/19 12:30:21 |
|M@gmail.com| ABC               | 9.99       |05/07/19 12:30:21 |
|M@gmail.com| efg               | 12.99      |05/07/19 12:35:42 |

1 record for 1 email tried to execute below query
Select Z from(
Select rank() over (PARTITION BY Email ORDER BY CreateDt desc) AS RN,
P.email,
P.product name,
P.price,
p.Creatdt
From product table P
)Z
Where Z.RN = 1

After executing the ranking query the result
| **Email** | **Product name** | **price**|    **Creatdt**   |
|R@gmail.com| ABC              | 9.99     |05/07/19 12:30:21 |
|R@gmail.com| efg              | 12.99    |05/07/19 12:30:21 |
|R@gmail.com| xyz              | 15.99    |05/07/19 12:30:21 |
|M@gmail.com| efg              | 12.99    |05/07/19 12:35:42 |

So I need only 1 R@gmail.com record, and want to prioritize based on product name.

*

*CASE 1 If product name is ABC then select that record with ABC as product name in the output table by excluding the records with efg and xyz.

*CASE 2 if there are two same records with efg and xyz then I want to select xyz as product name record to the destination table excluding efg record.

The table output should be
| **Email** | **Product name** | **price** |    **Creatdt**   |
|R@gmail.com| ABC              | 9.99      |05/07/19 12:30:21 |
|M@gmail.com| efg              | 12.99     |05/07/19 12:35:42 |

A: Sounds like you just need to add more columns to the ORDER BY clause in the RANK function:
SELECT Z.*
FROM(   SELECT RANK() OVER( PARTITION BY Email
                            ORDER BY CreateDt DESC,
                                     CASE
                                        WHEN product_name = 'abc' THEN 1
                                        WHEN product_name = 'xyz' THEN 2
                                        ELSE 3
                                     END) RN,
                P.email,
                P.product_name,
                P.price,
                p.Creatdt
        FROM product_table P)Z
WHERE Z.RN = 1


text:
Q: What is the meaning of AFAIK abbreviation? I would like to understand what is the meaning of AFAIK, as used in this answer at StackOverflow!

A: It stands for As Far As I Know.

AFAIK
  in British English
  messaging & social media
  ABBREVIATION FOR
  as far as I know

https://www.collinsdictionary.com/dictionary/english/afaik


text:
Q: Template must have exactly one root element with custom directive replace: true I am having issues with a custom directive with replace: true,
http://jsbin.com/OtARocO/2/edit
As far as I can tell, I do only have one root element, my , what is going on here?
Error: Template must have exactly one root element. was:

{{ item.name }}

row2

Javascript:
var app = angular.module("AngularApp", [])
  .directive('custom', [function () {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'lineItem.html',
      link: function(scope, element, attrs) {

      }
    };
  }])
.controller('MyCtrl', ['$scope', function($scope) {
  $scope.items = [
    {
      name: 'foo'
    },
    {
      name: 'bar'
    },
    {
      name: 'baz'
    }
  ];
}]);

HTML:
<!DOCTYPE html>

  <meta name="description" content="Angular Avatar Example" />

<meta charset=utf-8 />
<title>JS Bin</title>

      <custom data-ng-repeat="item in items"></custom>

A: Watch out with comments in directive templates as well!
docs

Watch out for html comments at the beginning or end of templates, as these can cause this error as well. Consider the following template:

 ...

The  comment is interpreted as a second root element and causes the template to be invalid.

A: Seems to be a known bug of AngularJs.
What you could do is to change the restriction to attribute instead of element, remove the tbody from the template and use a
 in your html code.
Basically:
Your template becomes:

{{ item.name }}

row2

Your directive:
return {
  restrict: 'A',
  templateUrl: 'lineItem.html',
  link: function(scope, element, attrs) {

  }
};

And your HTML :

A: This error could also occur with an incorrect url to a (non-existing) template. See https://stackoverflow.com/a/34284646/430885

A: Make sure that all the html elements that will be echoed/written to the page, have been wrapped in an envelop. i.e if my template will write a form input that has a label,input[text] and a span. Remember to wrap everything in a div.
i.e

 My Directive Label
<input type='text' ng-model='xyz' />

Another Error you may receive may be  "Unterminated string object" which means that the template string has not been terminated properly - to solve this just include a backlash character "\" at the end of each line break i.e
.
.
replace:true,
restrict:'ACE',
template : "
 \
 My Directive Label \
<input type='text' ng-model='xyz' /> \
 \

 \
",....


text:
Q: XSD: complex type Attributes? I am creating attributes for a complex-type element. I created an attribute, which itself is of complex type. When I tried compiling my code, it threw an error saying could not find simple-type attribute corresponding to the attribute of complex-type. Can't we create attributes of complex-type?..I also looked at w3c schools, but it does not elaborate much on attributes for complex-type elements.
Thanks!

A: You cannot have complex types as attributes - only basic types like string, int and so forth. You can restrict your values (e.g. define a maximum length for a string, or a value range for an int), but you CANNOT use a complex type as an attribute in XSD.
For reference, check the MSDN Library:
The name of a built-in data type or a simple type defined in this schema (or another schema indicated by the specified namespace). The type must be a QName. The type can include a namespace prefix. The type attribute can only be present when the content does not contain a simpleType element.
The built-in data types are all simple types (string, int, etc.).
Marc


text:
Q: apostrophe rules in academic writing I've been reading papers from nucleate boiling mechanics and related areas, and I keep being puzzled by the usage of apostrophes. For example, we talk about bubbles:
Numerical simulations of the bubble dynamics in viscoelastic media
showed varying degrees of success in accurately predicting the observations.
Here we see bubble dynamics with no apostrophe. Then on the next page:
Visualization of the multiflash imaging technique with
timing diagrams of the variable flash sequences used during each
phase of the bubble's evolution with example images.
Here we have bubble's evolution, apsotrophe present.  Or, another example:
The assumption of material homogeneity in the model is
likely also not valid for agarose gels, particularly in the early
parts of a bubble's lifetime.
So is it equally correct to say the bubble's size and the bubble size, the heater's tempetature and the heater temperature, etc.?
Please help me sort it out. Many thanks to all who had enough patience to read all this.

A: You're seeing a mix of noun adjuncts, where the word "bubble" is used to modify another word, and possessives, where is said to belong to a bubble.
Bubble dynamics is a discipline within fluid mechanics. To name the field, we need to have a general, described term like this. "A bubble's dynamics" would be talking about the motion of a particular bubble (and would not match with the actual way we use the term 'dynamics' within engineering science). You will seldom see possessives used to describe a topic, abstractly.
The possessive is used in "each phase of the bubble's evolution" to refer to the phases belonging to a particular bubble. Thus, the bubble in question has an evolution. Though sometimes this could refer to a characteristic bubble rather than a concrete example of a bubble, the possessive would not be used to name the topic examining bubbles evolving: that topic would be bubble evolution.


text:
Q: I need to help with a formula to find the length of a line. I have a rectangle which I know the width and height of it.
I need to draw a line inside the rectangle and the information that I have include knowing the starting point of the line as well as the angle of the line.
My question is how can I calculate the length of the line given the informaiton that I have?
I don't know where the line will end up, I just have a starting point, the angle and the general width and height of the rectangle.
I tried to draw some sample lines to show you what I'm trying to do, I need to find the length of the red line so I can draw it in my App.

A: Since the problem remains the same when the rectangle is rotated/flipped, we can assume for simplicity that the starting point is on the bottom border of the rectangle. (When rotating the problem, make sure to get the angle and width/height of the rotated problem correct.)
Let $w$ denote the width and $h$ the height of the rectangle. Let the starting point have distance $x$ from the left border of the rectangle. Let $\alpha$ be the angle between your line and the bottom line that you get by "rotating your line to the left."
Image:

We want to compute the point $\overline{EF}$. If $\operatorname{arcsec}$ denotes the inverse function of $x\mapsto\frac1{\cos(x)}$ and $$\alpha=\operatorname{arcsec}\left(\frac{\overline{CE}}{\overline{AE}}\right)=\operatorname{arcsec}\left(\frac{\sqrt{x^2+h^2}}{x}\right),$$
then your line goes straight to the top left corner and the length is $\sqrt{x^2+h^2}$. If $\alpha$ is less than that, then you will "bump" into the left border and we have $\overline{AF}=\tan(\alpha) x$. Hence the length of the line is $$\sqrt{(\tan(\alpha)^2+1) x^2}=\lvert\sec(\alpha)x\rvert.$$
Let $\beta=\pi-\alpha$. You get the same thing: If $$\beta=\operatorname{arcsec}\left(\frac{\overline{ED}}{\overline{BE}}\right)=\operatorname{arcsec}\left(\frac{\sqrt{(w-x)^2+h^2}}{(w-x)}\right),$$
then the line goes straight up to the top right corner. So the length is $\sqrt{(w-x)^2+h^2}$. If $\beta$ is less than that, then analogously to before, the length of the line is $$\lvert\sec(\beta)(w-x)\rvert.$$
Now, if $\alpha$ is big enough such that you don't bump into the left border and $\beta$ is big enough such that you don't bump into the right border, you will bump into the top border (as in my image). In this case, let $F^\top$ be the orthogonal projection of $F$ onto the bottom border. Then $\overline{F^\top E}=h\cot(\alpha)$ so that the length of the line is $$\sqrt{h^2\cot(\alpha)^2+h^2}=\lvert h\csc(\alpha)\rvert.$$

Example (30°): After flipping we see $h=10, w=6, \beta=\frac\pi6, x=2$. We compute $$\operatorname{arcsec}\left(\frac{\sqrt{(w-x)^2+h^2}}{(w-x)}\right)=\operatorname{arcsec}(\sqrt{29}/2)\approx1.19>\beta.$$
So we will bump into the right border with a line length of $$\lvert\sec(\beta)(w-x)\rvert=4\sec(\pi/6)=\frac{8}{\sqrt 3}.$$

A: Assuming the lines begin and end on the rectangle, use trigonometric functions sin, cos. For example, in the third rectangle, denoting the line length $\ell$ we have:
$$\ell = 6/\cos(35^\circ)$$


text:
Q: Why PyCharm adds current file and parent directory to path? I'm using PyCharm on Windows 10 with Python 3.8. I was trying to get Python imports working from a parent directory using:
import sys
sys.path.append("..")  # Adds higher directory to python modules path.
from trace_recursion import trace

It worked fine, but then I noticed that commenting out sys.path.append("..")  # Adds higher directory to python modules path. also worked.
I checked this out running from a terminal, and commenting out sys.path.append("..") broke the program, as expected.
I then did a text comparison of the output of print(sys.path) and the output from PyCharm includes the current file and the project directory, whereas the output when run from a terminal does not.
What is going on here please? Has PyCharm cached the extended path from the first time I ran sys.path.append(".."), or is it some kind of default behavior of PyCharm to add that anyway? Or something else?

A: It's caused by these two options, that are by default selected in every run configuration:
Add contents root to PYTHONPATH
Add source root to PYTHONPATH

https://www.jetbrains.com/help/pycharm/creating-and-editing-run-debug-configurations.html#createExplicitly
If unchecking those doesn't help, then the issue is most likely the same as here: Why does PyCharm always add "contents root" to my PYTHONPATH, and what PYTHONPATH?

A: Pycharm has two options which are set by default:

Add contents root to PYTHONPATH
Add source root to PYTHONPATH

If the options are checked then you would have the scenario you had here, you can try unchecking the option and if the scenario persists then you would like to try out this link:-
Why does PyCharm always add "contents root" to my PYTHONPATH, and what PYTHONPATH? (from stack overflow)
Main Points:-

*

*Uncheck the options given above

*If the error persists then check the link above.


text:
Q: Resposta do socket com problemas no Android NDK Estou tentando implementar essa library, parson, no C, mas quando tento manipular os dados obtidos via conexão socket(SO link), recebo um null, o que não acontece quando coloco manualmente o json no C.
O problema está na resposta do socket, que não é recebida corretamente, pois no logcat do android tudo antes da resposta é apagado, ficando um campo em branco.
Abaixo, está toda a função usada para obter uma resposta do servidor.
#include "HttpGet.h"
#include <android/log.h>
#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netdb.h> /* struct hostent, gethostbyname */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include "parson.h" // JSON

int HttpGetPost(char *webserver,const char *url)
{
    __android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "Enter HttpGet function!");
          char* argva = "?tokenweb=meuapp";

      __android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "Enter argvs %s ",argva);

    int argc = 5;
      char* argv[7];
      argv[1] = "127.0.0.1";
      argv[2] = "80";
      argv[3] = "GET"; //POST //GET
      argv[4] = "/testmobile.php";
      argv[5] = "?tokenweb=meuapp";
      argv[6] = "";
      __android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "Enter argv2 %s ",argv[4]);

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    //message=malloc(message_size); //original
    message=malloc(1024);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */

    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) {
        error("ERROR, no such host");
        __android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "ERROR, no such host");
    }
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) {
            error("ERROR opening socket");
            __android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "ERROR opening socket");
        }
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
            error("ERROR connecting");
            __android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "ERROR connecting");
        }
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");

    /*
    do {
       printf("%s", response);
       __android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "Response: \n %s", response);

       //strcat(json_response, response);
       //strcpy(json_response,  response);
       json_response = response;

       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);
    */
    do {
        bytes = read(sockfd,response+received,total-received);
        __android_log_print(ANDROID_LOG_INFO, "---from--jni-RN---", "Response: %s", response);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    //__android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "Response2: \n %s", response);

//============ Verificação de Segurança =================================================//
      __android_log_print(ANDROID_LOG_INFO, "-----from--jni-1-----", "Response: \"%s\"", response); // = {"message":"success"}"
      __android_log_print(ANDROID_LOG_INFO, "-----from--jni-1a-----", "Response: '%s'", response);

      JSON_Value *user_data = json_parse_string(response);

      const char *msgs = json_object_get_string(json_object(user_data), "message");

    //Auth HashCode
//  __android_log_print(ANDROID_LOG_INFO, "-----from--jni-------", "Response Compare: \n [%s]", name );
        __android_log_print(ANDROID_LOG_INFO, "-----from--jni-1-----", "Json Message  1. [%s] ", msgs);
        //__android_log_print(ANDROID_LOG_INFO, "-----from--jni-2-----", "Signature Auth 2. [%s] \n",signature);

    //Auth PackageName

    char text[100] = "{\"key\": \"valor\"}";
    JSON_Value *data = json_parse_string(text);
    const char *sdata = json_object_get_string(json_object(data), "key");
    __android_log_print(ANDROID_LOG_INFO, "-----from--jni-1-----", "Json Key  1. [%s] \n", sdata);

    /* close the socket */
    close(sockfd);

    free(message);
    return 0;
}

Executando o código acima recebo a seguinte mensagem no logcat.
com.dou361.ijkplayer_simple.example I/-----from--jni-------: Enter mmain function!
com.dou361.ijkplayer_simple.example I/-----from--jni-------: Enter HttpGet function!
com.dou361.ijkplayer_simple.example I/-----from--jni-------: Enter argvs ?tokenweb=meuapp
com.dou361.ijkplayer_simple.example I/-----from--jni-------: Enter argv2 /testmobile.php
                                                             testando_msg
                                                             testando_msg
                                                             testando_msg"
                                                             testando_msg'
com.dou361.ijkplayer_simple.example I/-----from--jni-1-----: Json Message  1. [(null)]
com.dou361.ijkplayer_simple.example I/-----from--jni-1-----: Json Key  1. [valor]

Imagem

Como eu poderia receber essa resposta corretamente?
Como por exemplo com.dou361.ijkplayer_simple.example I/-----from--jni-1-----: Json Message  [testando_msg].

A: A solução encontrada, porem não a mais desejada está abaixo, usando o do/while em um loop que ocorre 2 vezes, é possível contornar o null que é recebido ao tentar obter o response. Como o response esta sendo processado no loop, é recebido 2 valores, o primeiro o null, e o segundo a variável desejada. Através do if(msgs) é possível ignorar o null e receber os dados desejados.
Segue o trecho modificado.
do {
  char * httpbody = strstr(response, "{\"message\"");

  JSON_Value * user_data = json_parse_string(httpbody);
  const char * msgs = json_object_get_string(json_object(user_data), "message");

  if (msgs) {
    __android_log_print(ANDROID_LOG_INFO, "---from--jni----", "Response:[%s]", httpbody);
    __android_log_print(ANDROID_LOG_INFO, "---from--jni-json-", "Json Message [%s]", msgs);
  }
  bytes = recv(sockfd, response, 1024, 0);
  if (bytes < 0)
    printf("ERROR reading response from socket");
  if (bytes == 0)
    break;
  received += bytes;
} while (1);

Com isso, é possível ignorar o \r\n ou blank line que é recebido com o response.
Resultado desejado obtido:
com.dou361.ijkplayer_simple.example I/---from--jni----: Response:[{"message":"success"}]
com.dou361.ijkplayer_simple.example I/---from--jni-json-: Json Message [success]