text:
Q: Dual representation of $\mathfrak{sl}(n)$ The natural representation $\mathbb{C}^n$ of $\mathfrak{sl}(n)$ has dual representation $\left(\mathbb{C}^n\right)^\vee, \ $ explicitly:
$\rho(h_i)=-h_i, \ \ \
\rho(x_i)=-y_i, \ \ \
\rho(y_i)=-x_i.$
This means that the weights of $\left(\mathbb{C}^n\right)^\vee$ are the same of  $\ \mathbb{C}^n$ but with opposite sign.
I believe that this implies that the two representations are isomorphic, since we can swap positive roots and negative roots of $\mathfrak{sl}(n)$, and obtain the same effect. I'm not sure if I can turn this into a formal argument though.
I think I could show that the map that send an element of $sl(n)$ to its inverse transpose is a Lie algebra homomorphism, since $\rho([x_i,y_i])=\rho(h_i)=-h_i=[-y_i,-x_i]=[\rho(x_i),\rho(y_i)].$

A: The observation about swapping positive and negative roots that you make shows that the two representations are related by an automorphism of $\mathfrak{sl}(n)$. Explicitly, this automorphism is given by $A\mapsto -A^t$. As it turns out, this is not an inner automorphism, and hence this is not quite enough to make the two representations isomorphic (as can be seen from the highest weights described in the answer of @AlvaroMartinez ).

A: In fact it will not be. Write the fundamental weights as $\lambda_1,...\lambda_{n-1}$. The standard representation $V=\mathbb{C}^n$ has highest weight $\lambda_1$, and lowest weight $\mu=w_0(\lambda_1)=-\lambda_{n-1}$. Therefore $V^{\vee}$ has highest weight $-\mu=\lambda_{n-1}$.


text:
Q: How to choose the right Composer packages? I'm a bit confused about using Composer.
I have built my own package manager, that uses a config-file and a large SVN-repo that contains all possible libraries (both PHP and Javascript / CSS) I need in several different projects. I download these packages myself from the library websites.
Now I'm trying to use Composer instead, since I like the automatic dependency checking and want to use something that everybody else does. But how do you decide what packages are best?
For example, for CodeMirror, I used to download the latest stable version from https://codemirror.net/ . But when I look in Packagist  I see so many different versions that I don't know which to choose. It seems everybody can create new packages for Composer ?  I just need the official ones.
So, how do you guys pick the packages you need?

A: To answer your question directly, for any component you want to import into your project, the way to find the "canonical" source - as opposed to various forks - is to go back to the original source and see what their usage/install instructions suggest. If they support a Packagist-based install, they will usually say so. If not, but there is a composer.json in their (typically) Github repository, then you can add the repository to your composer.json and then require the package as normal.
However, more generally, I think there is some confusion about what Composer really does. As noted in the comments, Composer is a dependency manager for PHP. Packagist is the primary repository for composer-managed packages. The CodeMirror library you cited is fundamentally a javascript library.
Now it's true that if you search for "codemirror" on Packagist, you will see lots of results there, some of which are labeled as Javascript components. But they are primarily:

*

*wrappers that allow consumers to interact with or simply load CodeMirror in PHP-based view-scripts, like conquer/codemirror for the Yii framework, or nitrado/code-mirror-bundle for the Symfony framework; or

*shim repositories for the Components project - like components/jquery, for example - which are then installed using the command-line script from their Component Installer for Composer
Bottom line: Composer is primarily used for importing PHP packages. It takes some gymnastics - like the Component Installer for Composer noted above - to make it usable/helpful for non-PHP packages.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting a table by Date SQlite I  have a table with 3 columns.(Id-Primary Key, Task-string, due date-string). i want to insert task and set due date. Then, i want to display them in list view.Before i display them in list view, i want this table sorted based on date from most recent to least.

A: Cursor cursor = db.query(DATABASEHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);

so argument order will be "COLUMN_NAME ASC"


text:
Q: Vee-Validate validation groups i using vee-validate of my project. But I'm hanging out.
I have 3 input fields.
When only 1 of these fields is valid, the other inputs must be valid.
Ex. Like jquery
Jquery validation groups

A: I found the correct solution:
HTML CODE
<input type="text" name="mobilePhone" class="form-control" v-model="form.mobilePhone" v-validate ="{ rules: { required: contactInfo} }" :class="{'input': true, 'is-danger': errors.has('mobilePhone') }">

<input type="text" name="emailAddress" class="form-control" v-model="form.emailAddress" v-validate ="{ rules: { required: contactInfo} }" :class="{'input': true, 'is-danger': errors.has('emailAddress') }">

<input type="text" name="phoneNumber" class="form-control" v-model="form.phoneNumber" v-validate ="{ rules: { required: contactInfo} }" :class="{'input': true, 'is-danger': errors.has('phoneNumber') }">

JS Computed code
computed: {
    contactInfo () {
      if (this.form.phoneNumber || this.form.mobilePhone || this.form.emailAddress) {
        return false
      }
      else {
        return true
      }
    }
  }


text:
Q: Facebook hash key issue I am trying to access Facebook info of loggedIn user. For that I read through the various docs and found that hash key configuration is required for this on developer section of facebook where application is created and generating Facebook App-Id. I tried to generate hash key for filling into Native Android App section on facebook developer portal. I gone through many links for this like Here
But hash key is not working at all. Sometimes it says no hash is match or sometime it just promt a facebook dialog and disappears.
But still it's not working in my Device. It's working fine on Emulator. I am using Mac system, is this any issue?
Can anybody guide me if I am missing something? Do I need to edit more things in Application setting on facebook developer portal?

A: This is because the device is creating a new key hash which is not in your app settings. So you have to update the keyhash accordingly. Use this in onCreate()
try {
            PackageInfo info = getPackageManager().getPackageInfo("YOUR_PACKAGE_NAME", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }

A: This has been an issue for many people. Alternatively from generating the hash from commandline, you can generate it from code, and then print it to the log so you can copy it from there.
The following code does that. You can place it in your activity onCreate() for instance, and remove it once you have the hash. Obviously you need to change the package name to your own.
try {
    PackageInfo info = getPackageManager().getPackageInfo(
            "com.facebook.samples.loginhowto",
             PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}

This answer nicely describes how to do the same from commandline, if you don't want to use the code. Both should have the same result.

A: Try this when session open
try {
            PackageInfo info = getPackageManager().getPackageInfo("YOUR_PACKAGE_NAME", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }


text:
Q: Como ejecutar una funcion escrita en php que recibe datos de cajas de texto desde un boton en otro formulario He buscado por un sin numero de paginas y casi tengo la respuesta correcta , pero falta algo:
lo que pasa es que yo ejecuto una funcion(Guardar()) en una pagina(registrar_cliente.php), ahora, lo que que quiero hacer es que en mi otra pagina(cliente.php) mediante un boton solo me ejecute la funcion mas no que me direccione a la segunda pagina y lo ejecute.
Lo pude lograr pero, al ejecutarlo es como si no estuviera jalando los datos de las cajas de texto.y me sale un error de base de datos que seria logico al no digitar el dni , pero si lo digito.
ESTE ES EL CODIGO:
registrar_cliente.php
<?php
function Guardar()
{
    $Conexion = new mysqli('localhost','root','12345678','prayci');
  $name= $_POST["Name"];
    $dni=$_POST["DNI"];
  $direccion= $_POST["Direccion"];
  $mysql = 'CALL Registrar_Cliente(?, ?, ?, @p_mensaje);';
  $stmt = $Conexion->prepare($mysql);
  $stmt->bind_param('sis',$name,$dni,$direccion);
  $stmt->execute();
  //variable de salida
   $select = mysqli_query($Conexion,'SELECT @p_mensaje');
   $result = mysqli_fetch_assoc($select);
   $mensaje = $result['@p_mensaje'];
   echo ($mensaje);
}

  ?>

cliente.php

De antemano gracias.

A: creo que lo que tienes que utilizar es AJAX.

$('#IDFORMULARIO').submit(function(event){   //donde #IDFORMULARIO es el id del formulario de registro
      var parametros = $(this).serialize(); //esto se encarga de obtener todas los datos ingresados
      $.ajax({ //la llamada ajax
        type: "POST",
        url: "registrar_cliente.php", //el archivo donde se encuentra el código a ejecutar
        data: parametros, //los datos ingresas en el formulario lo envías aquí
        success: function(data) {
          $('#resultado').html(data); //donde #resultado es el div donde se muestra el mensaje
        }
      });
      event.preventDefault(); //previene que el boton submit realice su comportamiento normal
    });
<form role="form" id="IDFORMULARIO" method="post" autocomplete="off">

  <input id="name" type="text" class="validate" name="name" required>
  Name
  <input type="text" class="validate" name="DNI">
  DNI
  <input type="text" class="validate" name="Direccion">
  Direccion

    <input class="btn right" type="submit" value="Registrar">

</form>


text:
Q: define the action of the free vector space functor on maps using the Yoneda lemma? I'm reading Emily Riehl's Category theory in context. In chapter 4, I saw the free vector space functor $
\Bbb{k}[-]: Set \to Vect_{\Bbb{k}}
$ and the forgetful functor $U: Vect_{\Bbb{k}} \to Set$. Here $Set$ is the cateogry of all sets and $Vect_{\Bbb{k}}$ is the category of all vector space on field $\Bbb{k}$.
I knew that these two functors are adjoint to each other. And it can be expressed by the universal property that linear maps $\Bbb{k}[S] \to V$ correspond naturally to functions $S \to U(V)$.
But I don't understand the following sentence, quoted from the book Cateogry theory in context, chapter 4 at the begining:

By the Yoneda lemma, this universal property can be used to define the action of the free vector space functor $\Bbb{k}[-]$ on maps.

I'm confused on this statement.

*

*Why is it related to the Yoneda lemma? I cannot see the relation between the statement and the Yoneda lemma.

*What is the meaning of "maps" in the statement? Is it the morphism in the Set category?

I attach a screenshot for the case if I didn't describe the context well. The purple sentence is what I feel confused.
Thanks!

A: Suppose $G : D \to C$ is a functor which has a "pointwise left adjoint" in the sense that for every object $c \in C$ you have constructed an object $F(c)$ satisfying the natural isomorphism
$$\text{Hom}_D(F(c), d) \cong \text{Hom}_C(c, G(d))$$
in $d$. Equivalently, the functor $\text{Hom}_C(c, G(-))$ is representable for every $c$. A priori this is not enough information to say that $G$ has a left adjoint, because $F$ has only been defined on objects, not on morphisms. However, it turns out that knowing $F$ on objects automatically determines it on morphisms by the universal property + the Yoneda lemma, as follows:
Suppose $f : c_1 \to c_2$ is a morphism. We'd like to use this to construct a morphism $F(f) : F(c_1) \to F(c_2)$. By the Yoneda lemma, this is the same as constructing a natural transformation $\text{Hom}_D(F(c_2), -) \to \text{Hom}_D(F(c_1), -)$. By the universal property we have $\text{Hom}_D(F(c_i), -) \cong \text{Hom}_C(c_i, G(-))$, so a morphism $f : c_1 \to c_2$ naturally induces a natural transformation $\text{Hom}_C(c_2, G(-)) \to \text{Hom}_C(c_1, G(-))$ which via the above identifications gives $F(f)$.
This is very abstract, so let's unwind what it actually says in the case that $G$ is the forgetful functor $U : \text{Vect} \to \text{Set}$ and its left adjoint $F$ is the free vector space functor. Let $f : X \to Y$ be a map of sets ("maps" here means morphisms in $\text{Set}$, or just ordinary functions). We want to construct out of $f$ a linear map $k[f] : k[X] \to k[Y]$. According to the above argument, we should first use $f$ to construct a natural transformation
$$\text{Hom}_{\text{Set}}(Y, U(V)) \to \text{Hom}_{\text{Set}}(X, U(V))$$
where $V$ is an arbitrary vector space. $\text{Hom}_{\text{Set}}(X, U(V))$ is just the set of functions from $X$ to the underlying set of $V$, or equivalently the $X$-fold product $V^X$. So the function above $V^Y \to V^X$ can be thought of as pullback of $V$-valued functions; explicitly it is just given by precomposition. Next, we use the universal property to identify this with a natural transformation
$$\text{Hom}_{\text{Vect}}(k[Y], V) \to \text{Hom}_{\text{Vect}}(k[X], V).$$
We are still talking, now, about the set of functions from $X$ resp. $Y$ to $V$, but now thought of as the set of linear functions from $k[X]$ resp. $k[Y]$ to $V$. This identification comes from taking a function $X \to V$ and then freely extending it by linearity (this is part of the universal property of the free vector space). Finally, we want to recover an actual linear map $k[X] \to k[Y]$. As usual, we do this by taking $V = k[Y]$ above, getting a map
$$\text{Hom}_{\text{Vect}}(k[Y], k[Y]) \to \text{Hom}_{\text{Vect}}(k[X], k[Y])$$
then evaluating this map on the identity to get a linear map $k[f] : k[X] \to k[Y]$. What is this map? Well, the identity map $k[Y] \to k[Y]$ corresponds via the adjunction to the map $Y \to k[Y]$ given by sending every element of $Y$ to the corresponding basis vector of $k[Y]$. Pulling back along $f : X \to Y$ gives a map $X \to k[Y]$ given by sending $x \in X$ to the basis vector $f(x) \in k[Y]$. Then we freely extend by linearity to get a linear map $k[X] \to k[Y]$. In other words, we get the map
$$\boxed{ k[f] : k[X] \ni \sum c_x x \mapsto \sum c_x f(x) \in k[Y] }.$$


text:
Q: Grabar tiempo de escritura de textos cuento con una duda, debo realizar con JavaScript o ASP. NetFramework que permita grabar el tiempo que me demoro escribiendo un texto y que posterior permita reproducir la escritura o subrayado del texto escrito en el mismo tiempo que se tardó en escribirse.
// iniciar funcion
    $(document).ready(function(){
        var tiempoescritura;
          // iniciamos el timer
          $("#escribir").keyup(function(e) {
              clearTimeout(tiempoescritura);
              if (e.keyCode == 13){ // Si se presiona enter no se ejecutará la función
              return true;
              }
          // he puesto 1s, podrías poner el valor que quieras
          tiempoescritura = setTimeout(mostrarproductos, 1000);
      });
      // borramos el timer
      $("#escribir").keydown(function() {
          clearTimeout(tiempoescritura);
      });
      function mostrarproductos(){
        console.log("He dejado de escribir!");
      }
  });

  <textarea id="escribir" name="escibir"></textarea>


text:
Q: Expressão regular para pegar uma ou mais ocorrências que precedem e sucedem determinada letra Tenho os seguintes casos...
Um primeiro texto da seguinte forma:
let text = "olá meu numero é trezentos e vinte e quatro tudo bem?"

E este texto quer recebo também pode ser como exemplo:
let text = "olá meu número é quarenta e três tudo bem?

Tentei fazer uma expressão regular que pega as ocorrências antes e depois do e para pegar as palavras que tem antes e depois do e. Fiz da seguinte forma:
console.log(text.match(/(\w+\se\s\w+)/g))

Porém a saída que tenho no primeiro caso de texto é 'trezentos e vinte', de modo que ignora o segundo grupo do e. Eu gostaria que a saída nesse caso fosse 'trezentos e vinte e quatro' e se eu passasse o segundo texto fosse 'quarenta e três' a saída mesmo, mas estou com muita dificuldade com essa Regex, poderiam me ajudar?

A:
Conforme apontado nos comentários, a solução abaixo vai trazer falsos positivos se a frase tiver quaisquer palavras que não sejam números e tenham um "e" entre elas. Então veja se é isso mesmo que você precisa...

Primeiramente, o atalho \w não pega caracteres acentuados, então sua regex não funciona nem para "quarenta e três":

let text = "olá meu número é quarenta e três tudo bem?";
console.log(text.match(/(\w+\se\s\w+)/g)); // [ 'quarenta e tr' ]

Para isso você pode usar a flag u (veja aqui para mais detalhes), ou colocar os acentos na regex. E para repetir a parte "e ....", basta colocar outro quantificador em volta dele:

let text = "olá meu número é trezentos e quarenta e três tudo bem?";

// com a flag "u" e Unicode Properties
console.log(text.match(/\p{L}+( e \p{L}+)+/ug)); // [ 'trezentos e quarenta e três' ]

// colocando os acentos na regex
console.log(text.match(/[a-záéíóúâêôãõ]+( e [a-záéíóúâêôãõ]+)+/ig)); // [ 'trezentos e quarenta e três' ]

Com a flag u, usei Unicode Properties (no caso, \p{L} pega qualquer letra definida pelo Unicode - que são os que estão nas categorias que começam com "L" desta lista). Outro detalhe é que isso também acaba sendo abrangente demais, pegando letras de outros alfabetos (japonês, árabe, etc). Se quiser restringir para o nosso alfabeto, pode trocar \p{L} por \p{Script=Latin}.
No segundo caso, coloquei as letras acentuadas na regex. Só coloquei minúsculas, mas usei a flag i, então ela também vai considerar as letras maiúsculas. Esta é uma alternativa caso o seu ambiente ainda não suporte Unicode Properties.
E na parte que tem " e etc...", coloquei outro quantificador em volta - no caso, +, pois entendi que essa parte se repete uma ou mais vezes. E troquei \s por um espaço simples (já que \s também pega quebras de linha e outros caracteres).
Além disso, tem outra diferença: o \w pega também os dígitos de 0 a 9 e o caractere _. Já as regex que fiz acima só pegam letras (o que parece fazer mais sentido no seu caso).

Sobre regex e acentos, ver também aqui e aqui.

A: Isso acontece porque a expressão regular desconsidera que sequências de e podem vir uma após a outra.
Desse modo, embora isto funcione:

/(\w+\se\s\w+)/g

foo aaa e bbb bar baz ccc e ddd qux

Isto não funcionaria:

/(\w+\se\s\w+)/g

foo aaa e bbb e ccc qux

Porque a expressão regular /(\w+\se\s\w+)/g não determina o match de duas sequências seguidas uma da outra. Isso porque  ela exige termos antes e depois do e. No caso de já ter dado match numa expressão imediatamente anterior ao próximo e, não terá nada "antes" dele, de modo que o match será impossível por não satisfazer essa condição.
Uma solução é indicar que qualquer termo após o e pode se repetir dentro de um único match. Uma opção seria assim:

/\w+(?:\se\s\w+)+/g

foo aaa e bbb bar baz ccc e ddd e eee qux

Veja no Regex101.
Embora a expressão regular acima funcione para casos em que as palavras forem formadas por caracteres alfanuméricos ASCII, letras acentuadas (como é, á, à etc) não são englobadas pelo \w.
Desse modo, você pode mudar a expressão para:

/\p{L}+(?:\se\s\p{L}+)+/gu

foo aáà e bbb bar baz ccc e ddd e eéè qux

Veja no Regex101.
De modo que, ao utilizar a flag u, pode-se utilizar \p{L}, que captura qualquer letra definida pelo padrão Unicode – o que inclui os caracteres acentuados anteriormente mencionados.
Apesar de já ser bem suportado, alguns ambientes podem não implementar expressões regulares com a flag do Unicode. Nesses casos, para alternativas ao \p{L} com a flag u, consultar a outra resposta.

Não relacionado à resposta, mas vale observar que a expressão regular original da pergunta (/(\w+\se\s\w+)/g) poderia ser substituída por /\w+\se\s\w+/g, uma vez que o grupo de captura nesse caso não faz nada.

A: Nesse caso o que você precisa é usar (\w+\se\s\w+) como um grupo e colocar um quantificador. Veja:

let text1 = "olá meu numero é trezentos e vinte e quatro tudo bem?";
let text2= "olá meu número é quarenta e três tudo bem?"

console.log(text1.match(/\w+(\se\s[a-zê]+)+/g))
console.log(text2.match(/\w+(\se\s[a-zê]+)+/g))


text:
Q: bash, if then script to parse file My requirements is to look through a F-5 config.
Something like:
 If x=virtual
 grep for virtual | pool | destination

File looks like this:
virtual vs_website_443 {
snat automap
pool pl_website_443
destination 11.11.11.11:https
ip protocol tcp
persist pr_cookie_JSESSION_AP
profiles {
   oneconnect-ebiz-blah {}
  pr_http_ebiz_x_forwarded_for {}
   serverssl {
      serverside
  }
   tcp-lan-optimized {}
   wildcard.origin.website.com {
      clientside
   }
}

A: plain bash, though can easily be converted to POSIX sh.
#!/usr/bin/env bash

in=0 # whether we are inside a 'virtual' block
     # such a block ends once we meet a line that starts with '}'

while read -r
do
    if [[ $REPLY =~ ^virtual ]]; then
        in=1
        echo "${REPLY% *}"
    elif (( in )); then
        if [[ $REPLY =~ ^pool ]]
        then echo "$REPLY"
        elif [[ $REPLY =~ ^destination ]]
        then echo "${REPLY%:*}" # or just "$REPLY" if you want the ':https' part
        elif [[ $REPLY =~ ^} ]]
        then in=0
        fi
    fi
done < file

where file is your data. You can change that to "$1"
and give the file as an argument to the script.
tested with given data, returns:
virtual vs_website_443
pool pl_website_443
destination 11.11.11.11

using plain awk
awk '$1 == "virtual" { f=1; print $1,$2; next }         \
     f == 1 { if ($1 == "pool") { print }               \
              else if ($1 == "destination") { print }   \
              else if ($0 ~ /^}/) { f=0 }               \
     }' file

with the given data output is:
 $ awk '$1 == "virtual" { f=1; print $1,$2; next } f == 1 { if ($1 == "pool") { print } else if ($1 == "destination") { print } else if ($0 ~ /^}/) { f=0 } }' file
virtual vs_website_443
pool pl_website_443
destination 11.11.11.11:https


text:
Q: How to copy multiple files according a txt file in python Please help me.
I'm trying to move files from one directory to another according to a list.
The text file(mp3text.txt)looks like this:
p008-002031903
p008-002031906
p008-002031910
Each line contains a file name without a path. The other directory(e:\p008) contains hundreds of files(p008-002031910.spx).
I had tried many times.it could run part of it but couldn't copy anything. Many Thanks!
import os
import shutil

destination = 'e:\\result'

with open('c:\\mp3text.txt', 'r',encoding= 'utf-8') as lines:
    filenames_to_copy = set(line.rstrip() for line in lines)
for root, _,filenames in os.walk('e:\\p008'):
    for filename in filenames:
        if filename in filenames_to_copy:
            shutil.copy(os.path.join(root, filename), destination)

A: <mp3text.txt xargs -I filename find ./p008 -name filename | xargs -I filepath cp -rf filepath ./result/

Without having the filesystem examples to hand it's hard to say if this will 100% work though.

A: I had figured it out finally!
The script is no problem.
The problem is the File extension from the source directory.
After I deleted the file extension.
It works!


text:
Q: How to pass a variable to urls.py I have a database 'artist' with one table : 'name', 'style'.
Users can add any names for an artist.
I would like to pass an argument to url in my template, like this :
<a href="{% url 'webgui.views.music' artist.name %}" style="margin-bottom: 3px" type="button"

But is it possible to set dynamically the URL with the argument 'artist.name' (in urls.py) ?
My urls.py actually :
url(r'^music/(\d+)/$', 'webgui.views.music'),

Maybe I need to change '\d+' by another regexp ??

A: Instead of using
url(r'^music/(\d+)/$', 'webgui.views.music'),

because d+ stands for digits, you should use
url(r'^music/?P<artist_name>[a-zA-Z0-9 \'&-]/$', 'webgui.views.music')

Don't forget to modify function
def whatever_named_it(request, artist_name):
    ...

Update: In template you should use
{% url 'webgui.views.music' artist_name=artist.name %}

because we are using named arguments.
Extra: If you are going to allow any text for artist's name, I would recommend you using slug to avoid spaces in URL. That would make it better to read, search engine friendly and avoid of insane user input. When programming web-app never trust user input ... ever.
For "slugified" name urls would be:
url(r'^music/(?P<slug>[\w-]+)/$', 'webgui.views.music')


text:
Q: Native Messaging host not able to send 1 MB data I am using the native-host in C++, when i send base64 from the native app to chrome extension(Native messaging) with size base64 < 1M, the program is still running. but when i send base64 from the native app to chrome extension (Native messaging) with size base64 >1M, the program is error "Error when communicating with the native messaging host"
my code below
int _tmain(int argc, _TCHAR* argv[])
{
    std::cout.setf( std::ios_base::unitbuf );
    unsigned int c, t=0;
    inp="";
    t=0;
    // Sum the first 4 chars from stdin (the length of the message passed).
    for (int i = 0; i <= 3; i++) {
        //t += getchar();
        t += std::pow(256.0f, i) * getchar();
    }
    // Loop getchar to pull in the message until we reach the total
    //  length provided.
    for (int i=0; i < t; i++) {
        c = getchar();
        inp += c;
    }

    unsigned int len =  inp.length();
    // We need to send the 4 btyes of length information
    std::cout << char(((len>>0) & 0xFF))
              << char(((len>>8) & 0xFF))
              << char(((len>>16) & 0xFF))
              << char(((len>>24) & 0xFF));
    // Now we can output our message
    std::cout << inp;
    return 0;
}

A: Native messaging hosts cannot send a message with more than 1024*1024 bytes. From
https://cs.chromium.org/file%3Anative_message_process_host.cc%20kMaximumMessageSize:
// Maximum message size in bytes for messages received from Native Messaging
// hosts. Message size is limited mainly to prevent Chrome from crashing when
// native application misbehaves (e.g. starts writing garbage to the pipe).
const size_t kMaximumMessageSize = 1024 * 1024;

To work around this problem, you have to split the message sent from the native messaging host to your extension/app in chunks of less than 1MB.
In your native messaging host, you could create a loop that repeatedly outputs the 32-bit message length (max 1MB) followed by a chunk of the message.
In your app/extension, use chrome.runtime.connectNative instead of chrome.runtime.sendNativeMessage to open a port that lasts longer than one message (if you use sendNativeMessage, the port will be closed after receiving one reply, which causes the native messaging host to terminate).


text:
Q: How can i reset the path of file uploaded in angular js I'm creating one function for uploading details with photos of users,
so for that i have use angularjs,
Their are multiple users i have to update from that page.
in that first user image get added successfully, but when i'm going to add next user image or update other data the path and name of image is by default shown up for next user.

like the above image
if i don't want to add image but do some other updates related to user and save them
that time that image is also get send as it get auto selected,
could you please give me solution for this,
i'm pretty new to UI part so i'm able to figur it out what is going wrong
    <form id="user-image-form" class="col-sm-11 col-md-11 col-lg-11">

            Select profile image

                <input type="file" class="btn btn-default" id="imageFile" ng-model="imageFile"  name="imageFile" onchange="angular.element(this).scope().uploadAndReloadImage()" style="width:100%">

    </form>

Angular part
 $scope.uploadAndReloadImage = finction(){
         var FD  = new FormData();
         FD.append('image',document.getElementById("user-image-form"));
         d.image_file =  $scope.user_data.user_id;
        d.image_file_data = FD;
        var f = document.getElementById('imageFile').files[0];
        if(f && $scope.user_data.user_id && $scope.user_data.user_id != "-1" && $scope.user_data.user_id != "")  {
        //ajax call
        }

       };


text:
Q: Python 3.11 installation: some modules are missing I'll try to be as clear and specific as possible because I've seen so many people with the same problem, but none of the answers they had worked for me.
The problem in question is: missing modules when trying to import other modules, that (by far as I understand) are installed by default in Python 3.11. eg: missing _sqlite3 when importing sqlite3.
Python 3.11.0 (main, Jan 12 2023, 03:19:52) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user_name/opt/Python-3.11.0/lib/python3.11/sqlite3/__init__.py",
  line 57, in <module> from sqlite3.dbapi2 import *
  File "/home/user_name/opt/Python-3.11.0/lib/python3.11/sqlite3/dbapi2.py",
  line 27, in <module> from _sqlite3 import *
ModuleNotFoundError: No module named '_sqlite3'

Context
I'm currently working on a Dreamhost VPS, running on Ubuntu 20.04.5. Since it's a Dreamhost VPS keep in mind I can't uso sudo.
I've Python 3.8 installed globally, but I'm trying to set Python 3.11 with venv. The steps to install Python 3.11 were, as indicated by 'Installing a custom version of Python 3 by Dreamhost':

*

*cd /home/user_name/opt

*wget https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tgz

*tar zxvf Python-3.11.0.tgz

*cd Python-3.11.0

*./configure --prefix=$HOME/opt/Python-3.11.0

*make

*make install

When running the make command I saw the following message:
The necessary bits to build these optional modules were not found:
_bz2                  _curses               _curses_panel
_lzma                 _tkinter              _uuid
readline
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

The following modules found by detect_modules() in setup.py have not
been built, they are *disabled* by configure:
_sqlite3

This is my detect_modules() in setup.py:
def detect_modules(self):
        # remove dummy extension
        self.extensions = []

        # Some C extensions are built by entries in Modules/Setup.bootstrap.
        # These are extensions are required to bootstrap the interpreter or
        # build process.
        self.detect_simple_extensions()
        self.detect_test_extensions()
        self.detect_readline_curses()
        self.detect_crypt()
        self.detect_openssl_hashlib()
        self.detect_hash_builtins()
        self.detect_dbm_gdbm()
        self.detect_sqlite()
        self.detect_platform_specific_exts()
        self.detect_nis()
        self.detect_compress_exts()
        self.detect_expat_elementtree()
        self.detect_multibytecodecs()
        self.detect_decimal()
        self.detect_ctypes()
        self.detect_multiprocessing()
        self.detect_tkinter()
        self.detect_uuid()

        # Uncomment the next line if you want to play with xxmodule.c
#        self.add(Extension('xx', ['xxmodule.c']))

        self.addext(Extension('xxlimited', ['xxlimited.c']))
        self.addext(Extension('xxlimited_35', ['xxlimited_35.c']))

So after running the commands I just mentioned, I proceeded to setup the virtualenv to test Python 3.11:

*

*cd /home/user_name/opt

*/home/user_name/opt/Python-3.11.0/bin/python3 -m venv venv

*source venv/bin/activate

And then I got the ModuleNotFoundError I mentioned at the start of the question.
Things I tried/saw:
When I checked my Python 3.11 directory, I saw that in /home/user_name/opt/Python-3.11.0/lib/python3.11/lib-dynload the cpython files for the modules I don't have are just not there, e.g: /home/user_name/opt/Python-3.11.0/lib/python3.11/lib-dynload/_sqlite3.cpython-311-x86_64-linux-gnu.so* where as in my Python 3.8, they're indeed there: /usr/lib/python3.8/lib-dynload/_sqlite3.cpython-38-x86_64-linux-gnu.so
I tried copying the cpython file from my 3.8 to my 3.11 and renaming it:

*

*cp /usr/lib/python3.8/lib-dynload/_sqlite3.cpython-38-x86_64-linux-gnu.so /home/user_name/opt/Python-3.11.0/lib/python3.11/lib-dynload

*mv /home/user_name/opt/Python-3.11.0/lib/python3.11/lib-dynload/_sqlite3.cpython-38-x86_64-linux-gnu.so /home/user_name/opt/Python-3.11.0/lib/python3.11/lib-dynload/_sqlite3.cpython-311-x86_64-linux-gnu.so

Then when I ran Python 3.11 I got the following error:
Python 3.11.0 (main, Jan 12 2023, 04:33:33) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import _sqlite3 # this works just fine
>>> import sqlite3 # throws error
356306 segmentation fault (core dumped)  python

Tried recompiling Python and running ./configure --prefix=$HOME/opt/Python-3.11.0 --enable-loadable-sqlite-extensions and didn't work.
Hope I was clear enough and thanks in advance.


text:
Q: Prevent absolutely-positioned elements from overlapping with text I have a unique situation here.
Essentially, I have an absolutely positioned block of text, which must be absolutely positioned due to design limitations.
I also have the rest of my text, which is normally positioned. However, I need to prevent my normal text from overlapping with my original text.
Is this possible simply with HTML and inline CSS? I do not have access to JavaScript or external/head-related CSS; only inline styles are available. I have created a simplified version of my CSS with this jsFiddle.

A: Is a solution to create another div (div2) that overlaps the absolutely positioned div (div1), but is itself invisible? Then the rest of the text would avoid overlapping div2...
Sketched this out here: http://jsfiddle.net/VKYwD/8/
Not entirely clear on what your constraints are though.


text:
Q: Reading lines from an asset file So I thought I had everything right, but apparently I do not. Below is the buggy function and it does not read the line right. The file "save.txt" is located in the assets folder with only the word "new" in it at the very top. This loadGame function will print "load" to logcat which is not correct because the word new is the first line in the file. Also sending br.readLine() to the log will crash the application so it definitely is not reading the right thing.
private boolean loadGame() {
        AssetManager am = getAssets();
        InputStream is = null;
        BufferedReader br = null;
        try {
            is = am.open("save.txt");
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            if(br.readLine() != "new") {
                //More parsing will go here
                Log.d("test", "load");
                return(true);
            } else {
                Log.d("test", "new");
                return(false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return(false);
    }

A: @Want2bExpert ans is correct but why your code is not working or what is problem in your code for this understood below concept :
== is used compare Object reference.
equals/equalsIgnoreCase are used to compare Object value.
So when you compare two String try to use second option instead of first.
Examples :
String s1 = "string1";
String s2 = "string2";
String s3 = "string1";
String s4 = s2;

if(s1 == s2) -> false
if(s1.equals(s2)) -> false
if(s1 ==  s3) -> false
if(s1.equals(s3)) - > true
if(s2 == s3) -> false
if(s2 == s4) -> true
if(s2.equals(s4)) - > true

A: Use equals in place of "=" as below  !br.readLine().equals("new")


text:
Q: Example of a Type that would need custom exensibility in Postgres In postgres there are two different flavors of a custom type:

*

*CREATE TYPE, which is more or less just a named STRUCT in SQL, for example:
CREATE TYPE bug_status AS ENUM ('new', 'open', 'closed');

CREATE TABLE bug (
  id serial,
  description text,
  status bug_status

);```

*A lower-level User-Defined Type, defined in C with full custumizability.
What would be an example of a type that would need to be implemented at a lower-level that just having a named struct? The only examples I can find in the documentation are pretty trivial ("Box" or "Complex Number") and so would never actually require using a lower-level type, but I imagine there are other types (Geo?) that would need 100% customizability.
What would be a few examples of a type that could not be supported with a named struct?

A: Many things can be represented as a composite type, but then input and output of your type relies on the type input and output functions of the data types used, which may not be what you want. You might want your complex data type to be displayed as (-2 + 5i).
Also, and perhaps more importantly, the performance of data type that was implemented in C will be superior. A complex data type whose operators +, -, * and / are defined as PL/pgSQL functions will not be useful for number crunching.
For other examples, look at the contrib modules described in appendix F of the documentation. I doubt that you can reasonably implement something like ltree as a composite type.


text:
Q: multiple deletion in servlet protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath());

 String[] id = request.getParameterValues("hiddenID");
 //int id=Integer.parseInt(request.getParameter("hiddenID"));

 foodDB db = new foodDB();
 Boolean success = db.deletefood(id);

 //Boolean success=(Boolean)db.deletefood("%" + id + "%");
 //boolean success=(Boolean)db.deletefood( F );

 request.setAttribute("success", success);

 RequestDispatcher rd = request.getRequestDispatcher("delete.jsp");
 rd.forward(request, response);

}

this is my servlet part. Multiple deletion in database by using checkboxes selected. But it doesnt work.

A: This statement is wrong
 pstmt.setString(1, "%" + id + "%");

here id is a string array. So you are passing string array object to setString(). But not the array value.
Use for-each loop to get each id from the array id.
PreparedStatement pstmt=null;

for(String i:id)
{
     pstmt=conn.prepareStatement(sqlStr);
     pstmt.setString(1, "%" + i + "%");
     //now execute it

}


text:
Q: Click-Once installation from Website not working I have created a little winform project in Visual Studio 2019 and I have published it to a website.
I do get the index.html file where there is a download link to the setup.exe file.
But when I run the setup file I get an error, its like it cannot download the installation files from the website.
I did this a few years ago, but cannot remember how I got it to work.
Can any one help my, what do I need to get it to work?
Is it something on the webserver or something else?


text:
Q: Xcode project that was generated by CMake is not show header file I build my C++ project with CMake.
I want use Xcode as Editor
so, I run this command.
cmake . -GXcode

BTW, My C++ Project header and source file is located in different folder.
my project directory tree:
project_root
└CMakeLists.txt
└src
   └CMakeLists.txt
   └main.cpp
└include
   └xxx1.hpp
   └inner
      └in_xxx1.hpp

so I set src/CMakeLists.txt like this:
include_directories (
   ${CMAKE_SOURCE_DIR}/include
)
add_executable( "runrun" main.cpp )

In Xcode, only main.cpp file is shown.

I want see header file also in Xcode.
What should I do?

A: For CMake to also put header files into your XCode project, you simply need to add the corresponding header files to your sources.
In your case, you should also add xxx1.hpp and inner/in_xxx1.hpp as parameters of add_executables. So far, I have not seen any disadvantage of that.


text:
Q: php workaround for query limit Google Maps Directions v3 Documentation says that waypoints limit is 8 points. But I have to calculate a route with more than 8 waypoints. How to do that?
I figured out that i can do multiple requests with different waypoints till I have all the directions.
Now my question : How to know which waypoint belongs to which request? Else the driver who gets the directions will drive around in circles :)
Can anybody help me with this or point me in the right direction? Thanks in advance!
Edit: I saw the other post on this problem, but that one was allready answered. It didn't really help me because I allready figured out that answer.

A: There are two problems with your proposed system:

*

*Should your site be successful, you will stop getting answers from the directions service due to too many requests from the same ip address

*The contracts offered by Google allow for more than 8 way points - you are therefore opening yourself to potential problems with Google !

Having said that, from what I understand, you have a list of destinations which make up your global itinerary. In addition I feel that this itinerary is not to be completed in one day/trip.
Why not simply request directions for each step and store the result ?

A: You might want to check out the following:
http://lemonharpy.wordpress.com/2011/12/15/working-around-8-waypoint-limit-in-google-maps-directions-api/


text:
Q: $\varphi(A(x))$ continuous $\Rightarrow$ $A$ continuous? Let's define linear operator:
$$A \colon X \rightarrow Y$$
between normed spaces $X$ and $Y$. Also consider linear, continuous operator:
$$B\colon Y' \rightarrow X'$$
such that $B(\varphi(x)) = \varphi(A(x))$ for $\varphi \in Y', \; x \in X$.
I want to prove that if $B$ is well defined then $A$ is continuous and $\|A\| = \|B\|$.
My work so far
Continuity of $B$:
$$\|B(\varphi(x))\| \le \|B\| \cdot \|\varphi(x)\| \le \|B\| \cdot \|\varphi\| \cdot \|x\|$$
Continuity of $\varphi$:
$$\|B(\varphi(x))\| = \|\varphi(A(x))\| \le \|\varphi\|\cdot \|A(x)\|$$
And here out of these two inequalities I tried somehow to obtain that $\|A(x)\| \le \|B\| \cdot\|x\|$, and $\|B\|$ is the smallest constant $M \ge 0$ for such $\|A(x)\| \le M \|x\|$.
Also my other idea was to use Hahn-Banach theorem, becuase in thesis there is continuity and equality of norms, however I wasn't able to use it. Could you please give me a hint how to end this proof?

A: As you say, you have
$$
\|\varphi(Ax)\|=\|(B\varphi)x\|\leq\|B\varphi\|\,\|x\|\leq\|B\|\,\|\varphi\|\,\|x\|.
$$
Then, because of Hahn-Banach,
$$
\|Ax\|=\sup\{\|\varphi(Ax)\|:\ \varphi\in Y',\ \|\varphi\|=1\},
$$
and so $\|Ax\|\leq\|B\|\,\|x\|$. As this works for any $x$, we get that $\|A\|\leq\|B\|$.
For any $\varphi\in Y'$,
$$
\|B\varphi\|=\sup\{|(B\varphi)x|:\ \|x\|=1\}.
$$
Using that $$|(B\varphi)x|=|\varphi(Ax)|\leq \|\varphi\|\,\|Ax\|\leq\|\varphi\|\,\|A\|\,\|x\|,$$
we get that $\|B\varphi\|\leq\|A\|\,\|\varphi\|$. As this can be done for any $\varphi\in Y'$, this shows that $\|B\|\leq\|A\|$.


text:
Q: Probability of defective items, and the probability the first chosen items come from Group A I'm still trying to work out how to answer this question.
If Group $A$ has $\frac{1}{100}$ items defective, and Group $B$ has $\frac{1}{200}$ items defective. Overall probability of item being defective is therefore $\frac{3}{200} = 0.015$.
If the first item chosen works (is not defective) what is the probability it came from group $A$?
My thinking on this was just $1 - \frac{1}{100}$. Is that correct?
Secondly, what is the probability the second item works given the first one also works. Should I be applying conditional probability here?

A: Assuming both groups are equally large, the a priori probabilities are $P(A) = P(B) = \frac{1}{2}$ .Given is (the event $d$ is for defective) $P(d|A) = \frac{1}{100}$ and so $P(\lnot d| A) = \frac{99}{100}$.
So standard Bayesian rules tell us:
$$P(A| \lnot d) = \frac{P(\lnot d|A)P(A)}{P(\lnot d|A)P(A) + P(\lnot d|B)P(B)}$$
which equals $\frac{2\cdot 99}{2\cdot 99+199}$ after simplification (a little less than a half).


text:
Q: Definite integral of function inverse to a polynomial $f(x) = x+ x^3$
$g(y) = f^{-1}(x)$
$\int_2^{10} g(y) dy = $ ?
$\int_2^{10} g(y) dy =$ [$dy = df(x), dy = 1+3x^2$] = $\int_1^2 (1+3x^2)dx$ = [$x+x^3$] =$ 10 - 2 =8$
Am I right or I did a mistake? My friend told me that $dy = 1+(x^3)/3$
Thanks for helping!

A: Let $y=f(x)$ then $dy=f'(x)dx$ so
$$\int_2^{10}g(y)dy=\int_{g(2)}^{g(10)} xf'(x)dx=\int_1^{2}x(1+3x^2)dx=\left[\frac {x^2}2+\frac{3x^4}4\right]_1^2=\frac{51}4$$

A: In the rectangle $[0,2]\times[0,10]$ of the $(x,y)$-plane draw the curve
$$y=f(x)\quad(1\leq x\leq2),\qquad{\rm resp.}\qquad x=g(y)\quad(2\leq y\leq 10)\ .$$
By inspection of the figure one then sees that
$$\int_2^{10} g(y)\>dy=2\cdot10-1\cdot 2-\int_1^2 f(x)\>dx=18-\left.\left({x^2\over2}+{x^4\over4}\right)\right|_1^2={51\over4}\ .$$


text:
Q: Null Pointer Exception - Custom Camera with Flash Light In my program i want to allow user to capture multiple Images back to back, but once i do tap on Capture button getting Null Pointer Exception (NPE). I have created a Custom Camera.
If i will remove the flash light code from my existing code, then it's working fine for me (yeah then i am able to capture multiple images back to back without facing any NPE), but whenever i use Flash Light code facing NPE

*

*At line number : 324
mediaFile = new File(mediaStorageDir.getPath() + File.separator
        + "IMG_" + timeStamp + ".jpg");

*At line number : 301
    pictureFile = getOutputMediaFile();

*Java Code
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

    mCamera = getCameraInstance();

    mCameraPreview = new PreviewSurface(this, mCamera);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mCameraPreview);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String value = extras.getString("folder_name");
        Log.d(CameraLauncherActivity.LOG_TAG, "folder_name :: " + value);
    }

    Button captureButton = (Button) findViewById(R.id.btnCapture);
    Log.d(CameraLauncherActivity.LOG_TAG, "captureButton :: " + captureButton);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCamera.takePicture(null, null, mPicture);
            Log.d(CameraLauncherActivity.LOG_TAG, "mCamera.takePicture :: " + mCamera);
        }
    });

    Button viewButton = (Button) findViewById(R.id.btnView);
    Log.d(CameraLauncherActivity.LOG_TAG, "SingleAngelActivityButton :: " + viewButton);
    viewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intentNewEvent = new Intent(CameraLauncherActivity.this, UploadActivity.class);
            String event_id = customFolder;
            intentNewEvent.putExtra("event_id", event_id);
            startActivity(intentNewEvent);
        }
    });

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(CameraLauncherActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

   hasFlash = getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

   // Check if Internet present
    if (!hasFlash) {
        // device doesn't support flash
        alert.showAlertDialog(CameraLauncherActivity.this, "Sorry",
                "your Device doesn't support Flash Light !", false);
        // stop executing code by return
        return;
    }

     // displaying button image
   toggleButtonImage();

   // flash switch button
    btnSwitch = (ImageButton) findViewById(R.id.btnFlash);

    btnSwitch.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (isFlashOn) {
                // turn off flash
                turnOffFlash();
            } else {
                // turn on flash
                turnOnFlash();
            }
        }
    });

// Get event id, angel id
Intent i = getIntent();
event_id = i.getStringExtra("event_id");
angel_id = i.getStringExtra("angel_id");

// calling background thread
new LoadSingleTrack().execute();
}

 /**
 * Background Async Task to get single angel information
 * */
class LoadSingleTrack extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(CameraLauncherActivity.this);
        pDialog.setMessage("Initializing Camera...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting angel json and parsing
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // post event id, angel id as GET parameters
        params.add(new BasicNameValuePair("event", event_id));
        params.add(new BasicNameValuePair("angel", angel_id));

        // getting JSON string from URL
        String json = jsonParser.makeHttpRequest(URL_angel, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("Single Track JSON: ", json);

        try {
            JSONObject jObj = new JSONObject(json);
            if(jObj != null){
                angel_name = jObj.getString(TAG_ANGEL);
                event_name = jObj.getString(TAG_EVENT);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting angel information
        pDialog.dismiss();

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {

                TextView txt_angel_name = (TextView) findViewById(R.id.angel_title);
                String timeStamp = new SimpleDateFormat("dd-MM-yyyy").format(new Date());

                txt_angel_name.setText(event_name + " Event_"+ angel_name + "-" + timeStamp);
                customFolder = txt_angel_name.getText().toString();

                // Change Activity Title with angel title
                setTitle(angel_name);

                // folder name
                mediaStorageDir = new File(
                        Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                "/CaptureImages/"+ customFolder + "/");

                if (!mediaStorageDir.exists()) {
                    if (!mediaStorageDir.mkdirs()) {
                        Log.d("App", "failed to create directory");
                    }
                }
            }
        });
    }
}

}
Logcat:-
12-04 23:23:04.610: E/AndroidRuntime(798): FATAL EXCEPTION: main
12-04 23:23:04.610: E/AndroidRuntime(798): java.lang.NullPointerException
12-04 23:23:04.610: E/AndroidRuntime(798):  at com.example.camera.CameraLauncherActivity.getOutputMediaFile(CameraLauncherActivity.java:324)
12-04 23:23:04.610: E/AndroidRuntime(798):  at com.example.camera.CameraLauncherActivity$1.onPictureTaken(CameraLauncherActivity.java:301)
12-04 23:23:04.610: E/AndroidRuntime(798):  at android.hardware.Camera$EventHandler.handleMessage(Camera.java:773)
12-04 23:23:04.610: E/AndroidRuntime(798):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-04 23:23:04.610: E/AndroidRuntime(798):  at android.os.Looper.loop(Looper.java:137)
12-04 23:23:04.610: E/AndroidRuntime(798):  at android.app.ActivityThread.main(ActivityThread.java:5103)
12-04 23:23:04.610: E/AndroidRuntime(798):  at java.lang.reflect.Method.invokeNative(Native Method)
12-04 23:23:04.610: E/AndroidRuntime(798):  at java.lang.reflect.Method.invoke(Method.java:525)
12-04 23:23:04.610: E/AndroidRuntime(798):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-04 23:23:04.610: E/AndroidRuntime(798):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-04 23:23:04.610: E/AndroidRuntime(798):  at dalvik.system.NativeStart.main(Native Method)
12-04 23:23:07.570: I/Process(798): Sending signal. PID: 798 SIG: 9

A: I can't figure out the exact sequence of execution for various parts of your code, but the only thing on that line that can generate a NPE is that mediaStorageDir is null. Since you initialize mediaStorageDir after an instance of LoadSingleTrack asynchronously executes, I can only assume that it is executing after line 324 executes. Resolve this out-of-order sequencing of code execution and the problem should disappear.
Just as a side note: there is no point in calling runOnUiThread from onPostExecute of an AsyncTask; you are already on the UI thread when onPostExecute is called.


text:
Q: Some ways to debug code I have a BuddyPress installation with many custom code.
I had everything ready for production until I moved my database to shared hosting.
The problem is that in strange ocasions, all the activities in wp_bp_activity gets deleted.
I'm not saying that this problem ocured because I moved my database, but I cant reproduce this bug with my original installation (but had the same problem when I compied hosting database to new installation on my local machine)
my details:
1) I don't beliave this DELETE is triggered with buddypress native code because everything staies as is in wp_bp_activity_meta.
2) I can't reproduce this bug and I can't understand when this happens. Also this does not happen often. maybe once or twice a day (or even once in two days). this is why it drives me  crazy )
3) The most interesting, it deletes EVERYTHING except "like". I'm using bp-like-unlike compontent. It deletes everything: avatar_change, comments, activity, my own components but not bp-like which is just a copy of original (liked).

UPDATE: As @S_HA_DUM suggested I turned SQL debbuging on and found (in 500mb data) this request (no error from php side)
DELETE FROM wp_bp_activity WHERE item_id = 0
the only thing I found that queries to wp_bp_activitiy is delete function (someone named it this simple :D) in buddypress plugin.
but still can't find where this function is triggered
I want some suggestions how to debug this error.
Any help is welcomed

A: Did you enable for debug in wp-config.php, you know, that is great for developing your theme
define('WP_DEBUG', false);

A: I finally found an error and I will write it here
The problem was in my code: I was deleting activites with item_id being activity ID deleted. In other words I have a hook which is triggered after activity gets deleted where I delete "BuddyPress LIKE" activity (X Liked a Post).
But there is a cron job triggered by BBPress which deletes auto_draft posts (if any). and since BBPress can have an activity in BuddyPress, it also triggeres "DELETE_ACTIVITY", but in this case $activity_id is zero (I don't know, maybe because it does not exist and I'm hooking to early.
and that's where I get DELETE FROM wp_bp_activity WHERE item_id = 0
function clean_activity_dollars($activity){
    global $wpdb;
    $activity_table = $wpdb->prefix . 'bp_activity';
    $wpdb->delete($activity_table, array( 'item_id' => $activity['id'] ), array('%d'));
}
add_action("bp_before_activity_delete","clean_activity_dollars",10,1);

which I changed to this
$wpdb->delete($activity_table, array( 'item_id' => $activity['id'], 'type' => 'activity_liked' ), array('%d', '%s'));

so even if item_id is zero, it will check for type.


text:
Q: how to set AWS variables by using environment variables I folllow this tutorial http://pjambet.github.com/blog/direct-upload-to-s3/. Pretty much stuck in the setting the AWS variable. The tut says I have to set the variables as below
export S3_BUCKET=<YOUR BUCKET>
export AWS_ACCESS_KEY_ID=<YOUR KEY>
export AWS_SECRET_KEY_ID=<YOUR SECRET KEY>

But it doesn't mention where to set those of variable.
Could anyone point me out ? Thanks

A: Just type it in the command line. Export command.


text:
Q: How to draw a line within a view along the frame? I'm trying to create a dialog fragment whose frame has a line that gets smaller (like a snake) at a certain time, of course in animation.
It's like in Waze application, only that the line is complete and small at first.
Pay attention to the increasing line size of the "go now" button in the Gif

*

*how achieve line that gets smaller?

*how achieve the Waze animation, increasing line size?

A: I found the solution and built a library, you can see the tutorial how to use it here
Simple implementation with Gradle dependency

implementation 'com.bagi: drawerpath: 1.4'


text:
Q: Does FFMpeg support encoding a group of raw frames with out-of-band timestamps into a video Suppose I have a group of raw frames captured from a camera and a csv file listing the exact time the frame are captured. Notice the frames are not captured at a constant rate.
Is that possible to encode such raw frames into a video with FFMpeg and somehow make FFMpeg to attach timestamp to each frame based on the time information stored in the csv?
I found a 2012 post at https://ffmpeg.org/pipermail/ffmpeg-user/2012-December/011907.html, which seems to suggest the answer then was negative. Not sure whether anything has changed since.


text:
Q: nivo slider & lightbox video challenge I am using to different plug-ins: Nivo slider & a Lightbox.
I want to be able to click an image in the slider to trigger (only jQuery) an action to show my video in a lightbox.
My current solution is to link to another page that has:
<script type="text/javascript">
$(document).ready(function(){
$('#videoanchor').trigger('click');
}); </script>

Which works fine but takes them away from the original page and every time they visit the video page (which is where the link takes them) this video pops up.
I have tried:
<script type="text/javascript">
$('#sliderimg').click(function(){
$('#videoanchor').trigger('click');
});</script>

Didn't work.
What am I missing?

A: if it is youtube video and address contains /v/etc.... change v into "watch"


text:
Q: char WM_KEYDOWN showing up as number and no capitol letters when hard coded I'm writing an app that can send keystrokes to another application.  I have some of it sort of working when I hard code the text that I want to send.  However when I use argv[] to get the text from the arguments list it no longer sends the text and instead numbers or nothing shows up.  I think the problem lies in taking the text from char* and putting it into the std::string before parsing that and sending each char to the function that sends the keystroke to the awaiting application.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <psapi.h>
#include <cstdlib>
#include <string>

using namespace std;

HWND SendIt (DWORD dwProcessID, const char key)
{
    HWND hwnd = NULL;
    do {
        hwnd = FindWindowEx(NULL, hwnd, NULL, NULL);
        DWORD dwPID = 0;
        GetWindowThreadProcessId(hwnd, &dwPID);
        if (dwPID == dwProcessID) {
            PostMessage(hwnd, WM_KEYDOWN,key, 1);
        }
    } while (hwnd != 0);
    return hwnd;
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        cout << "Please provide a PID# and a String of Charaters to pass to the PID#.\n";
        cout << "Examples:\n";
        cout << "RegTSM.exe 16855 WP3C94\n";
        cout << "RegTSM.exe 16855 \"type this into the PID Handle\" \n";
        exit(1);
    }
    else {
        DWORD PID;
        std::string sPID;
        std::string text;
        sPID = argv[1];
        PID = atof(sPID.c_str());
        text = argv[2];
        text += "\r";
        //std::string text = "WN403A\r";

        for (char & key : text) {
            SendIt(PID, key);
        }
    }
    return 0;
}

If I run the code above and provide the PID of a cmd.exe process and some text like the letter 'a' it will print 1 in the cmd.exe process I targeted.
If I use the commented section std::string text = "WN403A\r"; instead as the input to the for (char & key : text) then it will work fine (except for not producing capitol letters, which I need) and type out wn403a.

*

*command line arguments not producing the actual characters provided.

*even when string is hard coded the output to the other cmd.exe window is not in capital letters.

Thanks in advance!!

A: As Raymond Chen blogged:
You can't simulate keyboard input with PostMessage.
Even if you could do it reliably, your code is NOT:

*

*accounting for the possibility of the target process having multiple windows.  Or even that it might switch between windows while you are in the middle of sending keystrokes.  You are sending your key messages to random windows within the process, and even then only to top-level windows, not to any particular child control windows that have keyboard input at the time of the send.

*sending any WM_KEYUP messages, only WM_KEYDOWN messages.

*sending virtual key codes.  WM_KEYDOWN/UP do not operate on characters, they operate on key codes and scan codes instead.  WM_CHAR, on the other hand, operates on characters.

*taking lowercase vs uppercase into account, which requires simulating the Shift key being held down while sending an uppercase character.
You really should rethink your approach.  Don't use PostMessage() at all, you should be using SendInput() instead.  However, it doesn't allow you to target a specific window, so you would have to use WM_SETTEXT or even UI Automation to send your text directly to the target window.
That being said, if you insist on using PostMessage(), then try something more like this instead:
#include "stdafx.h"
#include <windows.h>
#include <psapi.h>

#include <iostream>
#include <string>
#include <cstdio>
#include <cctype>

struct MyEnumInfo
{
    DWORD dwProcessID;
    HWND hwndFocus;
};

BOOL CALLBACK FindFocusedWindow(HWND hwnd, LPARAM lParam)
{
    MyEnumInfo *mei = (MyEnumInfo*)lParam;

    DWORD dwPID = 0;
    DWORD dwThreadID = GetWindowThreadProcessId(hwnd, &dwPID);
    if (dwPID == mei->dwProcessID)
    {
        GUITHREADINFO gti = {0};
        gti.cbSize = sizeof(gti);
        if (GetGUIThreadInfo(dwThreadID, &gti))
        {
            mei->hwndFocus = gti.hwndFocus;
            if (mei->hwndFocus)
                return FALSE;
        }
    }

    return TRUE;
}

HWND SendIt(DWORD dwProcessID, const std::string &text)
{
    if (text.empty())
        return NULL;

    MyEnumInfo mei;
    mei.dwProcessID = dwProcessID;
    mei.hwndFocus = NULL;

    EnumWindows(&FindFocusedWindow, (LPARAM)&mei);

    if (!mei.hwndFocus)
        return NULL;

    LPARAM lParamShift = MapVirtualKey(VK_SHIFT, MAPVK_VK_TO_VSC) << 16;
    LPARAM lParamCtrl = MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC) << 16;
    LPARAM lParamAlt = MapVirtualKey(VK_MENU, MAPVK_VK_TO_VSC) << 16;

    for (const char& key : text)
    {
        SHORT code = VkKeyScanA(key);
        BYTE vk = LOBYTE(code);
        BYTE shift = HIBYTE(code);

        if ((vk != -1) && (shift != -1))
        {
            if (shift & 1) PostMessage(mei.hwndFocus, WM_KEYDOWN, VK_SHIFT, lParamShift);
            if (shift & 2) PostMessage(mei.hwndFocus, WM_KEYDOWN, VK_CONTROL, lParamCtrl);
            if (shift & 4) PostMessage(mei.hwndFocus, WM_KEYDOWN, VK_MENU, lParamAlt);

            LPARAM lParamKey = MapVirtualKey(vk, MAPVK_VK_TO_VSC) << 16;
            PostMessage(mei.hwndFocus, WM_KEYDOWN, vk, lParamKey);
            PostMessage(mei.hwndFocus, WM_KEYUP, vk, lParamKey | 0xC0000001);

            if (shift & 1) PostMessage(mei.hwndFocus, WM_KEYUP, VK_SHIFT, lParamShift | 0xC0000001);
            if (shift & 2) PostMessage(mei.hwndFocus, WM_KEYUP, VK_CONTROL, lParamCtrl | 0xC0000001);
            if (shift & 4) PostMessage(mei.hwndFocus, WM_KEYUP, VK_MENU, lParamAlt | 0xC0000001);
        }
    }

    return mei.hwndFocus;
}

void usage()
{
    std::cout << "Please provide a PID# and a String of Characters to send to the PID#.\n";
    std::cout << "Examples:\n";
    std::cout << "RegTSM.exe 16855 WP3C94\n";
    std::cout << "RegTSM.exe 16855 \"type this into the PID Handle\"\n";
    exit(1);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        usage();
        return 1;
    }

    DWORD PID;
    if (std::sscanf(argv[1], "%u", &PID) != 0) {
        usage();
        return 1;
    }

    std::string text = std::string(argv[2]) + "\r";
    //std::string text = "WN403A\r";

    SendIt(PID, text);

    return 0;
}

A: It's been a while since I visited this project but I wanted to post the code that ended up working.  Thanks to all for comments and education!!
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <psapi.h>
#include <cstdlib>
#include <string>

using namespace std;

HWND SendIt (DWORD dwProcessID, const char key)
{
    HWND hwnd = NULL;
    do {
        hwnd = FindWindowEx(NULL, hwnd, NULL, NULL);
        DWORD dwPID = 0;
        DWORD threadId = GetWindowThreadProcessId(hwnd, &dwPID);
        if (dwPID == dwProcessID) {
            PostMessage(hwnd, WM_CHAR, (WPARAM)key, 0);
        }
    } while (hwnd != 0);
    return hwnd;

}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        cout << "Please provide a PID# and a String of Charaters to pass to the PID#.\n";
        cout << "Examples:\n";
        cout << "RegTSM.exe 16855 WP3C94\n";
        cout << "RegTSM.exe 16855 \"type this into the PID Handle\" \n";
        exit(1);
    }
    else {
        DWORD PID;
        std::string sPID;
        std::string text;
        sPID = argv[1];
        PID = atof(sPID.c_str());
        text = argv[2];
        text += "\r";

        for (char & key : text) {
            SendIt(PID, key);
        }
    }
    return 0;
}


text:
Q: Removing prime numbers from a linked list I have a linked list that I am trying to generate a random list and then remove all of its prime numbers. This is what I have so far. I know how to find the primes I'm just not sure where to go on removing them from the list. This is my updated list, it only removes one number instead of deleting all primes.
import random
from linkListDef import *

def is_prime(llist):
    number = llist[0]

    half = int(number / 2)
    status = True
    for count in range(2, half + 1):
        if number % count == 0:
            status = False
    return status

def main():
    llist = LinkedList()
    counter = 0

    while counter != 20:
        numbers = random.randrange(1, 101)
        counter += 1
        llist.push(numbers)
    print ("Created Linked List: ")
    llist.printList()
    llist.deleteNode(numbers)
    print ("Linked List after Deletion of primes:")
    llist.printList()

if __name__ == '__main__':
    main()

A: You can do a for loop on the now generated linked list, check the number using your isPrime method and running .remove(item) on the list, where item is the current iteration over the list


text:
Q: Jasper Reports OutOfMemoryError on export I have written a web app for managing and running Jasper reports.  Lately I've been working with some reports that generate extremely large (1500+ page) outputs, and attempting to resolve the resultant memory issues.  I have discovered the JRFileVirtualizer, which has allowed me to run the report successfully with a very limited memory footprint.  However, one of the features of my application is that it stores output files from previously run reports, and allows them to be exported to various formats (PDF, CSV, etc.).  Therefore, I find myself in the situation of having a 500+MB .jrprint file and wanting to export it to, for example, CSV on demand.  Here is some simplified example code:
JRCsvExporter exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME, jrprintPath);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
exporter.exportReport();

Unfortunately, when I attempt this on the large file I mentioned, I get an OutOfMemoryError:
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.io.ObjectInputStream$HandleTable.grow(ObjectInputStream.java:3421)
    at java.io.ObjectInputStream$HandleTable.assign(ObjectInputStream.java:3227)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1744)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
    at java.util.ArrayList.readObject(ArrayList.java:593)
    at sun.reflect.GeneratedMethodAccessor184.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
    at net.sf.jasperreports.engine.base.JRVirtualPrintPage.readObject(JRVirtualPrintPage.java:423)
    ...

From browsing some of the Jasper internals, it looks like no matter how I attempt to set up this export (I have also tried loading and setting the JASPER_PRINT parameter directly), there will ultimately be a call to JRLoader.loadObject(...) which will attempt to load my entire 500MB report into memory (see net.sf.jasperreports.engine.JRAbstractExporter.setInput()).
My question is, is there a way around this that doesn't involve just throwing memory at the problem?  500MB is doable, but it doesn't leave my application very future-proof, and the JRVirtualizer solution for report execution leaves me hoping there will be something similar for export.  I am willing to get my hands dirty and extend some of the Jasper internal classes, but the ideal solution would be one provided by Jasper itself, for obvious reasons.

A: Since posting this question, I have also filed a feature request with JasperSoft.  As a follow-up, I was pointed to the JRVirtualizationHelper.setThreadVirtualizer method.  This method allows you to set a JRVirtualizer associated with the current thread, which will be used during JasperPrint deserialization.
I have tested this in my project with satisfactory results.  It seems the feature I was hoping existed does indeed exist, although its visibility in the API could potentially be improved.
Code sample:
JRVirtualizer virtualizer = new JRSwapFileVirtualizer(1000, new JRSwapFile(reportFilePath, 2048, 1024), true);
JRVirtualizationHelper.setThreadVirtualizer(virtualizer);

A: I think your problem is that a .jrprint is a serialized Java object that you must deserialize completely. You need to break it somehow into small files and then concatenate the outputs at export time.
My proposal is a bit involved but I think it might work, at least for some cases:

*

*Fill your report using a JRVirtualizer. Use the methods that return a JasperPrint instance, to avoid dumping everything to a huge .jrprint.

*Do an internal export using a JRXmlExporter. The trick would be to use the appropiate JRExportParameters to tell Jasper to export each page separately (you can use a ZipOutputStream as a container to avoid directories with lots of files).

*When you want to do your real export, use a JASPER_PRINT_LIST. It is important that the list implementation is lazy and creates JasperPrint instances one by one using JRPrintXmlLoader, so you do not need to load the whole thing at once.

Anyway, you should inspect Jasper source code to check if this approach is doable.

A: Thank you for your question and your own answer.
But I have a further question on your solution:
You said you use the method JRVirtualizationHelper.setThreadVirtualizer to set the JRSwapFileVirtualizer instance associated with current thread. But since your requirement is to export some previously generated reports into PDF/CSV files, I think the GENERATE and EXPORT actions are run in two separated threads, because these two actions are probably generated by two separated user clicks.
So, why can you set a single JRSwapFileVirtualizer instance for the two threads? You are using a single server JVM?


text:
Q: subclassing a singleton What is the recommended way, if any, to subclass a singleton?  For example,  I would like to make a subclass of AVAudioSession that adds a couple properties and makes the singleton its own AVAudioSessionDelegate.
Right now, I am overriding sharedInstance to allocate my own class, then call my own class' init method.  I am not sure if the other singleton methods need to be protected like a regular singleton, as the super class already is a singleton:
@interface PdAudioSession : AVAudioSession <AVAudioSessionDelegate>

@implementation PdAudioSession

+ (PdAudioSession *)sharedInstance {
    static PdAudioSession *myInstance = nil;
    @synchronized (self) {
        if (!myInstance) {
            myInstance = [[PdAudioSession alloc] init];
        }
    }
    return myInstance;
}

- (id)init {
    self = [super init];
    if (self) {
        self.delegate = self;
    }
    return self;
}

A: Rather than subclass the singleton, why not just create a new class that contains an AVAudioSession object. That way you can create it when you initialize your new class, you can add properties to this new class and also provide itself as a delegate.
Composition is the preferred design pattern in Cocoa over subclassing.


text:
Q: How to monitor a file descriptor for new data availability? Consider the following code snippet.
#include <fcntl.h>
#include <stdio.h>
#include <sys/poll.h>
#include <unistd.h>

int main(int argc, char ** argv) {
    int fd;
    char buf[1024];
    int i;
    struct pollfd pfds;
    fd = open(argv[1], O_RDONLY);

    while (1) {
        pfds.fd = fd;
        pfds.events = POLLIN;

        poll(&pfds, 1, -1);

        if (pfds.revents & POLLIN) {
            i = read(fd, buf, 1024);

            write(1, buf, i);
        }
    }

    return 0;
}

This program receives a file name, opens the corresponding file, and "poll"s its file descriptor in order to monitor data in availability. Whenever poll detects data in availability, those new data are printed.
However, what happens with this program? If the file I want to monitor already contained data when the program is launched, its contents are printed. That's ok. But, later, when I edit the file with a text editor and save it, my program doesn't print the new data.
So, how to monitor a regular file descriptor (not a file using its path) for new data availability? Do I have to use another function other than poll? Or am I missing any pollfd flag?

A: You can't use poll on regular files to watch for changes. However, there are several other ways. The classic approach is to call fstat at regular intervals with the open file descriptor, and compare the returned fields with the previous fields (in particular st_size). A modern approach is to use inotify(7) for monitoring files. For example recent versions of GNU tail use this approach:
$ strace tail -f /tmp/foobar
...
open("/tmp/foobar", O_RDONLY) ) = 3
...
inotify_init() = 4
inotify_add_watch(4, "/tmp/foobar", IN_MODIFY|IN_ATTRIB|IN_DELETE_SELF|IN_MOVE_SELF) = 1
...
read(4, ...

See the manual page inotify(7) for more information on how that works.


text:
Q: MySQL nested Conditional in Update Trigger I am trying to figure out a conditional trigger for an update to a MySQL table.
The issue is that the update trigger fires off even when the data being entered is the same as the data that was already there. So if I have a column with a row:value set up like this plus_votes:2 if I update with UPDATE votes SET plus_votes = 2; even though nothing has really changed the UPDATE trigger still gets fired off. So to prevent all of this I want to add a conditional clause to my trigger like this
BEGIN
IF NEW.vote_value <> OLD.vote_value THEN
UPDATE my_other_table
SET plus_votes =
    CASE NEW.vote_value WHEN '1'
        THEN plus_votes + 1
        ELSE plus_votes
    END,
    minus_votes =
    CASE NEW.vote_value WHEN '1'
        THEN minus_votes
        ELSE minus_votes +1
    END
WHERE my_other_table.id=NEW.votes_join_id;
END

END
the second half of the issue is that I have CASE condition inside the IF statement.
Can someone help on this issiu and show how to do nested conditionals inside a TRIGGER?
much appreciated

A: although the syntax you have posted is completely wrong, I have figured out what you want try this ( not tested )
DROP TRIGGER IF EXISTS upd_vote;

DELIMITER $$

  CREATE TRIGGER upd_vote AFTER UPDATE ON `my_other_table`
  FOR EACH ROW BEGIN
    IF NEW.vote_value <> OLD.vote_value THEN
      SET
        NEW.plus_votes = IF(NEW.vote_value=1,OLD.plus_votes+1,OLD.plus_votes),
        NEW.minus_votes = IF(NEW.vote_value=1,OLD.minus_votes,OLD.minus_votes +1 )
    END IF;
END$$

DELIMITER ;


text:
Q: Index optimization on a view using a full outer join Table structure:
Foo             FooChild                Bar
---             --------                ---
ID              ID                      ID
Date            FooID                   Date
GroupID         UserID                  UserID
Notes           Amount                  GroupID
                                        IsComplete

*

*Foo has a unique index on Date+GroupID

*FooChild has a FK to Foo, and a unique index on FooID+UserID, which includes Amount

*Bar has a unique index on Date+UserID+GroupID, which includes IsComplete
Now I need to create a report showing the sum of all FooChild amounts alongside the count of complete Bars for any given date range.  The users also want to be able to see the stats per group or per user.  This would seem to be a great place to write a view:
create view vFooBar as
select f.Date, f.GroupID, fc.UserID, fc.Amount, b.IsComplete
from Foo f join FooChild fc on fc.FooID = f.ID
left join Bar b on f.Date = b.Date and f.GroupID = b.GroupID and fc.UserID = b.UserID
union
select b.Date, b.GroupID, b.UserID, x.Amount, b.IsComplete
from Bar b left join
    (select f.Date, f.GroupID, fc.UserID, fc.Amount
    from Foo f join FooChild fc on fc.FooID = f.ID) x
on x.Date = b.Date and x.GroupID = b.GroupID and x.UserID = b.UserID

(Here's why I wrote the view this way.)
Now I can easily write queries like this:
select UserID, sum(Amount) FooAmount, sum(cast(IsCompleted as int)) CompletedBars
from vFooBar
where Date between @fromDate and @toDate
group by UserID

But there's a snag here.  As soon as the date range starts getting relatively big, the execution plan goes all pear shaped.  It uses the date index on Foo, but instead of then using the FooID index on FooChild, it does a clustered index scan, then a hash match on FooID to join with the results from Foo.  And it does that twice in the overall plan; I'm guessing once for each aggregate.  And that really hurts.
I understand that using the index I created on FooChild may not be efficient, since the values of FooID for a given date might be discrete, though typically they are inserted in roughly the same order.
I could denormalize, and add Date and GroupID to the FooChild table, then index those columns, and I'm pretty sure that would improve performance a lot.  But it just doesn't feel right.
Any other ideas?

A: The optimizer makes choices based on costing estimates. The cost model is generic, and may not always choose optimal plans for your particular hardware, and its assumptions may not always be valid for your circumstances.
In this case, the optimizer assesses a hash join as the cheaper option over nested loops when the estimated number of rows to be joined is large. If you are certain that a nested loops join will always be preferable to a hash join, you could consider (and test!) forcing a seek instead of a scan of the FooChild table in the view:
SELECT
    f.TheDate,
    f.GroupID,
    fc.UserID,
    fc.Amount,
    b.IsComplete
FROM dbo.Foo AS f
JOIN dbo.FooChild AS fc WITH (FORCESEEK) -- New hint
    ON fc.FooID = f.ID
LEFT JOIN dbo.Bar AS b
    ON f.TheDate = b.TheDate
    AND f.GroupID = b.GroupID
    AND fc.UserID = b.UserID
UNION
SELECT
    b.TheDate,
    b.GroupID,
    b.UserID,
    x.Amount,
    b.IsComplete
FROM dbo.Bar AS b
LEFT JOIN
(
    SELECT
        f.TheDate,
        f.GroupID,
        fc.UserID,
        fc.Amount
    FROM dbo.Foo AS f
    JOIN dbo.FooChild AS fc WITH (FORCESEEK) -- New hint
        ON fc.FooID = f.ID
) AS x
    ON x.TheDate = b.TheDate
    AND x.GroupID = b.GroupID
    AND x.UserID = b.UserID;

Side note: while this transformation from the original full join is valid given the current uniqueness constraints on your tables, please review the answer to your previous question and consider rewriting the full join as suggested in my edit.


text:
Q: iostream causing mismatch with another library I'm trying to read a memory value to use with discord_rpc to add a sort of rich presence pseudo functionality to an existing program.
It seems whenever I try to #include <iostream> it throws a bunch of errors whenever I try to compile code.
Here is some the error:
Error   LNK2038 mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MDd_DynamicDebug' in Discord RPC.obj Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\discord-rpc.lib(discord_rpc.obj)   1
Error   LNK2038 mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in Discord RPC.obj Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\discord-rpc.lib(discord_rpc.obj)   1
Error   LNK2038 mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in Discord RPC.obj Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\discord-rpc.lib(discord_register_win.obj)  1
Error   LNK2038 mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MDd_DynamicDebug' in Discord RPC.obj Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\discord-rpc.lib(discord_register_win.obj)  1
Error   LNK2038 mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in Discord RPC.obj Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\discord-rpc.lib(serialization.obj) 1
Error   LNK2038 mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MDd_DynamicDebug' in Discord RPC.obj Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\discord-rpc.lib(serialization.obj) 1
Error   LNK2038 mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in Discord RPC.obj Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\discord-rpc.lib(rpc_connection.obj)    1
Error   LNK2038 mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MDd_DynamicDebug' in Discord RPC.obj Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\discord-rpc.lib(rpc_connection.obj)    1
Warning LNK4098 defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Discord RPC\LINK   1
Error   LNK1319 8 mismatches detected   Discord RPC C:\Users\Joseph\source\repos\Discord RPC\Debug\Discord RPC.exe  1

I'm very new to c++ so I have little to no clue what I'm doing wrong.
Here is a pastebin of my full code thus far: https://pastebin.com/N1vnJiXZ
I'm also using visual studio 2017

A: Seems I was using C code examples to base the discord RPC part of my program off and I don't think C want's to play nicely with C++. Very stupid mistake, though I learnt from it which is what matters.


text:
Q: selectedindexchanged event in radcombobox I have a radcombobox as:
<telerik:RadComboBox ID="SelectInitiative" runat="server" AutoPostBack="true"
                    DataSourceID="SqlInitiative" DataTextField="Initiative_Name"
                    DataValueField="ID"  EmptyMessage="Select Initiative" Height="200px"
                      OnSelectedIndexChanged="SelectInitiative_SelectedIndexChanged" Width="300px">
                </telerik:RadComboBox>

                <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

            	`

<asp:SqlDataSource ID="SqlInitiative" runat="server"
        ConnectionString="<%$ ConnectionStrings:ProjectPlanningConnectionString %>"
        SelectCommand="SELECT * FROM [Initiative]"></asp:SqlDataSource>

And the code for the event is as:
 protected void SelectInitiative_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (SelectInitiative.SelectedValue.ToString() != "")
        {
            Session["InitiativeID"] = SelectInitiative.SelectedValue.ToString();
        }
        Label1.Text = "You selected " + e.Value + " item";

    }

The problem is that it is neither picking up the value of " selectedvalue" or "e.Value" ,both values are coming out to be empty....... Please help ..........

A: Do you can try this ?
protected void SelectInitiative_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
    if(!IsPostBack)
    {
        if (SelectInitiative.SelectedValue.ToString() != "")
        {
            Session["InitiativeID"] = SelectInitiative.SelectedValue.ToString();
        }
        //Or change this line
        //Label1.Text = "You selected " + e.Value + " item";
        //To this sample
        Label1.Text = "You selected " + SelectInitiative.SelectedValue + " item";

    }

}

Or look/check the content of this variable from  RadComboBoxSelectedIndexChangedEventArgs properties:
-Text     : is the text of the item that was just selected.
-Value    : is the value of the item that was just selected.
-OldText  : is the text of the item that was previously selected
-OldValue : is the value of the item that was previously selected
Or try this:
Label1.Text = "You selected " + SelectInitiative.SelectedValue + " item";

A: I had a similar problem and for me the source was that I was setting the datasource on every AutoPostBack. Make sure that you're not reinitializing the items in the combo box before the event triggers.


text:
Q: $h_n:=\lvert f-f_n\rvert\to 0\implies\int h_n\, d\mu\to 0$?

Let $f,f_n\in\mathcal{L}_{\mu}^1$ with $f_n\to f\text{ a.s.}$. Define $h_n:=\lvert f-f_n\rvert$. Then $h_n\to 0\text{ a.s.}$. How can I prove that $\int h_n\, d\mu\to 0$?

My idea ia to use the following proposition:

$f_n\in\mathcal{L}_{\mu}^1$ with $f_n\nearrow f$ a.s. and $\sup\int f_n\, d\mu<\infty$, so it is $f\in\mathcal{L}_{\mu}^1$ and $\int f_n\, d\mu\nearrow\int f\, d\mu$

Here $-h_n\in\mathcal{L}_{\mu}^1$, $-h_n\nearrow 0$ a.s. and $\sup\int -h_n\, d\mu<\infty$, so $-\int h_n\, d\mu\nearrow\int 0\, d\mu =0\Leftrightarrow \int h_n\nearrow 0$.

Is there another way?

A: From Folland's Real Analysis Sec. 2.4, there are 4 examples you should keep in mind with the Lebesgue Measure on modes of convergence:

*

*$f_n = \frac{1}{n} \chi_{(0,n)}$

*$f_n = \chi_{(n,n+1)}$

*$f_n = n \chi_{[0,1/n]}$

*$f_n = \chi_{[j/2^k,(j+1)/2^k]}$ where $n=2^k+j$ and $0\leq j < 2^k$. So the intervals are $[0,1],[0,1/2],[1/2,1],[0,1/4]...$.

In the first 3 cases, you have uniform, pointwise, a.e. convergence to 0 but not in $L^1$. The fourth converges in $L^1$ to 0 but converges nowhere. Cases 1,2,4 converge in measure, but case 2 is not Cauchy in measure.


text:
Q: Why does np.astype('uint8') give different results on Windows versus Mac? I have a (1000,1000,3) shaped numpy array (dtype='float32') and when I cast it to dtype='uint8' I get different results on Windows versus Mac.
Array is available here: https://www.dropbox.com/s/jrs4n2ayh86s0fn/image.npy?dl=0
On Mac
>>> import numpy as np
>>> X = np.load('image.npy')
>>> X = X.astype('uint8')
>>> X.sum()
167942490

On Windows
>>> import numpy as np
>>> X = np.load('image.npy')
>>> X = X.astype('uint8')
>>> X.sum()
323510676

Also reproduces with this array:
import numpy as np
X = np.array([
[[46410., 42585., 32640.],
 [45645., 41820., 31875.],
 [45390., 41310., 32130.]],

[[44880., 41055., 31110.],
 [44115., 40290., 30345.],
 [46410., 42330., 33150.]],

[[45390., 41310., 32130.],
 [46155., 42075., 32895.],
 [42840., 38760., 30090.]]], dtype=np.float32)

print(X.sum(), X.astype('uint8').sum())

Prints 1065135.0 2735 on Windows and 1065135.0 1860 on Mac.
Here are results with different OS and Python and Numpy:
Python 3.8.8  (Win) Numpy 1.22.4 => 1065135.0 2735
Python 3.10.6 (Mac) Numpy 1.24.2 => 1065135.0 2735
Python 3.7.12 (Mac) Numpy 1.21.6 => 1065135.0 1860

A: This problem is due to a bad conversion causing integer overflows. Indeed, Numpy use C casts so to convert values, but converting floats outside the range 0-255 to 8-bit unsigned integers results in an undefined behaviour in C. We tried to do our best to report errors in this case without impacting performance but this is not possible in all cases. The latest versions of Numpy should fix this but the issue is still partially unsolved. See the 1.24.0 release notes, this issue and this one, as well as this PR (AFAIK, the first reference to this issue is found here).
Anyway, while the error may not be detected on your target machine, casting floating-point number outside the range 0-255 is unsafe and you should not expect a correct result. You need to adapt your code so there is no overflow in the first place. I also advise you to use at least the version 1.24.0 of Numpy so to better track such errors.
Related post: Why does numpy handle overflows inconsistently?


text:
Q: What is the purpose of creating a class-level variable in Java? I was writing a piece of code that goes like this,
public class Grades
{
   public int marks; // what's the purpose of this?
...
...
}

A: By declaring the variable outside of any methods you've made it an attribute of the class. This means that any method in the class can access it, and depending on its encapsulation (public/private/protected/package private) other classes can access it as well.
As for that specific variable's purpose in that specific class, that cannot be determined without seeing more code.

A: Objects are data and methods encapsulated together into a single software component.
Classes are templates ("cookie cutters") from which you can create one or more instances in memory ("cookies").  Each one is independent; each can have its own state.