text:
Q: FLTK callbacks won't accept my function pointers So I have this class
which is supposed to contain my window and all the functions that I'm going to use as callbacks.
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Value_Input.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Slider.H>
#include <FL/Fl_Check_Button.H>
#include "world.hpp"

class Controller
{
    private:
        Fl_Double_Window *window;
    public:
        int process(int argc, char **argv);
        void nextStep(Fl_Widget *widget, void *data);
        void togglePlay(Fl_Widget *widget, void *data);
        void newWorld(Fl_Widget *widget, void *data);
        void randFill(Fl_Widget *widget, void *data);
        void togglePreviz(Fl_Widget *widget, void *data);
        void updateSpeed(Fl_Widget *widget, void *data);
        Fl_Double_Window* make_window();
};

Now in the implementation of "make_window()" (which was originally created using FLUID) I want to assign my functions to the appropriate widgets.
Fl_Double_Window* Controller::make_window()
{
    //Generated with FLUID designer
    Fl_Double_Window* w;
    { Fl_Double_Window* o = new Fl_Double_Window(1200, 900);
    w = o; if (w) {/* empty */}
    o->color(FL_FOREGROUND_COLOR);
    { World* o = new World(25, 25, 800, 800);
      o->box(FL_DOWN_BOX);
      o->color((Fl_Color)30);
      o->end();
    } // Fl_Group* o
    { Fl_Group* o = new Fl_Group(850, 25, 300, 805);
      o->box(FL_DOWN_BOX);
      o->color(FL_INACTIVE_COLOR);
      { Fl_Value_Input* o = new Fl_Value_Input(875, 50, 100, 24, "Cellules");
        o->align(Fl_Align(FL_ALIGN_RIGHT));
      } // Fl_Value_Input* o
      { Fl_Button* o = new Fl_Button(900, 100, 200, 40, "Creation Monde");
        o->box(FL_ROUNDED_BOX);
        o->callback(newWorld);
      } // Fl_Button* o
      { Fl_Slider* o = new Fl_Slider(FL_HOR_NICE_SLIDER, 900, 175, 200, 25, "Vitesse");
        o->callback(updateSpeed);
        o->align(Fl_Align(FL_ALIGN_TOP));
        o->bounds(0.0, 1.0);
      } // Fl_Slider* o
      { Fl_Check_Button* o = new Fl_Check_Button(875, 225, 64, 20, "Mode PreViz");
        o->callback(togglePreviz);
        o->down_box(FL_DOWN_BOX);
      } // Fl_Check_Button* o
      { Fl_Value_Input* o = new Fl_Value_Input(875, 300, 100, 24, "Taux");
        o->align(Fl_Align(FL_ALIGN_RIGHT));
      } // Fl_Value_Input* o
      { Fl_Button* o = new Fl_Button(900, 350, 200, 40, "Remplissage Aleatoire");
        o->callback(randFill);
        o->box(FL_ROUNDED_BOX);
      } // Fl_Button* o
      { Fl_Button* o = new Fl_Button(950, 500, 100, 100, "@>");
        o->callback(togglePlay);
        o->box(FL_ROUNDED_BOX);
        o->labelsize(50);
      } // Fl_Button* o
      { Fl_Button* o = new Fl_Button(950, 650, 100, 100, "@->");
        o->callback(nextStep);
        o->box(FL_ROUNDED_BOX);
        o->labelsize(50);
      } // Fl_Button* o
      o->end();
    } // Fl_Group* o
    o->end();
  } // Fl_Double_Window* o
  return w;
}

The problem is that at every line where I call "o->callback(myFunctionPointer);" I get an error telling me that
no instance of overloaded function "Fl_Button::callback" matches the argument list -- argument types are: (void (Fl_Widget *widget, void *data)) -- object type is: Fl_Button

From what I've researched it should mean that I don't send the appropriate number or type of parameters in my "callback" function. After digging in the documentation, I've found that the "callback" function expects at least a pointer to a Fl_callback object but I've seen examples of code where people just send a function pointer and it seems to work just fine on their code.
Why won't FLTK accept my pointers ? Have I declared them wrong ?
Any help would be appreciated
Thanks

A: FLTK callbacks are free functions( static or none-member fuunctions ). You are passing instance member functions. If the this parameter is not needed you can declare your functions static.  Or install some ad-hoc callback manager(assuming c++17 support):
typedef void fltk_cb(Fl_Widget *, void*);

void Controller::nextStep(Fl_Widget *);

template<auto cb, typename cb_type=decltype(cb)>
struct mem_cb{
static_assert(std::is_same_v<cb_type, void Controller::(*)(Fl_Widget *)>,"incompatible type");
    constexpr operator fltk_cb*()const{return &static_cb;};
    static void static_cb(Fl_Widget * w, void * that){
        (reinterpret_cast<Controller*>(that)->*cb)(w);
    };
};

//...
 o->callback(mem_cb<&nextStep>{},this);

prior to c++17 syntax can be awkward. Using std::function or boost::signal2 and a little bit of more complication better ad-hoc callback management can be achieved. But I guess you just need some starter.
A shorter solution is none-capture lambda:
void Controller::nextStep(Fl_Widget *);

o->callback(
    [](Fl_Widget *w, void *that){
        reinterpret_cast<Controller*>(that)->nextStep(w);
    }
,this);

a none-capture lambda - by convention - decays to a free function pointer with compatible signature. This solution is simpler but the template one encapsulates the potentially risky cast in a class in order to decrease the chances for bugs.

A: One static for every callback is how we used to do it before C++08, lambdas and future versions came out
{ Fl_Check_Button* o = new Fl_Check_Button(875, 225, 64, 20, "Mode PreViz");
   o->callback(_togglePreviz, this);
   o->down_box(FL_DOWN_BOX);
} // Fl_Check_Button* o

static void _togglePreviz(Widget* w, void* me)
{
    Fl_Check_Button* cb = dynamic_cast<Fl_Check_Button*>(w);
    Controller* self = reinterpret_cast<Controller*>(me);
    self->togglePreviz(cb);
}

void togglePreviz(Fl_Check_Button* cb)
{
     ....
}


text:
Q: Android : How to store a generated ID and recall it the next app run? Every time my app starts an ID is generated by my program. Since each time it generates a different ID , I want to save the ID somewhere before exiting the program so I can use it again when the program runs later.
Sample ID : 125469
Note : I rather to not save it in file but some else.

A: Even a better solution would be to use GreenDAO here are some examples
https://github.com/greenrobot/greenDAO
https://github.com/octa-george/Android-GreenDao-Sample
GreenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases. Being highly optimized for Android, greenDAO offers great performance and consumes minimal memory.

You only need the greendao jar
public class MyDaoGenerator {

      public static void main(String args[]) throws Exception {
      Schema schema = new Schema(1, "ro.octa.greendaosample.dao");
      createSchema(schema);
      new DaoGenerator().generateAll(schema, "C:/GreenDaoSchema");
}

private static void createSchema(Schema schema) {

     Entity user = schema.addEntity("DBUser");
     user.addIdProperty().primaryKey().autoincrement();
     user.addStringProperty("email").notNull().unique();
     user.addStringProperty("password").notNull();

}

After a few lines of code you have the model generated for autoincrement id, email and password.

A: You can use SharedPreferences or you can use SQLite database for storing purposes.

A: You can do it like that:
private SharedPreferences prefs;

...
...
private void initializeFromPreference() {
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
myId = prefs.getInt("myId", myId );
}
...
...
public void onDestroy() {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("myId", myId );
editor.commit();
super.onDestroy();
}

i wouldnt use a database for a single value, Sharedpreferences is a good way to do so

A: You can Use SharedPreferences to store your id
 SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE);

       Editor edit=prefs.edit();

       //to store value
       edit.putInt("Your Id Name", Id Value).commit();

       //to get value

       int id=prefs.getInt("Your Id Name", 0);

A: Here's the simple way, I can think of :)
    public static SharedPreferences sharedpreferences;
    sharedpreferences = getSharedPreferences("MyIds", Context.MODE_PRIVATE);

    if (sharedpreferences.contains("id"))
    {
       String id = sharedpreferences.getString("id", "");
       // *Use existing id and enjoy* ;)
    }
    else{

            // *Generate New ID (yourID)*
            Editor editor = sharedpreferences.edit();
            editor.putString("id", yourID);
            editor.commit();
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integrate vue in a template with vars / props I'm currently creating a vue app and wondering how to integrate it into a template and passing vars (props) into it.
So I basically run npm run dev, coding the app and all its components and so far everything is fine.
When I run npm run build I'll get some js in my build folder, created by webpack.
I guess (as seen before before here on stackoverflow) I can just load these files in my template, create an html-element mit the id "App" and everything works and the app initializes itself automatically.
But now my problem is: the app fires some Ajax requests, and depending on the environment the targets are different (dev: api.local, test: api.testsystem.com, prod: api.livesystem.com, ...).
And therefore I need to pass the url from outside into the app.
We don't build the app at deployment, as it's on a different repository than the "websites" using it. (Our plans are wether to copy the build files manually in these projects or offer an cdn-like url where the other projects load it). And with other projects I mean a symfony based website, or a typo3 plugin, ...
So, from React I remember you can initiate an app like React.render('app.js', {props: 'api-url': 'http://api.local'}); (don't kill me, it was somehow like this...)
How do I do it in vue?
Like:
new Vue(
  <template>
    <App :api-url="api-url" />
  </template>

  <script>
    import App from "path/to/app.js";

    export default {
      data() {
        api-url: "inject url here"
      }
    }
  </script>
);

or add an data attribute like <div id="App" data-api-url="http://url"> and try to access it inside the app?
I've also seen something like an env-loader - but I'm not sure if this helps in my case.

A: You talk about different environment mode. You should read this documentation about how to start vue app with different env mode.
You can define different .env files for each mode and populate process.env with this file, or you can start vue.js with NODE_ENV=development per example, and check for process.env.NODE_ENV where you need to pass appropriate variables.


text:
Q: Can I use D'Fusion as the Augmented Reality Authoring Tool for Metaio? Like the title says. Can I use D'Fusion as the authoring tool for metaio (as for metaio's own authoring tool, you have to buy a licence)?

A: No you can't.
Metaio's sdk is  free though. You only have to buy a license if your need to get rid of the watermark. Otherwise, pretty much all of the functions an features are there for unlimited use.


text:
Q: ¿Por qué no reconoce el metodo del service que llamo desde un metodo en el componente? Tengo este Service que administra todo lo que tiene que ver con el cliente.

Y dentro de este Service tengo este metodo:
public getCustomers() {
return this.http.get(this.customerUri).map(res => {
  return res.json();
});}

El Cual llega a un WebApi a traer la informacion de todos los clientes, y la retorna al componente Customer para mostrarla en pantalla.
Del lado del component creo la instancia del Service

Y muestro a todos los usuarios en el momento en que el componente se inicia y renderiza.

He creado aqui mismo en el metodo ngOnInit un timer que ejecutara un metodo cada 10s y el fin de este metodo es ejecutar el metodo getCustomers() del Service.

Pero aunque parece que todo esta bien, y solo estoy reusando el mismo metodo, me tira este error:

¿No estoy siguiento los pasos correctamente? ¿El metodo de un servicio puede solo usarse desde el metodo ngOnInit? o ¿De alguna manera se pierde la instancia?

A: Si ves en la consola el error viene del metodo updateCustomerStuff.
Dentro de este metodo this hace referencia a updateCustomerStuff y no al componente. Como updateCustomerStuff.getCustomers no está definido llega ese error.


text:
Q: Derivation of gaussian mixture models assuming that hidden variable is known I saw the following notes from CS229 (screenshotted below). I am confused how the two equations are equivalent. How were they able to distribute the $log$ inside the summation? I don't see how knowing the hidden variable $z$, allows us to write it this way.

A: The meaning of $z^{(i)}$ in the two equations differs. In the observed log-likelihood
$$\ell^o(\theta|\mathbf x)=\sum_{i=1}^m \log \sum_{z^{(i)}=1}^k p(z^{(i)}|\theta)
p(x^{(i)}|z^{(i)},\theta)$$
$z^{(i)}$ is an index and the above could be written
$$\ell^o(\theta|\mathbf x)=\sum_{i=1}^m \log \sum_{j=1}^k p(j|\theta)
p(x^{(i)}|j,\theta)$$
In the completed log-likelihood
$$\ell^c(\theta|\mathbf x,\mathbf z)=\sum_{i=1}^m \log p(z^{(i)}|\theta)
p(x^{(i)}|z^{(i)},\theta)$$
$z^{(i)}$ is a latent variable that indicates the provenance component of $x^{(i)}$.

The completed log-likelihood $\ell^c(\theta|\mathbf x,\mathbf z)$ is
  the log-likelihood associated with the joint distribution of the
  random sample $(\mathbf x,\mathbf z)$. The observed log-likelihood
  $\ell^c(\theta|\mathbf x)$ is the log-likelihood associated with the
  marginal distribution of the random sample $\mathbf x$.

A: The summation cannot be distributed but the product can. If the $z^{(i)}$ value is unknown, the variable inside the log is the summation over $z^{(i)}$. But when the value is known, it reduces to one term, which is just the product of the two probabilities.

To understand why it reduces to the one term, you need to think from a different point of view. The original log-likelihood is derived with the assumption that we don't know the index of the Gaussian in the mixture the observation comes from. This is an ignorant observer's point of view. The observer didn't see the drawing process of the sample and he/she only can guess probabilistically from what class the observation came.
However, there is a different point of view. If you are actually the person draw the sample, you perfectly know the origin of the observation. So in this case, you will have only one index of mixture contributing to the observation and the summation reduces to the one term. The EM algorithm goes with this view but it assumes we don't know the parameters of the distribution either and tries to decide the parameters in a recursive way.


text:
Q: Search Bar, Box I am making some site for personal use.
I am trying to make some search bar, box.
But, all that I found is with PHP.
I do not want PHP search box,
I want something like Ctrl+G or Ctrl+H (Like "Find words in this site").
I want to make search bar for only text in active site,page.
Without PHP.
W3S is helping only with PHP.
If You know what I mean, please respond fast.
Sorry for my bad English. ;)
Thank You!
I tried search codes in Google and did not find how to make search box without PHP.
eg. CTRL+G or CTRL+H
I do not have code.
This is my first question on stackoverflow, sorry for mistakes..
I expect to work only in that site that is code in.(Again, sorry for English)

A: Any search box that you are creating to get data or information from your site will be using php because it is more then likely in most cases pulling data from your database if you are trying to replicate the default browser functionality for Ctrl+F then you can create a search box with html and JavaScript
Heres a little snippet to send you on the right path

jQuery(document).keydown(function(event) {
        // If Control or Command key is pressed and the F key is pressed
        if((event.ctrlKey || event.metaKey) && event.which == 70) {
            // hide/unhide search box
            //or put your custom code here

            //Insert code above this line
            event.preventDefault();
            return false;
        }
    }
);
<form action="#">
  <input type="text" id="search" placeholder="search">
  <input type="submit">
</form>


text:
Q: Draw 4 straight lines on image (overlay) I need an image to be divided in the users browser by 2 lines horizontally and 2 lines vertically. So that there are 9 pieces the image consists of.
Either doing this by drawing lines or by putting the 9 pieces a little bit apart.
I know of Raphael and paper.js but maybe it can be done (canvas html5 and html4 JS) without additional frameworks.
If you got an approach, would using it also be capable to part a circle by 4 like splitting a cake?

A: You can slice and space an image apart using the canvas drawImage function

All the work is done by the context.drawImage function using some extra parameters
drawImage is able to clip a portion of the source image and draw it on the canvas
BTW, drawImage is also able to simultaneously scale that  clipped portion.
Here are the arguments to allow drawImage to slice the source image:

*

*The source image

*X position on the source image where clipping will start

*Y position on the source image where clipping will start

*Width of the source image to clip

*Height of the the source image to clip

*X position on the canvas to place the clipped sub-image

*Y position on the canvas to place the clipped sub-image

*The scaled width of the clipped image to be drawn on the canvas

*The scaled height of the clipped image to be drawn on the canvas

And here's how to use drawImage to slice the source image into 3x3 cells with 10px spacing
context.drawImage(

  img,               // the source image
  0,0,               // get the image starting at it's 0,0 position
  img.width,         // grab the entire width of the image
  img.height         // grab the entire height of the image
  x*img.width/3+10,  // make 3 image "columns" with 10px spacing
  x*img.height/3+10, // make 3 image "rows" with 10px spacing
  img.width/3,       // each image column is 1/3 of the original image
  img.height/3       // each image row is 1/3 of the original image

);

Here's code and a Fiddle:  http://jsfiddle.net/m1erickson/m89Gg/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var image=new Image();
    image.onload=function(){
        slice(image);
    }
    image.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sky-bg2.jpg";

    function slice(img){

        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        var w=img.width;  // original image width
        var h=img.height; // original image height
        var rows=3;       // # of rows
        var cols=3;       // # of columns
        var cw=w/rows;    // cell width
        var ch=h/cols;    // cell height
        var scale=3;      // also, scale the image down
        var spacing=5;    // spacing between cells

        // set the canvas width to accommodate
        // sliced/space/scaled image
        canvas.width=w/scale+spacing*2;
        canvas.height=h/scale+spacing*2;

        ctx.clearRect(0,0,canvas.width,canvas.height);

        for(var y=0;y<3;y++){
            for (var x=0;x<3;x++){
                ctx.drawImage(img,x*cw,y*ch,cw,ch,
                    x*(cw/scale+spacing),y*(ch/scale+spacing),cw/scale,ch/scale)
            }
        }
        ctx.stroke()
    }

}); // end $(function(){});
</script>

</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>


text:
Q: Copy numbered files to corresponding numbered directory using Linux bash commands or script This should be a relatively straightforward problem but I haven't found any answers within stackoverflow. In a given directory, I have ~1000 files that are numbered (e.g. chem-0320.inp). I would like to cp the numbered file to a correspondingly numbered directory; all copied files will be renamed with the same name. I would like to do this for a specified numbered of files (#'s 300-500 for example).
For example, I would like to copy chem-0320.inp to a directory named 320 and rename it mech.dat.
Another example: copy chem-0430.inp to a directory named 430 and rename it mech.dat.
Thanks in advance for your help!

A: The following script would do the work for you
for file in *.inp
do
 dir=$(echo $file | sed -r 's/[^0-9]+0([0-9]+).*/\1/g')
 mv $file $dir/mech.dat
done

A: "cd" first to right dir. Subdirs will be created there.
#!/bin/bash

lo_limit=300
hi_limit=500

for file in ./*.inp
do
    dir="${file//[^0-9]/}"
    dir_cut="${dir:1:3}" # leading zero cut off
    if  [ $dir_cut -ge $lo_limit ] && [ $dir_cut -le $hi_limit ]; then
        echo "$file  $dir_cut"
        mkdir -p "$dir_cut"
        cp "$file" "$dir_cut"/mech.dat
    fi
done


text:
Q: Evaluate variables for positioning multiple times Here is a working code (I'll describe it just after) :
    \documentclass[border=2pt]{standalone}
    \usepackage[utf8]{inputenc}

    \usepackage{graphics}
    \usepackage{tikz,pgfplots}
    \usetikzlibrary{math} % Pour evaluate
    \usetikzlibrary{calc} % Pour postionnement relatif

    \newcommand*{\addploZ}[2]{
        \addplot[#2,samples=60,domain=0:\Ttrace,thick=3pt,ultra thick,
            evaluate={  \Tun = (1 / ( 6 *(#1-sqrt(#1^2 -1)) ));
                    \Tdeux = (1 / ( 6 *(#1+sqrt(#1^2 -1)) )); }
            ] {  \K * (1 - ( 1/( \Tun - \Tdeux ) )*( \Tun *exp(-x/ \Tun ) - \Tdeux *exp(-x/ \Tdeux ) ))  };
    }

    \newcommand*{\LegendArrows}[5]{
        \pgfmathparse{(1 / ( 6 *(#1-sqrt(#1^2 -1)) ))} \pgfmathresult \let\Tun\pgfmathresult
        \pgfmathparse{(1 / ( 6 *(#1+sqrt(#1^2 -1)) ))} \pgfmathresult \let\Tdeux\pgfmathresult
        \coordinate (C2) at (axis cs:#2, {  \K * (1 - ( 1/( \Tun - \Tdeux ) )*( \Tun *exp(-#2/ \Tun )
                - \Tdeux *exp(-#2/ \Tdeux ) ))  }) ;
        \draw node[anchor=#3] (#4) at #5 {$z =#2$};
        \draw[fleche] (C2) -- (#4.west) ;
    }

    \tikzset{ fleche/.style={<-,>=latex,line width=0.2mm,shorten <=-0.02cm} }

    \begin{document}

    \begin{tikzpicture}

    \def\K{2}
    \def\w{(3.14159*2)}
    \def\Ttrace{3}

    \begin{axis}[axis x line=bottom, axis y line = left, width=13cm, height=\axisdefaultheight,ymax=1.55*\K,
    ytick=\empty,extra y ticks={\K}, extra y tick labels={},extra y tick style={grid=major}
    ]

    \addplot[samples=2,domain=0:(\Ttrace+0.1),thick=1pt] { \K };

    \addploZ{2}{blue}
    \addploZ{4}{red}

    \LegendArrows{4}{0.6}{west}{C3}{($(C2)+(axis cs:1,-0.5)$)}
    \LegendArrows{2}{0.6}{south}{C4}{(C3.north)}

    \end{axis}
    \end{tikzpicture}

    \end{document}

It compiles to give you this masterpiece:

But you can see the problem, the arrows point to the same point.
Look at the body,
Lets break it down :
\begin{document}
    \begin{tikzpicture}

a few variables for my functions :
    \def\K{2}
    \def\w{(3.14159*2)}
    \def\Ttrace{3}

some plot properties
    \begin{axis}[axis x line=bottom, axis y line = left, width=13cm, height=\axisdefaultheight,ymax=1.55*\K,
    ytick=\empty,extra y ticks={\K}, extra y tick labels={},extra y tick style={grid=major}
    ]

an horizontal asymptot
    \addplot[samples=2,domain=0:(\Ttrace+0.1),thick=1pt] { \K };

Now calling a function created above:
    \addploZ{2}{blue}
    \addploZ{4}{red}

It's calling this one :
\newcommand*{\addploZ}[2]{
    \addplot[#2,samples=60,domain=0:\Ttrace,thick=3pt,ultra thick,
        evaluate={  \Tun = (1 / ( 6 *(#1-sqrt(#1^2 -1)) ));
                \Tdeux = (1 / ( 6 *(#1+sqrt(#1^2 -1)) )); }
        ] {  \K * (1 - ( 1/( \Tun - \Tdeux ) )*( \Tun *exp(-x/ \Tun ) - \Tdeux *exp(-x/ \Tdeux ) ))  };
}

You can see I am using evaluate to find the value of two parameters :\Tun et \Tdeux based on the first parameter (I call it z if you want to know) sent to newcommand. So z=2 in the first call and z=4 in the second one.
And since you can see the two curves, evaluate does it work and I get what I want.
The troubles comes after:
Using arrow to point at the curves:
    \LegendArrows{4}{0.6}{west}{C3}{($(C2)+(axis cs:1,-0.5)$)}
    \LegendArrows{2}{0.6}{south}{C4}{(C3.north)}

Calling the function :
\newcommand*{\LegendArrows}[5]{
    \pgfmathparse{(1 / ( 6 *(#1-sqrt(#1^2 -1)) ))} \pgfmathresult \let\Tun\pgfmathresult
    \pgfmathparse{(1 / ( 6 *(#1+sqrt(#1^2 -1)) ))} \pgfmathresult \let\Tdeux\pgfmathresult
    \coordinate (C2) at (axis cs:#2, {  \K * (1 - ( 1/( \Tun - \Tdeux ) )*( \Tun *exp(-#2/ \Tun )
            - \Tdeux *exp(-#2/ \Tdeux ) ))  }) ;
    \draw node[anchor=#3] (#4) at #5 {$z =#2$};
    \draw[fleche] (C2) -- (#4.west) ;
}

This gives me colliding arrows because of the evaluation of \Tun and \Tdeux placing the node I called C2. I suppose the two evaluations using \pgfmathparse for the two callings of the function are done before the arrows are plotted, and therefore C2 is placed for both arrows at the same spot (the one of the last evaluation).
You can correct me if I'm wrong.
Anyway I tried other solutions, my first try was to duplicate the code I used to plot the function because I need to evaluate the same quantities, like so:
    \newcommand*{\LegendArrows}[5]{
        \coordinate[evaluate={  \Tun = (1 / ( 6 *(#1-sqrt(#1^2 -1)) ));
                    \Tdeux = (1 / ( 6 *(#1+sqrt(#1^2 -1)) )); }
            ] (C2) at (axis cs:#2, {  \K * (1 - ( 1/( \Tun - \Tdeux ) )*( \Tun *exp(-#2/ \Tun ) - \Tdeux *exp(-#2/ \Tdeux ) ))  }) ;
        \draw node[anchor=#3] (#4) at #5 {$z =#2$};
        \draw[fleche] (C2) -- (#4.west) ;
    }

but as I got a compilation error I suppose evaluate is an option of \addplot but not of \coordinate. However it is a option of \node so I can try :
    \newcommand*{\LegendArrows}[5]{
        \node[evaluate={  \Tun = (1 / ( 6 *(#1-sqrt(#1^2 -1)) ));
                    \Tdeux = (1 / ( 6 *(#1+sqrt(#1^2 -1)) )); }
            ] (C2) at (axis cs:#2, {  \K * (1 - ( 1/( \Tun - \Tdeux ) )*( \Tun *exp(-#2/ \Tun ) - \Tdeux *exp(-#2/ \Tdeux ) ))  }) {} ;
        \draw node[anchor=#3] (#4) at #5 {$z =#2$};
        \draw[fleche] (C2) -- (#4.west) ;
    }

which gives :

You can see here the arrows are separated like I want, but the use of node created that gap between the arrows and the curve which is why I tried to use \coordinate in the first place
And to be thoroughn here comes the end of the body:
    \end{axis}
    \end{tikzpicture}
\end{document}

So to sum up my request, I ask for your help either:

*

*to help me with the correct evaluation using \coordinate

*to correct that gap created whenever I use an empty \node as an anchor.

*to come up with improvement and clever tricks like this community so often do

Thank you in advance


text:
Q: Script error in review page Getting script error in review page, due to this, when clicking on "show full answer" link or any other link in that page. That particualr functionality is not working.
Please find screenshot below.
Error information:

Expected identifier, string or number
  Line: 72
  Char: 9
  URL: https://stackoverflow.com/review/

A: Trailing-comma issue, as usual when it's IE7-only. Fix is simple enough, so it should work after the next build.
You might still want to think about upgrading; IE7 is the new IE6. Unless it's trivial fixes like this, we more and more err on the side of "if it kinda works in IE7, that's more than good enough."


text:
Q: React Send Data Between Indirect Childs/Parents I have the below Parent/Child set up. I set it up this way to make it more organized and easy, though now I start seeing why it's impossible to do some things without Redux.
Below is my component Set-up:

There's a search field in the Account Search so when user fills up I need to trigger an API call, which is no big deal. Then I get the data and make the data in the state equal to the data I pulled from through API.  { isLoaded: true, api: data.data }
Then I have to send this data to the Daily component so it can display the data. It's significantly more over convoluting to send the value of the field within AccountSearch component to it's parent AppBarPanel then to his Parent Skeleton, then update the data state in Skeleton and send the data to Content then to it's child Router then to correct page which in this case Daily so data gets displayed.
How can I simplify my life here?
Below is the API Call I have
this.apiService
  .callApi("A", "B", "C")
  .then(data => {
    this.setState({ isLoaded: true, api: data.data });
    toastr.success('Api returned data successfully.');
  })
  .catch(error => {
    toastr.error(error);
  })

A: React is all about data flowing down in the component's hierarchy, which means that horizontal data shouldn't happen, if you are facing a situation where you need to pass data horizontally I advice you to rethink your component's structure. There is a couple of things that you can try:

*

*Use redux ou similar to centralize your application's state

*Wrap your components on a parent component that distributes the data

*Use context API

A: In my experience, there are many instances where you get horizontal requirements for data exchange between components in different branches of the tree (if not then redux would never have been invented).
There are many ways to achieve this:

*

*Redux - what most people use but requires a lot of boilerplate and complexity.

*Context - Facebook's built-in solution for what you want to do

*Events - the native JavaScript way

You can use a library such as pubsub or native js events
e.g. in your receiving component:
componentDidMount() {
   document.addEventListener("dataArrived", this.handleData)
}

and in your other component:
// on data arrived
var event = new CustomEvent('dataArrived', { detail: mydata });
document.dispatchEvent(event);

*Use Globals - Attach to global window (not recommended)
getDataApi().then(data => window.data = data)
listening component:
setInterval(() => if (window.data) { this.setState(window.data) }, 1000);


text:
Q: Prevent duplicate MDI children forms Is there a way to prevent the opening of a certain form within an MDI container if that said form is already opened?

A: You can interate over the OpenForms collection to check if there is already a form of the given type:
foreach (Form form in Application.OpenForms)
{
    if (form.GetType() == typeof(MyFormType))
    {
        form.Activate();
        return;
    }
}

Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();

A: AFAIK there is no standard way. You'll have to implement it yourself. I'd do it this way:
class TheForm: Form
{
    private static TheForm Instance;

    private TheForm() // Constructor is private
    {
    }

    public static Show(Form mdiParent)
    {
        if ( Instance == null )
        {
            // Create new form, assign it to Instance
        }
        else
            Instance.Activate(); // Not sure about this line, find the appropriate equivalent yourself.
    }

    protected override OnFormClose(EventArgs e)
    {
        Instance = null;
        base.OnFormClose(e);
    }
}

If thread safety is of concern, add the appropriate locks.

A: this code working
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        foreach (Form form in Application.OpenForms)
        {

            if (form.GetType() == typeof(Form2))
            {
                form.Activate();
                return;
            }
        }

        Form2 newForm = new Form2();
        newForm.MdiParent = this;
        newForm.Show();
    }

A: Though this post is very old, I thought this will add a help.
Need to handle if form is Minimized too. Here is the complete example:
foreach (Form form in this.MdiChildren)
{
    if (form.GetType() == typeof(frmMain))
    {
        if (form.WindowState == FormWindowState.Minimized)
        {
            form.WindowState = FormWindowState.Normal;
        }
        form.Activate();
        return;
    }
}
Form frm = new frmMain();
frm.MdiParent = this;
frm.Show();

A: This code work for me in vb.net

For Each f As Form In Application.OpenForms
            If TypeOf f Is form_name Then
                f.Activate()
                f.WindowState = FormWindowState.Normal
                f.StartPosition = FormStartPosition.WindowsDefaultLocation
                f.WindowState = FormWindowState.Maximized

            Return
        End If
    Next
    form_name .MdiParent = Me
    form_name .Show()

A: A method can be implemented using Generics (below C# and VB.net options), which can be useful if different MDI Forms need to be opened.
C#
private void OpenMDI<T>(bool multipleInstances)
    where T : Form, new()
{
    if (multipleInstances == false)
    {
        // Look if the form is open
        foreach (Form f in this.MdiChildren)
        {
            if (f.GetType() == typeof(T))
            {
                // Found an open instance. If minimized, maximize and activate
                if (f.WindowState == FormWindowState.Minimized)
                {
                    f.WindowState = FormWindowState.Maximized;
                }

                f.Activate();
                return;
            }
        }
    }

    T newForm = new T();
    newForm.MdiParent = this;
    newForm.Show();
}

Use it as follows (indicate false in multipleInstances to prevent them)
OpenMDI<Form2>(false);

VB.NET
Public Sub Open_MDI(Of T As {New, Form})(bMultipleInstances As Boolean)
    If bMultipleInstances = False Then
        For Each f As Form In Me.MdiChildren
            If TypeOf f Is T Then
                If (f.WindowState = FormWindowState.Minimized) Then
                    f.WindowState = FormWindowState.Maximized;
                End If

                f.Activate()
                Exit Sub
            End If
        Next
    End If

    Dim myChild As New T()
    myChild.MdiParent = Me
    myChild.Show()
End Sub

Use it as follows (indicate False for bMultipleInstances to prevent them)
Open_MDI(Of Form2)(False)

A: This code work for me in C#
      private void btn1_Click(object sender, EventArgs e)
            {
               Form2 new_form = new Form2();
                if (new_form.visible)
                    new_form.Show();
                else
                    new_form.ShowDialog();
            }


text:
Q: Installing ubuntu 16.04 on a usb flash drive using windows So i installed ubuntu on a flash drive using rufus, but every time i reboot everything gets erased (everything i did in the last session before rebooting.)

A: This is normal. You're making an 'live' flash drive. It behaves like a cd/dvd. Changes aren't stored on the drive.
You need to create a drive with persistence. I use Unetbootin for that task: https://unetbootin.github.io/

*

*Download the program, install it and launch it.

*Choose a distribution from the list or choose the diskimage you've already downloaded.

*Set 'space used to preserve files across reboots' to any other value than 0 MB.

Another option is to use 2 flash drives: first launch the live version of Ubuntu from a drive and start the installer. Install Ubuntu on the second disk, make sure the boot loader is also installed on the second flash drive. Turn off your computer when the install is completed. Remove the first drive and reboot your computer. All changes you make on the second drive are now saved. Make sure you use a fast flash drive with enough space.
By the way, you can also use a SD card (that's what I did a while ago to dual boot macOS and Ubuntu).


text:
Q: Multiple Forms With Input Fields With The Same Name Attribute? Good Or Bad? Is it an acceptable practice to have multiple HTML forms on a page with input fields that share the same name attribute? For example, the page contains a listing of all players and users are allowed to vote for the best player so next to each player card there is this form:
<form class="vote-for-player" enctype="application/x-www-form-urlencoded" method="post" action="/index/vote-for-best-player">
    <input type="hidden" name="player_id" value="1" />
    <input type="submit" name="vote_for_player" value="Vote" class="input-submit" />
</form>

Value attribute of the hidden input field is different for each form, of course.
Let's say there are 20 forms like this on the page so that means 20 input fields with the name equal to "player_id". If I pass that page through HTML validator, it is valid even with the XHTML 1.0 Strict doctype. But is this an acceptable practice from web standards or accessibility perspective?
One thing I know for sure, it makes the server side processing of the page easier as I just need to load value from one POST field called player_id.

A: Yes it is valid, I do it all the time.

A: yes that's perfectly fine.. in fact i personally feel that its really a good practice to do so as it turns relatively pretty handy for developers to work with relatively less names as compared to bunch of them.. moreover when elements are on different forms it dose not cause name space collision in any way since to identify elements in js by name we use both form name as well as input field name so it dose not cause any issues...

A: Agree with above answer. Name is totally ok, and will be passed as response parameter of your form. Different story would be if your input elements would have same id's as well - some browsers might have problems traversing dom of your document.
Again, think of bunch of radio buttons, where users can select gender etc. They must have same name (but different id's)...


text:
Q: How to Change hidden (+delay) node to Primary node in Mongodb Problem Statement:
Need to promote Hidden node which is delayed node (30 mins) too to Primary node. I want to test this delayed node feature in case of primary/secondary data corrupt.
I have a test environment with 4 node replica set:

10.0.0.1 - Hidden Delay node (30 mins)
10.0.0.2 - Primary Node
10.0.0.3 - Secondary Node
10.0.0.4 - Hidden Delay node (1 hour)

Below are the steps that I tried:

*

*With a simple script add some data into the primary & checked it on hidden node whether new data is present or not. Data was not there till the next 30 mins.

*Stopped Primary node 10.0.0.2 & 10.0.0.3 became Primary then.

*The issue below command to promote Hidden as Primary.
cfg = rs.conf()
cfg.members[0].hidden = false
cfg.members[0].priority = 1
rs.reconfig(cfg, {force : true})
rs.reconfig(cfg)

*In the above command, I'm missing the slave delay to use. Not sure what is the correct method to promote this node as Primary.


text:
Q: What we know about $\mathbb{Q}/\mathbb{Z}$ as a group?
What we know about $\mathbb{Q}/\mathbb{Z}$ as a group? Are there any interesting properties?

Best regards.

A: *

*$\mathbb{Q}/\mathbb{Z}$ is the torsion group of $\mathbb{C}^{\times}$

*$\mathbb{Q}/\mathbb{Z}$ is divisible

*$\mathbb{Q}/\mathbb{Z}$ is dense in $S^{1}$

*$\mathbb{Q}/\mathbb{Z}$ has a unique subgroup of order $n$ for every $n$

*$\mathbb{Q}/\mathbb{Z}$ is not finitely generated


text:
Q: SSL client certificate auth with ruby (sinatra) How can I authorize an API in sinatra, so that only callers possessing a known client certificate (or one issued by a trusted CA) are allowed to call it?
Currently I am using the 'thin' webserver, but I am open to other options if that is necessary.

A: You can use nginx to take care of your client-certificate - here is a blog post which shows how to set it up:

server {
    listen        443;
    ssl on;
    server_name example.com;

    ssl_certificate      /etc/nginx/certs/server.crt;
    ssl_certificate_key  /etc/nginx/certs/server.key;
    ssl_client_certificate /etc/nginx/certs/ca.crt;
    ssl_verify_client optional;

    location / {
        root           /var/www/example.com/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME /var/www/example.com/lib/Request.class.php;
        fastcgi_param  VERIFIED $ssl_client_verify;
        fastcgi_param  DN $ssl_client_s_dn;
        include        fastcgi_params;
    }
}

We specify our the server's certificate (server.crt) and private key
  (server.key) We specify the CA cert that we used to sign our client
  certificates (ca.crt) We set the ssl_verify_client to optional. This
  tells nginx to attempt to verify to SSL certificate if provided. My
  API allows both authenticated and unauthenticated requests, however if
  you only want to allow authenticated requests, you can go ahead and
  set this value to on.

You can use thin with nginx, but I believe that using passenger with nginx is more popular in this case, and quite easy to deploy.

ssl_verify_client optional is explained here:

ssl_verify_client
Syntax:   ssl_verify_client on | off | optional | optional_no_ca
Default:  off
Context:   http | server
Reference:    ssl_verify_client

This directive enables the verification of the client identity.
  Parameter 'optional' checks the client identity using its certificate
  in case it was made available to the server.

A: Since you're using Thin I don't think this is possible at the moment because peer verification appears to be broken. See https://github.com/macournoyer/thin/pull/203:

"The get_peer_cert method of EM doesn't return anything unless the cert has been verified. The --ssl-verify option of thin actually doesn't do anything. These two behaviors combined mean that env['rack.peer_cert'], which was introduced in thin 1.2.8, always returns nil. Since --ssl-verify never actually caused a verification to happen, it is better to remove that option until a fully verification process is put in place. However, the peer_cert can be made available in --ssl mode by always "verifying" the cert, thereby providing the client supplied certificate, if there is one, available in env['rack.peer_cert']."

I believe Uri Agassi is partially correct by recommending passenger but I worry a nginx/thin combination introduces a security risk if you're expecting the cert to act as the authentication if thin is ever moved off the nginx server, thereby exposing your thin server. I think an embedded appserver solution is the way to go (a la passenger).


text:
Q: Does INACTIVE sessions in Oracle is normal ? Is it Impacted on ORA-02391 Exceeded simultaneous session_per_user limit? I am facing the ORA-02391 for one user. My application keeping more Inactive session in oracle database. ORA-02391 is related to the inactive sessions or only parallel sessions of active connection please clarify.
When and How Inactive sessions for Oracle are removed ?


text:
Q: Symfony 4 Dynamic Subdomain Routing and Nginx Config I want to handle dynamic subdomain in my Symfony 4 application.
I'm looking for configuration like this:

*

*store1.domain.com => StoreController::index

*store2.domain.com => StoreController::index

*www.domain.com => HomeController::homePage

*domain.com => HomeController::homePage etc etc.
I'm trying this code but is not working. Its always match with HomeController. StoreController never matching.
And when I try this configuration "domain.com" request show to me "Welcome to nginx!" page.
class StoreController extends AbstractController
{
    /**
     * @Route("/", name="store_home", host="{store_name}.domain.test")
     */
    public function storeHomepage()
    {
        return $this->render('store/index.html.twig');
    }
}

class HomeController extends AbstractController
{
    /**
     * @Route("/", name="site_home")
     */
    public function homePage()
    {
        return $this->render('site/home/index.html.twig');
    }
}

And here is my nginx configuration:
server {
    listen       80;
    server_name  *.domain.test;
    root       /site/root/public;

    location config bla bla bla;
}

A:
I'm trying this code but is not working. Its always match with
  HomeController. StoreController never matching.

You are using annotation routing, so the routes are loaded alphabetically.
Your home controller will be tried first, and it will match, because you have not put any restrictions on it.
Try explicitly setting the host.
class HomeController extends AbstractController
{
    /**
     * @Route("/", name="site_home", host="domain.test")
     */
    public function homePage()
    {
        return $this->render('site/home/index.html.twig');
    }
}

And when I try this configuration "domain.com" request show to me
  "Welcome to nginx!" page.

I'm not really an nginx expert, but I believe that server_name  *.domain.test; means all subdomains, but exludes the main domain. Try it as server_name  .domain.test;

A: In NGINX configuration you can specify multiple server_name like :
 server_name  example.org  www.example.org;
That should work for you :
server {
    listen       80;
    server_name  *.domain.test domain.test;
    root       /site/root/public;

    location config bla bla bla;
}

http://nginx.org/en/docs/http/server_names.html


text:
Q: Folium in GNS construction and von Neumann algebras The GNS construction allows one to represent a $C^*$-algebra as the algebra of bounded operators on a Hilbert space when a state is fixed, this state being represented as a vector on the Hilbert space. Another state will be represented as a vector on a different Hilbert space. I am trying to find back the usual quantum picture: states are vectors or more generally positive trace class operators on a fixed Hilbert space.
Given a state $\omega$ on the $C^*$-algebra $\mathfrak{A}$, associated to a representation $(\pi_{\omega},\mathcal{H})$, one can define $\omega$-normal states: $\mu$ is an $\omega$-normal state iff there exists a positive trace class operator $\rho$ on $\mathcal{H}$ verifying $\mu(A)=\operatorname{tr}(\rho\pi_{\omega}(A))$ for all $A \in \mathfrak{A}$.
The folium of $\omega$ is the set of $\omega$-normal states, which corresponds basically to states which "live" on the same Hilbert space as $\omega$.
$(\ast)$: One can also show that the folium of a faithful state is *-weak-topology dense among the set of states.
That's the furthest I could get in understanding all this.
What I want is one folium for all states, so I probably need to put some conditions on my states ensemble.
One brute force way to do this is to ask all states to be positive trace class operators so there is a chance they are $\omega$-normal states for some specific $\omega$. von Neumann algebras are duals of trace class operators ensembles, so I get the feeling that at some point one has to take the weak closure of the $C^*$-algebra if we want to achieve this "one folium" goal, but then I can't find any clear explanation of how we do this, and if the positivity condition can't restrict us to something more specific than a von Neumann algebra.
Also, are there any weaker conditions that do the job so we don't need von Neumann algebras? For example using proposition $(\ast)$?

A: It will be rare to find a C*-algebra which has one folium for all states.  Most likely you need to require that it's dual space is norm separable (so you can do it for say subalgebras of compact operators on a separable Hilbert space). It might be equivalent to having a norm separable dual.
For example, if your C*-algebra $A$ contains an element with spectrum equal to $[0,1]$, you'll never find one folium for all states. This is essentially asking for a single measure $\mu$ on $[0,1]$ so that all regular Borel measures are absolutely continuous with respect to $\mu$ (such a measure, of course, doesn't exist).


text:
Q: azure function - Blob input binding Iam new to azure, any help is appreciated
In azure function we can give an input binding as below.
[QueueTrigger("myqueue-items")] string myQueueItem,
    [Blob("samples-workitems/{queueTrigger}", FileAccess.Read)] Stream myBlob,
    ILogger log)

Also, I see few codes where we use the below and they dont add the above lines. Can anyone explain the usage of these both.
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(ContainerName);
BlobClient blobClient = containerClient.GetBlobClient(fileName);

I have tried both the procedures and both of them works fine. I wanted to understand the significance of the usage

A: The first example is using input bindings for Functions. You can think of them like "managed connections". You dont need to worry about how the Blob in that case is being fetched from the storage account. It is abstracted away from you.
However, if you need more control over that, the second one comes into play. You are creating your own BlobClient etc with all the options available. This you could use anywhere, not just with Azure Functions.


text:
Q: Is it a bad idea to use [Char] instead of String in Haskell function type declaration I have just started learning Haskell using "Learn you a Haskell for Great Good".
I am currently reading "Types and Typeclasses" chapter, so my knowledge is pretty .. non-existent.
I am using Sublime Text 2 with SublimeHaskell package which builds/checks file on every save.
The problem: I'm trying to make function type declaration like this:
funcName :: [Char] -> [Char]

I'm getting this warning:

Warning: Use String
    Found:
      [Char] -> [Char]
    Why not:
      String -> String
Build FAILED

Can you explain to me why is it a bad idea to use Char array instead of String or give me a link to an explanation of possible repercussions etc. I've googled and found nothing.
P.S. I'm a C# developer, I understand the difference between char array and strings in c-like languages.

A: String is nothing more than a type alias for [Char], so there is no practical between the two - it's simply a matter of readability.

A: You seem to be running HLint on your code automatically, and treating any HLint warnings as fatal errors. As the HLint author says "Do not blindly apply the output of HLint". String and [Char] are exactly the same, as everyone says, it's a question of which looks nicer. I would tend to use String if I'm operating on contiguous lists of characters I want to treat as a block (most of the time), and explicitly use [Char] when the characters don't make sense combined in a run (far rarer). HLint divides all hints into error (fix) and warning (think), so perhaps it might be best only to build fail on error hints.

A: Somewhere in the base library you will find this definition:
type String = [Char]

which says that String and [Char] are exactly the same thing.  Which of the two you choose is a documentation choice.  I often define type aliases like this:
type Domain = ByteString
type UserName = Text

It's a good idea to use types for documentation.
Also as an important side note, [Char] is not the type for character arrays, but character lists.  Since there are also actual array types, the distinction is important!


text:
Q: Get the actual value use by MySQL after a mysqli_stmt_bind_param I have an web application working. I use that piece of code that do work:
$dbConnection = getDbConnection();
    $stmt =  mysqli_prepare( $dbConnection, $SQLStatement);
    $bindParamArray = array_merge(array($stmt, $SQLBindString), $bindValueArray );
    call_user_func_array ( mysqli_stmt_bind_param , $bindParamArray );

    if( mysqli_stmt_execute($stmt) ) {
        $ret = mysqli_insert_id ($dbConnection);
        mysqli_stmt_close($stmt);
        $dbConnection->close();
    }else{
        //echo "

statement : ".mysqli_stmt_error($stmt);
        mysqli_stmt_close($stmt);
        $dbConnection->close();
    }

Well I'd like to know how php is casting the value send to db when binding value, and I'm looking to a way to get the binded actual value in the db before statement is executed to check if there's differences between the original values and the binded values.
For example if you try to bind an empty string inside an INTEGER it will put the value 0 or if you put the date 2013-15-15 (a non-exiting date obviously) it wil cast it to 0000-00-00 and it's definitly not the behaviour I'm expecting.
Is there any to accomplish what I want ?


text:
Q: I am getting this error: stream_socket_sendto() ... no address was supplied I am getting this error

stream_socket_sendto(): A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

When I try to upload an image of size 2.72 MB (2,857,082 bytes) although I tried to change:
memory_limit
upload_max_filesize
post_max_size

to the max size look at this snapshot https://imgur.com/wmg3t39

A: You set upload_max_filesize and post_max_size like "24M" for 24 megabytes and restart your server services again then check
I have one more suggestion: make sure that you have proper permissions to the folder with temporary uploads.


text:
Q: Airflow: retry task with different parameter or settings I'm executing a query that sometimes will fail because of the setting of one parameter.
To set it on the 'safe' side is not desired, as this greatly affects performance in a negative way.
So I'd love to retry the same task on failure, but with a changed value for this parameter.
Is there a 'native' way of doing this in Airflow?
Or should I use the 'try: except:' way and work around this?

A: Having example code would help answer the question. But here's a generic example:
import datetime

from airflow.decorators import dag, task
from airflow.models import TaskInstance
from airflow.operators.bash import BashOperator

@dag(schedule_interval=None, start_date=datetime.datetime(2023, 1, 1))
def so_75553740():
    @task(retries=5, retry_delay=datetime.timedelta(seconds=0))
    def example(task_instance: TaskInstance = None):
        print(f"This is attempt #{task_instance.try_number}")
        if task_instance.try_number < 3:
            raise Exception("let's retry!")

    example()

    BashOperator(
        task_id="bash_example",
        retries=5,
        retry_delay=datetime.timedelta(seconds=0),
        bash_command="echo 'This is attempt #{{ task_instance.try_number }}' && exit {{ 1 if task_instance.try_number < 3 else 0 }}",
    )

so_75553740()

Using templated variables and Jinja templating, you can modify the behavior depending on the try_number. try_number is an attribute on task_instance, which is a variable available at runtime. See the full list of variables available at runtime here.
If running a PythonOperator or @task decorator, you can fetch task_instance.try_number as a Python object and use that in your Python code.
However, if using an operator where you cannot supply arbitrary Python code, you can apply Jinja templating to modify behavior at runtime. Here, I used {{ 1 if task_instance.try_number < 3 else 0 }} to define the exit code based on the try number, but you can make this more complex (i.e. change a query) based on your needs.


text:
Q: How do I use NSConditionLock? Or NSCondition I am try to make one function wait for another, and I would like to use NSCondionLock in order to accomplish this. I am not asking for help, but really hoping someone could show me a decent tutorial or example to explain NSConditionLock, or possibly suggest a better method.

A: EDIT: as @Bonshington commented, this answer refers to NSCondition (as opposed to NSConditionLock):
- (void) method1 {

    [myCondition lock];
    while (!someCheckIsTrue)
        [myCondition wait];

    // Do something.

    [myCondition unlock];
}

- (void) method2 {

    [myCondition lock];

    // Do something.

    someCheckIsTrue = YES;
    [myCondition signal];
    [myCondition unlock];
}

The someCheckIsTrue can be anything, it could be a simple BOOL variable or even something like [myArray count] == 0 && color == kColorRed, it doesn't matter. It only matters that in one method you check for a condition while you have the lock and in another method you make changes that can make the condition become true also while having the lock. The magic is the wait and signal part: the wait actually unlocks the lock and reacquires it after some other thread called signal.

A: Swift 5 version of @vilanovi answer from Playground:
let myCondition = NSCondition()

var someCheckIsTrue = false

func method1() {
    print("STARTING METHOD 1")

    print("WILL LOCK METHOD 1")
    myCondition.lock()
    print("DID LOCK METHOD 1")

    while (!someCheckIsTrue) {
        print("WILL WAIT METHOD 1")
        myCondition.wait()
        print("DID WAIT METHOD 1")
    }

    print("WILL UNLOCK METHOD 1")
    myCondition.unlock()
    print("DID UNLOCK METHOD 1")

    print("ENDING METHOD 1")
}

func method2() {
    print("STARTING METHOD 2")

    print("WILL LOCK METHOD 2")
    myCondition.lock()
    print("DID LOCK METHOD 2")

    someCheckIsTrue = true

    print("WILL SIGNAL METHOD 2")
    myCondition.signal()
    print("DID SIGNAL METHOD 2")

    print("WILL UNLOCK METHOD 2")
    myCondition.unlock()
    print("DID UNLOCK METHOD 2")

    print("ENDING METHOD 2")
}

DispatchQueue.global().async {
    method1()
}

DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.5) {
    method2()
}

A: For those that want a sample test class here I post what I did to play around and understand how NSCondition works.
// --- MyTestClass.h File --- //
@interface MyTestClass

- (void)startTest;

@end

// --- MyTestClass.m File --- //
@implementation MyTestClass
{
    NSCondition *_myCondition;
    BOOL _someCheckIsTrue;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        _someCheckIsTrue = NO;
        _myCondition = [[NSCondition alloc] init];
    }
    return self;
}

#pragma mark Public Methods

- (void)startTest
{
    [self performSelectorInBackground:@selector(_method1) withObject:nil];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(5);
        [self performSelectorInBackground:@selector(_method2) withObject:nil];
    });
}

#pragma mark Private Methods

- (void)_method1
{
    NSLog(@"STARTING METHOD 1");

    NSLog(@"WILL LOCK METHOD 1");
    [_myCondition lock];
    NSLog(@"DID LOCK METHOD 1");

    while (!_someCheckIsTrue)
    {
        NSLog(@"WILL WAIT METHOD 1");
        [_myCondition wait];
        NSLog(@"DID WAIT METHOD 1");
    }

    NSLog(@"WILL UNLOCK METHOD 1");
    [_myCondition unlock];
    NSLog(@"DID UNLOCK METHOD 1");

    NSLog(@"ENDING METHOD 1");
}

- (void)_method2
{
    NSLog(@"STARTING METHOD 2");

    NSLog(@"WILL LOCK METHOD 2");
    [_myCondition lock];
    NSLog(@"DID LOCK METHOD 2");

    _someCheckIsTrue = YES;

    NSLog(@"WILL SIGNAL METHOD 2");
    [_myCondition signal];
    NSLog(@"DID SIGNAL METHOD 2");

    NSLog(@"WILL UNLOCK METHOD 2");
    [_myCondition unlock];
    NSLog(@"DID UNLOCK METHOD 2");
}

@end

// --- Output --- //
/*
2012-11-14 11:01:21.416 MyApp[8375:3907] STARTING METHOD 1
2012-11-14 11:01:21.418 MyApp[8375:3907] WILL LOCK METHOD 1
2012-11-14 11:01:21.419 MyApp[8375:3907] DID LOCK METHOD 1
2012-11-14 11:01:21.421 MyApp[8375:3907] WILL WAIT METHOD 1
2012-11-14 11:01:26.418 MyApp[8375:4807] STARTING METHOD 2
2012-11-14 11:01:26.419 MyApp[8375:4807] WILL LOCK METHOD 2
2012-11-14 11:01:26.419 MyApp[8375:4807] DID LOCK METHOD 2
2012-11-14 11:01:26.420 MyApp[8375:4807] WILL SIGNAL METHOD 2
2012-11-14 11:01:26.420 MyApp[8375:4807] DID SIGNAL METHOD 2
2012-11-14 11:01:26.421 MyApp[8375:4807] WILL UNLOCK METHOD 2
2012-11-14 11:01:26.421 MyApp[8375:3907] DID WAIT METHOD 1
2012-11-14 11:01:26.421 MyApp[8375:4807] DID UNLOCK METHOD 2
2012-11-14 11:01:26.422 MyApp[8375:3907] WILL UNLOCK METHOD 1
2012-11-14 11:01:26.423 MyApp[8375:3907] DID UNLOCK METHOD 1
2012-11-14 11:01:26.423 MyApp[8375:3907] ENDING METHOD 1
*/

A: NSConditionLock example program.
#import <Foundation/Foundation.h>

#define IDLE 0
#define START 1
#define TASK_1_FINISHED 2
#define TASK_2_FINISHED 3
#define CLEANUP_FINISHED 4

#define SHARED_DATA_LENGTH 1024 * 1024 * 1024

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSConditionLock *lock = [[NSConditionLock alloc] initWithCondition:IDLE];
        char *shared_data = calloc(SHARED_DATA_LENGTH, sizeof(char));

        [NSThread detachNewThreadWithBlock:^{
            [lock lockWhenCondition:START];

            NSLog(@"[Thread-1]: Task 1 started...");
            for (size_t i = 0; i < SHARED_DATA_LENGTH; i++) {
                shared_data[i] = 0x00;
            }
            [lock unlockWithCondition:TASK_1_FINISHED];
        }];

        [NSThread detachNewThreadWithBlock:^{
            [lock lockWhenCondition:TASK_1_FINISHED];
            NSLog(@"[Thread-2]: Task 2 started...");
            for (size_t i = 0; i < SHARED_DATA_LENGTH; i++) {
                char c = shared_data[i];
                shared_data[i] = ~c;
            }
            [lock unlockWithCondition:TASK_2_FINISHED];
        }];

        [NSThread detachNewThreadWithBlock:^{
            [lock lockWhenCondition:TASK_2_FINISHED];

            NSLog(@"[Thread-3]: Cleaning up...");
            free(shared_data);
            [lock unlockWithCondition:CLEANUP_FINISHED];
        }];

        NSLog(@"[Thread-main]: Threads set up. Waiting for 2 task to finish");
        [lock unlockWithCondition:START];
        [lock lockWhenCondition:CLEANUP_FINISHED];
        NSLog(@"[Thread-main]: Completed");
    }
    return 0;
}


text:
Q: GWT Problem with MySQL Connection I am working on a GWT project in which I need to make some MySQL queries. I have handled RPC properly and in the server-side I am trying to make a mysql connection but am running into an exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance_(Runtime.java:112)
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance(Runtime.java:120)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2412)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
    at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:792)
    at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance_(Runtime.java:112)
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance(Runtime.java:120)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
.
.
.
more
.
.
.
I created a very simple java class to test out my code to confirm that my connection syntax and use is proper, and have confirmed that syntax is not a problem because with the very same code in a simple only main method java app I can create a connection and query the database properly. I have made sure to have mysql-connector-java-5.1.16-bin.jar in the classpath as well as the /lib folder in the WEB-INF folder.
Here is the class that I am using in order to create a connection:
public class DB_Connection {
protected Connection getConnection() {
      Connection conn = null;
      try {
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         conn = DriverManager.getConnection("jdbc:mysql:///",
                                            "",
                                            "");
      }
      catch (Exception ex)
      {
         ex.printStackTrace();
      }
  return conn;

}
}
public class Login extends DB_Connection {
public User getUser(String email) {
      User user = new User();
      user.setUserEmail(email);
      String query = "";
  try {
     Connection conn = getConnection();
     Statement statement = conn.createStatement();
     ResultSet result = statement.executeQuery(query);
     while(result.next()) {
        user.setUserId(result.getInt("rvuser_id"));
        System.out.println(user.getUserId());
     }
  }
  catch (Exception ex)
  {
     ex.printStackTrace();
  }

  return user;

}
It seems my problem happens all the way at the beginning in DB_Connection. Does anyone know what is making this happen? It is strange to me, because as a standalone the code works fine.
Another thing I just realized that I am at home now and don't even have access to that database server as it is on a local network and I am not connected through VPN. So it must be failing somehow before it even attempts to make the connection.
Thanks!

A: com.google.appengine ..
Does it means you are deploying on Google App Engine?
If so, MySQL,JDBC and many other things are restricted.


text:
Q: Specialization of operators inside template class between objects of different specialization of that class I have the following problem/question:
Suppose that i have a template class Couple which have two attributes x and y of type xobject.
I can easily define the sum between Couple of the same class simply defining the sum element by element, if it is defined the sum of the template object, i.e.:
Couple operator+(Couple in)
{
 return Couple((*this).x+in.x,(*this).y+in.y);
}

With this implementation i can compute the sum between Couple<int> element.
I don't exactly understand how i can define the sum between Couple<int> and Couple<something> inside that class.
The problem is that i cannot specialize the sum inside the class between classes that are not yet implemented, i.e., i cannot write
Couple<'int'> Couple<'int'>::operator+(Couple<'something'>)

inside the Couple class.
Do you have any idea how to do this?
My first idea was to use a second template parameter inside the operator but the results was not so good since doing this i allow only the one verse sum and not in both verse.
I hope that i explained the problem in a decent way.

A: You can use a friend template function:
template <typename T>
class Couple
{
private:
    T x, y;

public:
    Couple(T xx, T xy) : x{xx}, y{xy} { }

    template <typename T0, typename T1>
    friend Couple<std::common_type_t<T0, T1>>
    operator+(const Couple<T0>& x0, const Couple<T1>& x1);
};

template <typename T0, typename T1>
Couple<std::common_type_t<T0, T1>>
operator+(const Couple<T0>& x0, const Couple<T1>& x1)
{
    return {x0.x + x1.x, x0.y + x1.y};
}

I am using std::common_type_t to compute a type that suitable for the T0 + T1 addition.
coliru example

You may not need friend if you expose getters for x and y, as SebTu mentioned in the comments.


text:
Q: Test for device using udev sysname I'm writing my first ever C program in Ubuntu and it involves detecting when the AC adapter or Battery on my laptop see events (through udev_monitor). So far, I'm able to log to the console when the power situation changes using something like this while snippet:
while (1) {
    dev = udev_monitor_receive_device(mon);
    if (dev) {
        printf("\n[INFO] Got Device\n");
        printf(" [INFO] Device Name: %s\n", udev_device_get_sysname(dev));
...

And that's great! When I plug or unplug my laptop I get that logged to the console. However, what I'm failing to grok is how to conditionally test using these same functions.
For instance, this is never true:
if (udev_device_get_sysname(dev) == "ADP1") { ... }

I'm unsure how to properly test this. Obviously it prints as a string (array of characters?) when printf() and %s are used.
EDIT: The values logged to the consle from the function called are ADP1 for the adapter and BAT0 for the battery - which correlates to their entries in the /sys/class/ directory.

A: In C you compare strings using one of the string comparison routines, such as strcmp or strncmp. If you compare them using == you're only comparing the values of the pointers, which will not be the same.
So for the code checking the sysname is incorrect, as the pointer comparison will never be true. It should be changed to something like:
if (strcmp(udev_device_get_sysname(dev), "ADP1") == 0) { … }

which causes it to compare the strings, rather than the pointer values.


text:
Q: Delphi XE Database component that can cache query result I'm working on a Delphi XE-based desktop program with database, and I have noticed that it will be too big for the program to load an entire table before display it to user per page every time they want to browse for products, but it will be also inefficient for the program to load and reload each page as the user browse like in browser. I want to ask, is there any way for Delphi to cache a query call result, so that for the same query, the database component doesn't query again to the database, but return for the cache instead?
This is for scenario like this:
The program loads the first 20 lines for page 1 from database using query.
SELECT * FROM tbl_product_master LIMIT 0,20;

Then the user hit next page. The program loads the next 20 lines for page 2 from database using query.
SELECT * FROM tbl_product_master LIMIT 21,40;

Then the user hit previous page. The program attempts to load the first 20 lines again.
SELECT * FROM tbl_product_master LIMIT 0,20;

but because the database component knows I have already call this query before, and it already saves the result in the cache, it immediately returns the result from the cache, not firing the query again to the database, thus resulting in faster program.
Is there such a component or configuration exist for Delphi XE? I just need a nudge toward the right direction. Thank you.

A: (This isn't exactly an answer to your q, but it may provide some usual information and I've included some code which may help inform your implementation).
You didn't mentioned which server back-end you are using, nor what Delphi dataset
type you're using to get the data from the server.  Others have mentioned TClientDataSet
in comments and that is certainly a good place to start if you're interested in client-side
cacheing especially considering you can use TDataSetFields to nest Detail table data
in the data received by the CDS which is handling the Master.
A thing to bear in mind is that early on (around Delphi 5) the TClientDataSet got a bit of a reputation for having access performance which falls off a cliff once you get into the thousands of rows, though exactly where seems to depend on the number of fields and the record size, amongst other things.   The CDS code and Midas.Lib, which it depends upon, have been improved over the years and this has reduced but not entirely eliminated this problem.
Out of interest I wrote a little testbed to demonstrate this possible performance issue
and compare its performance with using the TAdoQuery which gets the CDS data from my server
to save and load its own data to/from a local disk file.  The code I used is shown below and
could certainly be improved and made more rigorous.
Broadly it retrieves a certain number of rows from a server table using a TAdoQuery,
saves and loads the data from a local disk file, then transfers the data to the CDS using
a TDataSetProvider, and saves and loads the CDS data, first with an index on the data's PK
and a second time without (because I wanted to see if the CDS could use the PK index to
increase the CDS's LoadFromFile performance - it didn't).
Here are the results.  Please take them with a large "pinch of salt" because I'm sure others
would get different results.  My point is, you should investigate this yourself, in
your own environment and using your own data and dataset components of choice.
Results
          A      B   C   D     E         F        G      H   I
  Recs  5000    140  63  93   967   0.0001934     952    15  31
  Recs  10000   172 125 156  2574   0.0002574    2355    47  47
  Recs  15000   250 171 219  4508   0.0003005    4477    63  62
  Recs  20000   359 218 297  7082   0.0003541    7129    78  94
  Recs  25000   390 327 343  9985   0.0003994    9968    94 109
  Recs  30000   531 343 421 13401   0.0004467   13572   125 140

A = Number of records
B = Open AdoQuery  (milliseconds)
C = Save AdoQuery to file (ms)
D = Load AdoQuery from file (ms)
E = Transfer AdoQuery data to CDS via DataSetProvider with PK index on CDS (ms)
F = E/A, i.e. transfer time per record
G = Transfer AdoQuery data to CDS via DataSetProvider without PK index on CDS (ms)
H = CDS save to disk file (ms)
I = CDS load from disk file (ms)
Btw, this data had a RecordSize of 241 and 45 fields
Comments/Observations

*

*The ClientDataSet is quite a lot faster than the AdoQuery in saving & loading data in a local disk.  Both sets of times vary roughly linearly with the number of records.

*The AdoQuery's Open times are roughly linear with number of records retrieved.

*The Adoquery-> ClientDataSet transfer time varies a lot worse than linearly with the number of records, which is what I meant by "off a cliff".  But as long as you restrict yourself to a few thousand records, the ClientDataSet works just fine.  You need to find out what "few" means for your application.

*Increasing the number of records by a factor or 2, from 5000 to 10000 makes the transfer take just over twice the time, while increasing it by a factor of 5, to 30000, multiplies the time by a factor of over 14.

*If I repeat the tests with cbSelectPKOnly.Checked, so that the CDS is only retrieving an integer field, the AdoQuery->ClientDataSet transfer times are quite a bit faster, so you can move the "cliff" by retrieving fewer data columns.

*The code was written in D7 and tested with that (without Andreas Hausladen's admirable "speed fix" for Midas) and XE4.  The results are for XE4.

*The host machine included the Sql Server and had all SSD disks, Win7 64-bit.
Code
const
  scPKName = 'ApcsID';
  scSql = 'select top %d %s from btapcs'; // order by apcsid';

function TForm1.GetTestSql(Count : Integer) : String;
var
  S : String;
begin
  if cbSelectPKOnly.Checked then
    S := scPKName
  else
    S := '*';
  Result := Format(scSql, [Count, S]);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Count : Integer;
begin
   Count := 5000;
   while Count <= StrToInt(edMaxRecs.Text) do begin
     TestOpenAdoQuery(Count);
     Inc(Count, 5000);
     Application.ProcessMessages;
   end;
end;

procedure TForm1.Log(const Msg : String);
begin
  Memo1.Lines.Add(Msg);
end;

procedure TForm1.TestOpenAdoQuery(Count : Integer);
type
  TDataOperation = (doOpenQuery, doSaveQueryData, doLoadQueryData, doGetCDSData,
    doSaveCDSData, doLoadCDSData);
var
  Msg : String;
  AdoFN,
  CdsFN : String;
  Query : TAdoQuery;
  DSP : TDataSetProvider;
  CDS : TClientDataSet;

  procedure PerformOperation(Op : TDataOperation; var Msg : String);
  var
    T1,
    T2 : Integer;
  begin
    T1 := GetTickCount;
    case Op of
      doOpenQuery : begin
        Query.Sql.Text := GetTestSql(Count);
        Query.Open;
        Msg := Msg + Chr(9) + IntToStr(Query.RecordCount);
      end;
      doSaveQueryData : begin
        Query.SaveToFile(AdoFN);
      end;
      doLoadQueryData : begin
        Query.LoadFromFile(AdoFN);
      end;
      doGetCDSData : begin
        CDS.Open;
      end;
      doSaveCDSData : begin
        CDS.SaveToFile(CdsFN, dfBinary);
      end;
      doLoadCDSData : begin
        CDS.LoadFromFile(CdsFN);
      end;
    end; { case }
    T2 := GetTickCount;
    Msg := Msg + Chr(9) + IntToStr(T2 - T1);
  end;

begin
  //  This proc uses a TAdoConnection1 on the form, but uses a temporary AdoQuery,
  //  DataSetProvider and TClientDataSet to avoid state being carried over
  //  from one call to the next.

  Screen.Cursor := crSqlWait;
  Update;
  try
    Query := TAdoQuery.Create(Nil);
    Query.CursorType := ctKeySet;
    Query.CursorLocation := clUseClient;
    Query.Connection := AdoConnection1;
    if cbDropConnectionBetweenRuns.Checked then begin
      AdoConnection1.Connected := False;
    end;

    AdoFN := IncludeTrailingPathDelimiter(GetEnvironmentVariable('TEMP'))+ 'ado.dat';
    CdsFN := IncludeTrailingPathDelimiter(GetEnvironmentVariable('TEMP'))+ 'cds.cds';

    Msg := 'Recs ';
    Query.Sql.Text := GetTestSql(Count);
    PerformOperation(doOpenQuery, Msg);

    Query.Connection := Nil;

    PerformOperation(doSaveQueryData, Msg);
    PerformOperation(doLoadQueryData, Msg);

    DSP := TDataSetProvider.Create(Self);
    DSP.Name := 'MyProvider';
    DSP.DataSet := Query;
    CDS := TClientDataSet.Create(Self);

    DSP.DataSet := Query;
    CDS.ProviderName := DSP.Name;

    CDS.IndexFieldNames := scPKName;
    PerformOperation(doGetCDSData, Msg);

    CDS.Close;
    CDS.IndexFieldNames := '';
    PerformOperation(doGetCDSData, Msg);
    PerformOperation(doSaveCDSData, Msg);

    CDS.Close;

    PerformOperation(doLoadCDSData, Msg);

    Log(Msg);

  finally
    Query.Free;
    DSP.Free;
    CDS.Free;
    Screen.Cursor := crDefault;
  end;
end;

A: There are different ways in Delphi to limit the number of records loaded by a query - it also depends on what database you're using and what data access components.
Some databases will be able to return you only a given number of records until you ask for more, if the Delphi data access library you use also supports that feature and can set it. Some can also cache query results, and avoid to re-execute a query if possible. Already fetched record will be retained.
The TClientDataset + Provider combo offers a similar functionality, independent from the database. It can load data incrementally, and it will cache already fetched rows. It requires a little more code to work, though.
In a native Windows application, you usually don't need the "paging" metaphor web UI uses, because it is far easier to use some control that can scroll up and down while caching data in local memory or disk.
But be aware that:

*

*If you don't limit the result set at the SQL level, the database may still need to generate the whole result set. The query could run slower, and more server resources are used.

*Some controls may load the whole dataset anyway. For example, Developer Express grids usually load the whole dataset to enable features like sorting, filtering and grouping locally, unless you set them to not do it.

*If you try to get the number of records, and don't do it in a separate SELECT COUNT query or if the db library doesn't return it somehow, the TDataset component may fetch all rows just to get the count.


text:
Q: How do I describe a bridge table to Ebean? Lets say I have these tables:

ORDER: id
ITEM: id
ORDER_ITEM: order_id, item_id

The table: ORDER_ITEM is a bridge table between ORDER and ITEM.
How do I describe this threesome to Ebean?
I would prefer not to use raw SQL so that I can still create and update these entities.
UPDATE Sat Nov  9 02:32:40 UTC 2013
Ok, lets make this problem harder and more representative of my actual situation. The column names dont fit the convention:

ORDER: order_number
ITEM: item_number
ORDER_ITEM: my_order, my_item

A: You don't have to create special bridge table yourself unless you want to have other fields there except foreign keys.
In Order class you should define field:
@ManyToMany
public List<Item> items;

In Item class:
@ManyToMany(mappedBy = "items")
public List<Order> orders;

And Ebean will generate bridge table for you.
And moreover:
You can have asymmetric relationship types between two classes:
@ManyToMany
@JoinTable(name="Order_Item")
public List<Item> items;

and
@ManyToOne
public Order order;

in case when order is an optional field in Item and you don't want to have a lot of empty fields in Item table.
UPDATE:
This will work for you. All the table and column names are now explicitly named by annotations:
@Entity
@Table(name="ITEM")
public class Item extends Model {
    @Id
    @Column(name="item_number")
    public Integer id;

    @ManyToMany(mappedBy = "items")
    public List<Order> orders;
}

and
@Entity @Table(name="ORDER") public class Order extends Model {
    @Id
    @Column(name="order_number")
    public Integer id;

    @ManyToMany
    @JoinTable(name="ORDER_ITEM",
            joinColumns=@JoinColumn(name="my_order",referencedColumnName = "order_number"),
            inverseJoinColumns = @JoinColumn(name="my_item", referencedColumnName="item_number"))
    public List<Item> items; }

The code is here: https://github.com/cosmolev/BridgeTable/tree/master/app/models


text:
Q: How to play any type of m8u3 live tv streaming on android? I could play some of the live tv streams on my app, but I failed to play some of them.
on VLC play I can play this: https://raw.githubusercontent.com/taodicakhia/IPTV_Exception/master/channels/af/tolotv.m3u8
and also this: http://51.210.227.142/hls/stream.m3u8
but in the android app, I can only play this one: http://51.210.227.142/hls/stream.m3u8
I tried a lot but I couldn't figure out how to play the first one: https://raw.githubusercontent.com/taodicakhia/IPTV_Exception/master/channels/af/tolotv.m3u8
This is my code:
private void playVideo() {
    try {
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        MediaController mediaController = new MediaController(AfghanistanTvAct.this);
        myVideoView.setMediaController(mediaController);
        Uri videoURI = Uri.parse(url);
        myVideoView.setVideoURI(videoURI);
        myVideoView.requestFocus();
        myVideoView.setOnPreparedListener(mp -> myVideoView.start());

    } catch (Exception e) {
        Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

A: If you look at the response from the servers in a browser inspector you will see that the MIME type, or content type, in the video that plays is:

*

*application/vnd.apple.mpegurl

while the MIME type of the video that does not play is:

*

*text/plain; charset=utf-8

I suspect this may be causing your issue.
Note that the video which does not play is also a master playlist - i.e. it contains links to other m3u8 files.
This is hard to verify as online HLS Analyser's and some test players seem to be able to handle this and still request the individual video streams, which do have the video MIME type, and will likely play for you if requested individually.


text:
Q: Limit of summation of trigonometric series Let $S_n=\sum_{k=1}^n \sin(k\theta)$.
Prove that:
$$\lim\limits_{n \to \infty} \sum_{k=1}^n \frac {S_k} n=\frac 1 2 (\cot( \theta/2))$$

A: If $e^{i\theta} \neq 1$ ($\theta \neq 0 \, (\textrm{mod } 2\pi)$), we have:
$$S_n=\sum_{k=1}^n \sin(k\theta)=\Im{\sum_{k=1}^n e^{ik\theta}}=\sin(\frac{n+1}{2}\theta)\frac{\sin(\dfrac{n}{2}\theta)}{\sin(\theta/2)}$$
Then $$\sum_{n=1}^N S_n=\dfrac{1}{\sin(\theta/2)}\sum_{n=1}^N \sin(\dfrac{n}{2}\theta)\sin(\frac{n+1}{2}\theta) = -\dfrac{1}{\sin(\theta/2)}\sum_{n=1}^N \dfrac{1}{2}(\cos(\dfrac{n+1}{2}\theta)-\cos(\theta/2)) $$
$$\sum_{n=1}^N S_n=\dfrac{N}{2\tan(\theta/2)}-\dfrac{1}{2\sin(\theta/2)}\sum_{n=1}^N\cos(\dfrac{n+1}{2}\theta)$$
And as previously you can compute
$$\sum_{n=1}^N\cos(\dfrac{n+1}{2}\theta)=\Re \sum_{n=1}^{N} e^{i\theta n/2}e^{i\theta/2}=\cos((N/2+1)\theta)\dfrac{\sin(N\theta/2)}{\sin(\theta/2)}$$
which is bounded by $1/\sin(\theta/2)$.
Finally we find that $$\dfrac{1}{N}\sum_{n=1}^N S_n \to \dfrac{1}{2}\cot(\theta/2) $$
And if $e^{i\theta}=1$, then $S_n=0$ and the sum converges to $0$ which is not $\cot(0)/2$...


text:
Q: Webbrowser Find Previous (text) I am trying to implement search routines: Find Next and Find Previous in Webbrowser. I know that there is Build-in Find dialog inside, but I do not want to use it. Instead I am trying hard to write my own routines, but I can not get through. Following code implements "Find next" nicely:
using mshtml;

....

private void toolStripButton5_Click(object sender, EventArgs e)
        {
            IHTMLDocument2 htmlDocument = WB.Document.DomDocument as IHTMLDocument2;
            IHTMLSelectionObject sel = (IHTMLSelectionObject)htmlDocument.selection;
            IHTMLTxtRange tr = (IHTMLTxtRange)sel.createRange() as IHTMLTxtRange;
            string s = toolStripTextBox1.Text;
            tr.collapse(false);
            tr.findText(s, 1, 0); // positive value, should search forward, negative backward
            tr.select();
        }

I am totaly helpless making "Find previous" routine. Can any genius forge it? (it will be probably very similar to that above).
Thanks very much

A: For "Find previous" routine use the same code with 2 modifications:
1) change argument of tr.collapse from false to true;
2) change the second parameter of tr.findText from 1 to -1.
So these line will be the following:
tr.collapse(true); // use true to move caret at the beginning of the current selection
tr.findText(s, -1, 0); // positive value, should search forward, negative backward

A: IHTMLTxtRange tmprange;
    private void Find(int Direction, bool Collapse)
        {
        IHTMLDocument2 htmlDocument = browser.Document.DomDocument as IHTMLDocument2;
        IHTMLSelectionObject sel = (IHTMLSelectionObject)htmlDocument.selection;
        IHTMLTxtRange tr = (IHTMLTxtRange)sel.createRange() as IHTMLTxtRange;
        string s = textBoxFindData.Text;
        if (tmprange == null)
        {
            tr.collapse(Collapse);
            tmprange = tr;
            tr.findText(s, Direction, 0); // positive value, should search forward, negative backward
            if (tr.text == null)
            {
                MessageBox.Show("Can not find string " + "[" + s + "]", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            tr.select();
        }
        else
        {
            tmprange.collapse(Collapse);
            tmprange.findText(s, Direction, 0); // positive value, should search forward, negative backward
            if (tmprange.text == null)
            {
                MessageBox.Show("Can not find string " + "[" + s + "]", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            tmprange.select();

        }
    }

    private void buttonPrevious_Click(object sender, EventArgs e)
    {
        Find(-1, true);
    }


text:
Q: How to remove ligatures from a font using FontForge I have a font with some ligature errors in it. This is causing problems in my Android application. I want to just remove the ligatures. How do I do that in FontForge?
This question is related but it is going the other way.

*

*Fontforge Scripting how to add ligatures for a glyph

A: In FontForge go to Element > Font Info > Lookups > GSUB. You should be able to select a ligature table there. Then you can click Delete to delete all the ligatures or Edit Data to choose which ligatures to delete.

After pressing Edit Data you can select specific ligatures. Click Delete to remove them.


text:
Q: Is there a one-step type conversion from String to Vec? I have a file containing prime numbers that I'm unpacking into a u32 vector. I'm curious if I can do this in one step. If I unpack contents into a str vector, then an u32 vector, everything's dandy.
If I try to move everything into a u32 vector as I try to do in
v_int2, I get the error that
|&x| doesn't have a known size at compile time.
My current understanding is that &str has a known size at compile time, since &str are written into the binary. Skipping this step means I'm parsing from String to u32, and I need to inform the compiler about something having to do with the size of my elements. I'm not aware of a way around this, though I'm new in Rust town.
let mut file = File::open("first10kprimes.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;

let v_str = contents.split_whitespace().collect::<Vec<&str>>(); // I just discovered I could do that typing after collect, was a lil jazzed
let v_int: Vec<u32> = v_str.iter().map(|&x| x.parse::<u32>().unwrap()).collect();

let v_int2: Vec<u32> = contents
    .split_whitespace()
    .map(|&x| x.parse().unwrap())
    .collect();


text:
Q: Data Storage record not found Freshdesk I´m trying to use Data Storage functionality of Freshdesk and it returns an error.
I´m following this example.
My code to store the data is:
var ticket = domHelper.ticket.getTicketInfo().helpdesk_ticket;
var dataTicket = {
   'ticketId': ticket.display_id,
   'osNumber': idOS
};
var dbKey = "ticket:" + ticket.display_id;
this.$db.set(dbKey, dataTicket).done(function(data) {
     if(data.Created) {
          console.log("Dados de OS salvos com sucesso.");
     }
}).fail(function(errorData) {
     alert("Falha ao salvar dados de OS.");
});

This code works fine. To retrieve that data, I'm using the code below:
var ticket = domHelper.ticket.getTicketInfo().helpdesk_ticket;
var dbKey = "ticket:" + ticket.display_id;
this.$db.get(ticket.display_id).done(function(data) {
     self.loadData(data);
}).fail(function(errorData) {
     console.log("Falha ao recuperar dados de OS.");
});

The key to retrieve the data is the same that I use to store that data, but it always enter in fail function. It tells me that there isn't data (return 404 error of the API).

A: I´ve noticed that my key was different when I've tried to retrieve the data.
I've fixed the problem using it:
var dbKey = "ticket:" + ticket.display_id;
this.$db.get(dbKey).done(function(data) {
     self.loadData(data);
});


text:
Q: error: Cannot find form control with name: CreatedOn in Angular When I set the response value to FormGroup varriable (programTypeForm) using  this.programTypeForm.setValue(programType) then I got the error
"Cannot find form control with name: CreatedOn." in Subscriber.js file

this.programTypeForm = this.fb.group({
            VersionNumber:[null],
            ProgramTypeID: [null],
            ProgramTypeName: [null, Validators.required],
            ProgramTypeEnglishName: [null, Validators.required],
            OrganizationID: [null],
            OrganizationHierarchyID: [null],
            LanguageID: ["Asdf"],
            UserID: [11],
            CurrencyID:["Asdasd"]
        });

 if(this.programTypeId>0)
       {
        //  alert(this.programTypeId);
         this._userService.get("ProgramType/getProgramTypeDetailById/" + this.programTypeId)
         .subscribe(programType => {
            alert(programType.VersionNumber);
            this.programTypeForm.setValue(programType);
            console.log(programType);

         },
         error => this.msg = <any>error);
       }

A: As mentioned in comments, your incoming response seems to have  property CreatedOn, which is not included in your form, thus the error. If you want to only pick specific properties from your response, you can do that by modifying your setValue() to something like this:
this.programTypeForm.setValue({
  VersionNumber: programType.VersionNumber, // here assuming the propertynames match...
  ProgramTypeID: programType.ProgramTypeID,
  // ... rest omitted
});

A: You can use patchValue not setValue. like this:
this.programTypeForm.patchValue(programType);


text:
Q: how can I make my image more visible on mobile I have used bootstrap for the layout, however when you view this page on a mobile device the overlaid text seems to hide most of the image, I have tried a couple of different things like media queries.
I have also added in some media queries for the website in general, which has helped the text to stay in the box but still is covering a large majority of the image.

/* CONTACT Page */

.somesection {
  margin-top: 50px!important;
}

body {
  font-size: 16px;
  font-family: raleway;
}

img {
  max-width: 100%;
}

h3 {
  font-size: 18px;
}

.overlay-text {
  font-size: 16px;
  width: 50%;
  /*important*/
  bottom: 21vw;
  /*important*/
  padding: 25px;
  background: #f7f7f7;
}

/*responsive */

@media only screen and (max-width: 768px) {
  /* For mobile phones: */
  [class*="col-"] {
    width: 100%;
  }
}

/* For mobile phones: */

[class*="col-"] {
  width: 100%;
}

CONTACT STEPHANIE

If you have any questions or any design requests please email me at:

EMAIL

A:
    /* CONTACT Page */
.somesection {
  margin-top: 50px!important;
}

body {
  font-size: 16px;
  font-family: raleway;
}

img {
  max-width: 100%;
}

h3 {
  font-size: 18px;
}

CONTACT STEPHANIE

If you have any questions or any design requests please email me at:

EMAIL

Try this will solve your problem!