text:
Q: opengl how to make fire move smoothly and without a hole I'm rendering fire in opengl using freeglut, I created a particlesystem with emmiter and forcefield and they are working well.
I'm going to put the fire in an old train in a university project, I used textured spheres to simulate it.
The code is going to be long , I'm very sorry but all is relevant, here it is :
#include <GL/freeglut.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <SOIL/SOIL.h>
#include <glm/glm.hpp>

#include <deque> using namespace std;

typedef glm::vec3 Vector3;

struct Force { private :
    float strength;
    Vector3 orentation; public :
    Force(const Vector3 &v,const float &s)
        :strength(s),orentation(v)
    {
    }
    Force(const Force &f)
        :strength(f.strength),orentation(f.orentation)
    {

    }
    float getStrength() const
    {
        return strength;
    }
    Vector3 getOrentation() const
    {
        return orentation;
    } };

class Particle { public :
    Vector3 velocity,position;
    const float mass;
    float *deltatime;
    float lifebegin;
    Particle(const Vector3 &pos,const float &m,float *dt,const float &life)
        :velocity(Vector3()),position(pos),mass(m),deltatime(dt),lifebegin(life)
    {

    }

    void applyforce(const Force &f)
    {
        Vector3 force=f.getOrentation()*f.getStrength();
        Vector3 accleration=force/mass;
        velocity+=accleration*(*deltatime);
        proceedintime();
    }
    void proceedintime()
    {
        position+=velocity*(*deltatime);
    }
    virtual void draw()const=0;
    virtual bool collide(Particle *p)const=0;
    virtual ~Particle()
    {

    } }; class TexturedParticle : public Particle { protected :
    unsigned int textureid; public:
    TexturedParticle(const Vector3 &pos,const float &m,float *dt,const float &life,const unsigned int &tex)
        :Particle(pos,m,dt,life),textureid(tex)
    {

    }
    virtual ~TexturedParticle()
    {

    }

}; class Emmiter; class ForceField;

class ParticleSystem {
    friend class Emmiter;
    friend class ForceField; private :
    deque<Particle*> particles;
    float elapsedtime;
    float *deltatime;
    float LifeOfParticles;
    unsigned short particlesperframe; public :
    ParticleSystem(const float &life,float *dt)
        :elapsedtime(0),deltatime(dt),LifeOfParticles(life)
    {

    }
    void deleteparticles()
    {
        float div=fmod(elapsedtime,LifeOfParticles);
        if(div==0)
        {
            deque<Particle*>::const_iterator begin=particles.begin();
            deque<Particle*>::const_iterator end=particles.end();
            for(deque<Particle*>::const_iterator it=begin;it!=end;it++)
                delete (*it);
            particles.clear();
        }
    }

    void drawparticl1es()
    {
        deque<Particle*>::const_iterator begin=particles.begin();
        deque<Particle*>::const_iterator end=particles.end();

        for(deque<Particle*>::const_iterator it=begin;it!=end;it++)
        {
            (*it)->proceedintime();
            (*it)->draw();
        }
        elapsedtime+=(*deltatime);
    } };

class Emmiter { public :
    unsigned short ParticlesPerSecond;
    Vector3 position;
    ParticleSystem *ps;
    unsigned char count;
    float *deltatime;
    Particle *(*emitfunc)(const Emmiter &em);
    Emmiter(const unsigned short &parpersec,const Vector3 &pos,ParticleSystem *p,const unsigned char &c)
        :ParticlesPerSecond(parpersec),position(pos),ps(p),count(c)
    {

    }
    unsigned short particlesperframe()const
    {
        return ParticlesPerSecond*(*deltatime);
    }
    void emitparticles()const
    {
        unsigned short numpars=particlesperframe();
        Particle *p=0;
        for(unsigned char i=0;i<count;i++)
        {
            for(unsigned short j=0;j<numpars;j++)
            {
                p=emitfunc(*this);
                p->lifebegin=ps->elapsedtime;
                ps[i].particles.push_back(p);
            }
        }
    } }; class ForceField { private :
    Vector3 center;
    float radius,MaxAcceleration;
    unsigned char count;
    ParticleSystem *pars; public:
    ForceField(const Vector3 &cen,const float &r,const float &mf,ParticleSystem *ps,const unsigned char &c);
    void applyforceonparticle(Particle *p)const;
    void applyforceonsystems()const; };

ForceField::ForceField(const Vector3 &cen,const float &r,const float
&mf,ParticleSystem *ps,const unsigned char &c)
    :center(cen),radius(r),MaxAcceleration(mf),count(c),pars(ps) {

}

void ForceField::applyforceonsystems() const {
    for(unsigned char i=0;i<count;i++)
    {
        ParticleSystem p=pars[i];
        for(deque<Particle*>::const_iterator it=p.particles.begin();it!=p.particles.end();it++)
        {
            applyforceonparticle(*it);
        }
    } }

void ForceField::applyforceonparticle(Particle *p) const {
    Vector3 orentation=center-p->position;
    float strength=1-orentation.length()/radius;
    if(strength<=0)
        return;
    p->applyforce(Force(orentation,strength*MaxAcceleration*p->mass)); }

class BallParticle:public TexturedParticle { public :
    float radius;
    BallParticle(const Vector3 &pos,const float &r,const float &m,float *dt,const float &life,const unsigned int &tex)
        :TexturedParticle(pos,m,dt,life,tex),radius(r)
    {

    }
    void draw() const
    {
        glPushMatrix();
        glBindTexture(GL_TEXTURE_2D,textureid);
        glTranslatef(position.x, position.y, position.z);
        glutSolidSphere(radius,10,10);
        glPopMatrix();
    }
    bool collide(Particle *p) const
    {
        BallParticle *b=dynamic_cast<BallParticle*>(p);
        return (b)&&((b->position-position).length()<=b->radius+radius);
    } }; using namespace std;

float deltatime; float oldtime; float newtime; GLuint texture;
ParticleSystem pars(1,&deltatime); Emmiter
emmiter(100,Vector3(0,0,0),&pars,1); ForceField
f(Vector3(0,0.5f,0),0.5f,0.1f,&pars,1);

float myrand(const float &min,const float &max) {
    return min+(max-min)*(float(rand())/float(RAND_MAX)); }

Particle *emitfunction(const Emmiter &em) {
    float x=em.position.x,y=em.position.y;
    BallParticle *b=new BallParticle(Vector3(myrand(x-1,x+1),myrand(y-1,y+1),em.position.z),1,2,&deltatime,0.0f,texture);
    b->velocity=Vector3(0,1,0);
    return b; }

GLuint GetTextId(const char *texture_name) {
    return(SOIL_load_OGL_texture(
               texture_name,
               SOIL_LOAD_AUTO,
               SOIL_CREATE_NEW_ID,
               SOIL_FLAG_POWER_OF_TWO
               ));

}

/* GLUT callback Handlers */ void resize(int width, int height) {
    glViewport(0, 0, width, height);
    /*glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45,(4/3.0f),2,100);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    camera.LookAt();*/
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45,(float)width/(float)height,0.1f,100);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt( 0, 0, 10, 0, 0, 0, 0, 1, 0 ); }

void display() {
    glClear(GL_COLOR_BUFFER_BIT);
    newtime=glutGet(GLUT_ELAPSED_TIME)/1000;
    deltatime=newtime-oldtime;
    oldtime=newtime;
    pars.drawparticl1es();
    glutSwapBuffers(); } void idle() {
    emmiter.emitparticles();
    f.applyforceonsystems();
    pars.deleteparticles();
    glutPostRedisplay(); }

void init() {
    const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 0.0f };
    const GLfloat light_diffuse[] = { 1, 0.5f, 0.0f, 1.0f };
    const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    const GLfloat light_position[] = { 0.0f, 0.0f, 0.0f, 1.0f };
    const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    const GLfloat high_shininess[] = { 100.0f };
    const GLfloat mat_emissive[]={1,0.5f,0,1};

    glClearColor(0, 0, 0, 0);
    glTexGeni(GL_S, GL_TEXTURE_GEN_MODE,GL_SPHERE_MAP);
    glTexGeni(GL_T, GL_TEXTURE_GEN_MODE,GL_SPHERE_MAP);

    glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_TEXTURE_2D);

    glEnable(GL_TEXTURE_GEN_S);
    glEnable(GL_TEXTURE_GEN_T);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
    glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);
    glEnable(GL_LIGHT0);
    glEnable(GL_LIGHTING);

    glMaterialfv(GL_FRONT, GL_SPECULAR,  mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
    glMaterialfv(GL_FRONT,GL_EMISSION,mat_emissive);
    //glShadeModel(GL_SMOOTH);
    //glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA,GL_ONE); }

int main(int argc, char *argv[]) {
    glutInit(&argc, argv);
    glutInitWindowSize(640,480);
    glutInitWindowPosition(300,200);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutCreateWindow("Fire");
    glutReshapeFunc(resize);
    glutDisplayFunc(display);
    glutIdleFunc(idle);
    init();
    oldtime=glutGet(GLUT_ELAPSED_TIME)/1000;
    emmiter.emitfunc=&emitfunction;

    emmiter.deltatime=&deltatime;
    texture=GetTextId("/home/abd/graphics/fire2.jpg");
    glutMainLoop();
    return EXIT_SUCCESS;
}

and here is the texture I'm using :

The fire looks somewhat good but I'm still having an empty hole in the middle, also the particles don't move smoothly.
I tried these things :
1-change the strength and radius of the forcefield: didn't work.
2-increasing the number of particles per second : didn't work, still see the hole.
3-I made my particles bigger: well it made the fire look better and the hole almost disappeared(almost, it somewhat goes and come) but I get strange curves around the fire and it's still not moving smoothly.
4-I have double buffering and I made a call to glutPostRedisplay in the idle function , they still don't move smoothly, I tried removing the hint for PERSPECTIVE NICEST and SMOOTH_SHADING_MODEL, I'm using glutSolidSphere which uses new opengl capabilities and I have Nvidia GT9400 with updated driver to the last version, and still they don't move smoothly.
So what to do to solve these two problems ?
PS
because this is for a university project, I don't want code, "where is the mistake" is enough, I can solve it after I know it.
An algorithm is ok but not code.
EDIT
here's a screenshot of the output :

As you can see, there is a small hole in the middle and curves around the fire.

A: at a first glance it looks like you have to play a bit with the glBlendFunc
https://www.opengl.org/sdk/docs/man2/xhtml/glBlendFunc.xml
here's a nice viewer of what those parameters do
http://www.andersriggelsen.dk/glblendfunc.php


text:
Q: How to show that two functions f and g are equal given that $f\:\subseteq g\:$ and dom g ⊆ dom f? My set theory textbook gives me the exercise, "assume that f and g are functions with $f\:\subseteq g\:$ and dom g ⊆ dom f.  Show that f = g."
One can quickly see that, given that $f\:\subseteq g\:\rightarrow \:\forall <x,y>\:\in f\:\rightarrow <x,y>\in g$, so it follows that $xFy\:\rightarrow \:xGy$
Is it necessary to prove the inverse case, $xGy\:\rightarrow \:xFy\:\:?$  Or, given that dom g ⊆ dom f, can we conclude now from the definition of a function that f = g?

A: We want to show that $xGy \rightarrow xFy$ for all $<x,y> \in g$. So let $<x,y> \in g$. As $g$ is a function, there is only one such $y$ with $xGy$. As $\operatorname{dom}(g)\subset \operatorname{dom}(f)$, there is some $y'$ such that $x F y'$. Now by $f\subset g$ we must have $xGy'$. As there is only one unique $y$ with $xGy$, we must have $y'=y$ so that also $xFy$.

A: Generally, for the equality of two functions, we have the following lemma:
Lemma (Criterion for Functional Equality). Suppose $f,g$ are functions. Then $f=g$ if and only if, $\operatorname{dom}(f)=\operatorname{dom}(g)$ and $f(x)=g(x)$ for all $x\in\operatorname{dom}(f)$.
Now return to the proof of your problem.
Proof. To show $f=g$, it's sufficient to show two points:

*

*$\operatorname{dom}(f)=\operatorname{dom}(g)$. The $\supseteq$ is the assumption and $\subseteq$ follows from $f\subseteq g$.

*$f(x)=g(x)$ for all $x\in\operatorname{dom}(f)$. It follows from $f\subseteq g$.

This completes the proof.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery add elements based on a value i'm trying to add(and remove but i'll try that when this will work) a number of selects based on the value of a main select when said select changes.
I have a
Number of Selects
    <select id="selectNumber">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    </select>

And a single
Select 1 Options
    <select id="selectN1">
    <option>option1</option>
    <option>option2</option>
    </select>

Now, changing the #selectNumber should add more SelectN* based on his value and this is what should do that:
$("#selectNumber").on("change", function(){
    var n = $("#selectNumber").val();
    for (i=2;i<=n;i++){
        var c = i-1;
        $("#selectN"+c).after("
Select "+i+" options <select id='selectN"+i+"'><option>option1</option><option>option2</option></select>");
    }
}
);

This is the fiddle
http://jsfiddle.net/xPZUn/14/
On my page it runs ok but it only adds a second select item(even if 3 ore more are selected in the main select) i guess that's cause the for loop can't select the dynamically created elements to append more.
On the fiddle it doesn't even add a second select.
Any suggestions?
Thanks

A: Firstly your code has several syntax errors with missing closing brackets and braces. Once those are fixed, it works, however if you select 3, and then 1 you end up with 4 select  elements, so you need to clear the previously appended. Try this:
$("#selectNumber").on("change", function () {
    $('.additional-select').remove(); // remove existing
    for (i = 1; i < +$("#selectNumber").val(); i++) {
        $("#selectN" + i).after('
Select ' + (i + 1) + ' options <select id="selectN' + (i + 1) + '"><option>option1</option><option>option2</option></select>');
    }
});

Example fiddle
Note that the i + 1 is wrapped in brackets to ensure the result is appended, not the value of i and 1 appended individually as was previously happening.


text:
Q: Manage Dynamic Thumbnails on Amazon S3 / Cloudfront I just wanted to ask if there was a speedy of dynamically showing thumbnails of images uploaded on S3. Lets say profile pictures.
I have 3 sizes of these pictures being shown Actual, 150x150 and 25x25. At the moment I am dynamically resizing them on the fly on my server - not S3.
http://www.mydomain.com/images/25X25/image.jpg

Above is a URL that checks if a thumbnail exists and if not generates it. I allow only 3 sizes at the moment.
Soon we would be shifting to S3. Is such thing possible at S3 also - do I have to get the original image, resize it and then reupload on S3 - all on the fly - of course with cache enabled?
Or should I do this when I upload the actual image itself - make 2 more thumbnails (with easily readable filename lile image_25_25 and image_150_150) and upload those too along with it?
So eventually every upload results in
https://bucket.s3.amazonaws.com/image.jpg
https://bucket.s3.amazonaws.com/image_25_25.jpg
https://bucket.s3.amazonaws.com/image_150_150.jpg

Which do you think is a good option? Or Suggestions please - will be really thankfull to you all (err - always am - such an amazing place this is to get help!)
Cheers!

A: I would think that your approach will largely depend on what your primary goals are for making this change, what sort of upload volume you are expecting to handle, what sort of typical hit rate you have on these thumbnails, and what your constraints are regarding cost of performing this thumbnailing (i.e server resources needed to do the processing and storage costs for storing).
If the #1 most important thing is to speed-up image download times for end users, regardless of cost, then building the thumbnails on upload would probably be the best choice (possibly along with the use of Cloudfront in front of the S3 bucket).  This would also take your application out of the business of trying to dynamically serve requests for these images.  One con is obviously that the upload process may take longer for the end user (if you need the files to be created and available in S3 before indicating success to the end user), and of course you end up having to tie up server resources and storage space for every single uploaded image, regardless as to whether the image will ever be used.
If your concerns are more about utilizing the minimum amount of resources and storage, then you could continue to take the approach of using the web application to handle the image requests and create the images as needed in S3.  You could potentially use something like s3fs (with its caching functions turned on) to make these images available on a local mount of your application server to help speed up the process, but really I would advise against this dynamic serving of content approach if your overall goal is to provide the best user experience (i.e. quickest downloads).


text:
Q: Is Erlang 19.xx is FIPS compliant? Does Erlang 19.x compliant FIPS?
Or it needs to be built?
How can we build FIPS enable erlang and once build is there, is there some mechanism to verify it?
When search erlang documentation, there is no mention of FIPS http://erlang.org/doc/search/?q=fips&x=0&y=0.
But when search the github repo of erlang there are quit a referance to fips https://github.com/erlang/otp/search?p=2&q=fips&type=&utf8=%E2%9C%93

A: FIPS 140-2 support was merged into the master branch in this pull request.  It is was released in Erlang/OTP 20.0 (see entry OTP-13921 in the readme file), so the answer to your question is "no": Erlang 19 is not FIPS 140 compliant.  (Though you could apply the patch on top of Erlang 19, if you really want to.)
Even with the new release, you'd have to:

*

*configure Erlang to support it, using the command line ./configure --enable-fips before compiling it

*ensure that Erlang is linked to a FIPS-compliant OpenSSL library

*set the fips_mode setting of the crypto application to true before loading the crypto module - the most convenient place would be in the sys.config file of your Erlang release


text:
Q: list of regular expresions Im trying to create a list of regular expressions but automatically is added a new '\'
a = ['\s+ interface *', '\s+ address', '\s+ priority \d']

>>> a[2]
'\\s+ priority \\d'

I try to do something like this
with open('conf.txt') as f:
   lines = f.readlines()

for i in lines:
    for s in a:
        if bool(re.match(s, i)):
            print('i')

So basically I have a configuration file and I want to find some specific commands (list a). The command has a format for that reason I need a regular expression.
I want to do the equivalent of this:
for i in lines:
    if bool(re.match('\s+ interface *', a)):
        print('i')
    elif bool(re.match( '\s+ address', a)):
        print('i')
    elif bool(re.match( '\s+ priority \d', a)):
        print('i')

A: Your list does contain single slashes.  If you want to print the strings, try doing it like this:
a = ['\s+ interface *', '\s+ address', '\s+ priority \d']

print( '%s'%a[0] )

The output will be,
\s+ interface *

Note that it has a single slash.

A: The idea works as expected. My problem was the regular expression itself.


text:
Q: Converting jpg image with white background to transparent background png when image object also has white color I am trying to convert few JPG files with white background to PNG with transparent background.
I am using the following command:

convert 2868cif.jpg -fuzz 10% -transparent white 2868cif.png

The command works fine on most of the images. But for images with white content it converts them to as white. refer to sample images below:
Original image

convert image

In logical terms, I can understand why this is happening. I just wanted to know if there is a workaround for this using imagemagick?

A: Try floodfill with transparent color:
convert input.jpg -fuzz 15% -fill none -draw "matte 0,0 floodfill" output.png


text:
Q: Package incompatibilty between alphalph, and hyperref with amsmath subequations I have a document which makes use of subequations and alphalph, which compiles without hyperref, but throws an error when using hyperref.
Loading hyperref after the alphalph package does not help.
The error is:
! Undefined control sequence.
\GenericError  ...
                                                #4  \errhelp \@err@     ...
l.39    \end{align}

MWE:
\documentclass{article}

\usepackage{amsmath}
\usepackage{hyperref}
\usepackage{alphalph}

\begin{document}
\begin{subequations}
\renewcommand{\theequation}{\theparentequation \alphalph{\value{equation}}}
\begin{align}
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
    Blah\\
\end{align}
\end{subequations}
\end{document}

Does anyone know a fix?

A: I've tried out your minimum working example and found by trial and error that if you load the hyperref package first everything works as it should.
So the MWE you posted becomes:
\documentclass{article}

\usepackage{hyperref}
\usepackage{amsmath}
\usepackage{alphalph}

\begin{document}
\begin{subequations}
\renewcommand{\theequation}{\theparentequation \alphalph{\value{equation}}}
\begin{align}
    Blah\\
    Blah
\end{align}
\end{subequations}
\end{document}

Note that I have also removed the two backslashes from the last Blah. This prevents the creation of a numbered empty line. I have left out 25 lines of Blah\\ in the align block to keep it concise.

A: I think the actual problem was the location of your \label{} statements within the sub equations environment and your rearrangements inadvertently fixed up the \label{} location problem.
Here is an example with hyerref last that fails solely because the amsmath package dumps out of the sub equation environment poorly when there is a labeling problem.
This compiles:
\documentclass{amsart}

% mathematic related packages
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{thmtools}
\usepackage{hyperref}
% above is the preamble

\begin{document}

The Euler-Maclaurin summation formula for a function, $f(n, x)$, that is $(2 m + 1)$-differentiable in $z$ is:
\begin{subequations} \label{eq:EulerMacLaurin:GenM:Works}
\begin{align}
\sum\limits_{n = a}^{b} f(n, x) &= \int\limits_{z = a}^{b} f(t,x) dz \label{eq:EulerMacLaurin:GenM:Core}
\\ &+
\frac{1}{2}\left[ f(b,x) + f(a,x) \right] \label{eq:EulerMacLaurin:GenM:Endpoints}
\\ &+
\sum\limits_{k = 1}^{m} \frac{B_{2k}}{(2k)!}\left[ f^{(2 k -1 )}(b,x) - f^{(2 k -1 )}(a,x) \right] \label{eq:EulerMacLaurin:GenM:Corrections}
\\ &+
\int\limits_{z = a}^{b} f^{(2 m + 1)}(z,x) \frac{P_{2 m +1}(z)}{(2 m + 1)!} dt \label{eq:EulerMacLaurin:GenM:ErrorTerm}
\end{align}
\end{subequations}
Where equation \eqref{eq:EulerMacLaurin:GenM:Works}, has the following parts
\begin{itemize}
\item \eqref{eq:EulerMacLaurin:GenM:Core} is the core connection between an sum and its integral
\item \eqref{eq:EulerMacLaurin:GenM:Endpoints} is the correction due to the values at the end points of the interval
\item \eqref{eq:EulerMacLaurin:GenM:Corrections} are the sequence of progressively better corrections based on Bernoulli numbers and derivatives of the function under study
\item \eqref{eq:EulerMacLaurin:GenM:ErrorTerm} is the be-deviling error term that we hope goes to zero at some point
\end{itemize}

\begin{equation}
\int_limits_{s=-\infty}^{\infty} f(z,x) dz
\end{equation}

\end{document}

This fails with unrecognized control sequence, \end{align} on the second equation:
\documentclass{amsart}

% mathematic related packages
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{thmtools}
\usepackage{hyperref}
% above is the preamble

\begin{document}

The Euler-Maclaurin summation formula for a function, $f(n, x)$, that is $(2 m + 1)$-differentiable in $z$ is:
\begin{subequations}
\begin{align} \label{eq:EulerMacLaurin:GenM:Fails}
\sum\limits_{n = a}^{b} f(n, x) &= \int\limits_{z = a}^{b} f(t,x) dz \label{eq:EulerMacLaurin:GenM:Core}
\\ &+
\frac{1}{2}\left[ f(b,x) + f(a,x) \right] \label{eq:EulerMacLaurin:GenM:Endpoints}
\\ &+
\sum\limits_{k = 1}^{m} \frac{B_{2k}}{(2k)!}\left[ f^{(2 k -1 )}(b,x) - f^{(2 k -1 )}(a,x) \right] \label{eq:EulerMacLaurin:GenM:Corrections}
\\ &+
\int\limits_{z = a}^{b} f^{(2 m + 1)}(z,x) \frac{P_{2 m +1}(z)}{(2 m + 1)!} dt \label{eq:EulerMacLaurin:GenM:ErrorTerm}
\end{align}
\end{subequations}
Where equation \eqref{eq:EulerMacLaurin:GenM:Works}, has the following parts
\begin{itemize}
\item \eqref{eq:EulerMacLaurin:GenM:Core} is the core connection between an sum and its integral
\item \eqref{eq:EulerMacLaurin:GenM:Endpoints} is the correction due to the values at the end points of the interval
\item \eqref{eq:EulerMacLaurin:GenM:Corrections} are the sequence of progressively better corrections based on Bernoulli numbers and derivatives of the function under study
\item \eqref{eq:EulerMacLaurin:GenM:ErrorTerm} is the be-deviling error term that we hope goes to zero at some point
\end{itemize}

\begin{equation}
\int_limits_{s=-\infty}^{\infty} f(z,x) dz
\end{equation}

\end{document}

The un-helpful section of the log reads:
! Package amsmath Error: Multiple \label's: label 'eq:EulerMaclaurin:GenM:Fails' will be lost.

See the amsmath package documentation for explanation.
Type  H <return>  for immediate help.
 ...

! Undefined control sequence.
l.37     \end{align}


text:
Q: $.ajax function's success: not firing i have a $.ajax function that POSTS a data.
i have success: function(){alert("successflly posted")}
i check Firebug console, ajax request is POSTED and completed successfully, hOWEVER, the alert message never fires.

A: There's probably some error. Try setting the error callback:
error: function(httpRequest, textStatus, errorThrown) {
   alert("status=" + textStatus + ",error=" + errorThrown);
}

That may tell you why it's not working

A: A great suggestion by Philippe.
You could also try setting breakpoints/watches in firebug to see where your code is actually going (or not going).

A: You can also try the $.post() method, which is a wrapper for the more complicated $.ajax() method.
http://docs.jquery.com/Ajax/jQuery.post

A: Would you mind posting the entire block of code here?  A couple of quick notes- if you are using firebug, you don't need to use the alert() method, instead, use console.log()


text:
Q: From where do the initial values of the variable length array (VLA) in [c] come? example c code:
#include <stdio.h>
int main (int argc, char** args) {

    int k = 8;
    int sendbuffer[k]; // VLA

    for (int n = 0; n < k; n++) {
        printf("sendbuffer[%i]: %i \n", n, sendbuffer[n]);
    }

    return 0;
}

example output:
sendbuffer[0]: 1
sendbuffer[1]: 0
sendbuffer[2]: 1583871280
sendbuffer[3]: 32767
sendbuffer[4]: 22544384
sendbuffer[5]: 1
sendbuffer[6]: 1713234504
sendbuffer[7]: 32767

From where do the numbers in sendbuffer[] come from? And why are sendbuffer[2,4,6] the only ones that change when running the code again?
I'm using clang compiler on OSX El Capitan (compiling with gcc example.c)
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.4.0
Thread model: posix
If is a different behavior with other compiler/OS, I'd like to hear about these cases too.

A: This isn't just for VLAs; the behavior above is for any variable declaration. If you declare a variable, for example
int a;

This allocates sizeof(int) bytes on the stack, at whichever address the system chooses. The memory there is uninitalized; it is whatever happens to be there at the time. It is up to the programmer to initialize the memory.

A: Online C 2011 standard, 6.7.9/10: "If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate..."
Unless you declare it at file scope or with the static keyword1, a variable won't be initialized to any specific value; the contents will be whatever was last written to that memory location.

*

* Neither of which apply to VLAs; they cannot be declared static or at file scope, nor can they have an explicit initializer.

A: These values are called garbage values, they're whatever that was in memory when the array was created interpreted as ints.
Your program just says to the OS: "gimme that part of memory pls" and so the OS does, giving it to your program without changing the contents.


text:
Q: 3rd Party load CSV into Marketing Cloud I'm looking into a solution to allow a 3rd party to load a CSV into Marketing cloud.
The solution we're converging on is building a page, with a browse-save file dialog. The 3rd part can manually submit or script a post call to the url.
Where I'm unclear is how best to receive the CSV into Marketing Cloud.
We can save it into Portfolio, but getting it out and parsing is not self-evidently possible.
(Why FTP is not an option - it seems that it's difficult to control access at a folder level with the FTP accounts.)

A: Ok, I figured out a way. It is VERY manual, so take it like it is, but it allows you to upload into Content Builder and then import from there as you asked for in your question.

*

*Upload the file to the portfolio

*Get the File URL from the properties page

*Create an import/use Import Wizard

*select 'My Computer' as import option

*click 'browse' to open browse window

*Paste the File URL into file name text field at bottom

*Click Open

*Continue as normal

This potentially could be automated via API calls, but it would require a developer to spend a good amount of hours to construct it and it would have to be completely custom.


text:
Q: Python assignment operator associativity Consider the following Python3 program:
a = [0, 0]
i = 0
a[i] = i = 1
print(a, i)

a = [0, 0]
i = 0
i = a[i] = 1
print(a, i)

I expected the output to be:
[0, 1] 1
[1, 0] 1

But instead I got:
[1, 0] 1
[0, 1] 1

My question is: is there anything in the Python language specification about associativity of the assignment operator, or is the behavior for the above example undefined?
All I was able to find is that expressions are evaluated form left to right, except that r-value is evaluated first in case of assignment, but that doesn't help.

A: Just to make it clear, since I struggled myself to understand this. The statement:
a = b = c = ... = E

is equivalent to
a = E
b = E
c = E
...

A: Short answer: the code is well defined; the order is left-to-right.
Long answer:
First of all, let's get the terminology right. Unlike in some other languages, assignment in Python is a statement, not an operator. This means that you can't use assignment as part of another expression: for example i = (j = 0) is not valid Python code.
The assignment statement is defined to explicitly permit multiple assignment targets (in your example, these are i and a[i]). Each target can be a list, but let's leave that aside.
Where there are multiple assignment targets, the value is assigned from left to right. To quote the documentation:

An assignment statement evaluates the expression list (remember that
  this can be a single expression or a comma-separated list, the latter
  yielding a tuple) and assigns the single resulting object to each of
  the target lists, from left to right.


text:
Q: Find top 10 values above Y threshold and spread across X Quick question
I have a series of data points defined in two lists as X and Y. I'm looking for an efficient algorithm to select (let's say) 10 values from X and Y which are not only above a particular value of Y (a threshold), but are also spread across values of X as much as possible. By 'spread', I mean maximising the delta between X for adjacent points.
For example:
If the Y threshold = 100 and the X range = 1-10, an ideal set of values would be.
[1,104]
[2.5,120]
[3,101]
[4.7,150]
[5.2,190]
[6.3,115]
etc

A non-ideal set would be:
[1,104]
[1.3,157]
[1.6,174]
[1.5,120]
[1.17,135]
Etc

Any thoughts would be most appreciated

A: First extract the data points such that Y > Threshold.
Then sort on increasing X. Get Xmin and Xmax and compute 8 additional values of X equally spaced in this range, to form an increasing list Z (the "ideal" values).
Now scan both lists in parallel, as in a merge operation. Every time you move in the Z list, keep the corresponding X element.
CAUTION: this process can fail if the algorithm finds the same X corresponding to two different Z's. Fixing this isn't so obvious.

A: Similiar to @Yves Daoust's solution, I write a script:
from itertools import combinations
def get_max_x_scatter(datapoints, y_threshold, no_of_points):
        # First exclude the data points that is below y_threshold
        candidates = filter(lambda x: x[1]>y_threshold, datapoints)
        if len(candidates)<no_of_points:
                print "Not enough data points"
                return
        # Sort the candidate data points by x
        candidates_sorted_by_x = sorted(candidates, lambda m,n:int(m[0]-n[0]))
        # Get the x distance of 2 data points on remote ends
        distance = candidates_sorted_by_x[-1][0]-candidates_sorted_by_x[0][0]
        # Divide by the number of data points wanted, you get the expected average delta
        avg = distance/(no_of_points-1)
        # Within the K data points, find n of them that is *most scattered*

        min_delta = distance * no_of_points # make sure the initial min is large enough
        result = None
        for combination in combinations(candidates_sorted_by_x, no_of_points):
                delta = 0.0
                for i in range(1, no_of_points):
                        gap = combination[i][0] - combination[i-1][0]
                        delta += abs(gap - avg)
                if delta < min_delta:
                        min_delta = delta
                        result = combination
        return result

dp = [
[1,104],
[1.3,157],
[1.6,174],
[1.5,120],
[1.17,135],
[2.5,120],
[3,101],
[4.7,150],
[5.2,190],
[6.3,115],
[2,23]]

print get_max_x_scatter(dp, 100, 5)

>>> ([1, 104], [1.6, 174], [3, 101], [4.7, 150], [6.3, 115])

This algorithm minimize the deviation of data points from average delta, it may or may not be what you want. But it can be described to be 'as scattered as possible'.

A: I think that you should define "maximizing the spread across values of X" more precisely. Anyhow, let assume you a function f(S) that returns, for a set of point S, the spread across values of X of this set. You could try the following greedy algorithm (pseudocode below), that just select the potential values one after the other.
I assume your initial set of values comes as (X_i, Y_i)for 1 <= i <= n.
Let S = empty list
Let i = 0
While |S| <= 10
    If (Y_i > threshold) add (X_i,Y_i) to S
    i++;
While i < n
    If Y_i >= threshold
        Let j be such that X_j <= X_i <= X_{j+1}
        Let S_j = S, S_{j+1} = S;
        Remove (X_j, Y_j) from S_j and (X_{j+1}, Y_{j+1}) from S_{j+1}
        Add (X_i, Y_i) to S_j and to S_{j+1}
        If f(S_j) > f(S) let S = S_j
        If f(S_{j+1})> f(S) let S = S_{j+1}
    i++;
Return S

This would reduce the complexity to something like p*n where p is the number of values you want to select (assuming you keep S sorted and have a relatively fast way to compute f). I am not sure however whether this greedy algorithm yields an optimal solution. I would guess that it does at least for some reasonable forms of f.


text:
Q: Encoding issue with spanish file in C# I have a file store online in an azure blob storage in spanish. Some word have special charactere (for example : Almacén)
When I open the file in notepad++, the encoding is ANSI.
So now I try to read the file with the code :
        using StreamReader reader = new StreamReader(Stream, Encoding.UTF8);
        blobStream.Seek(0, SeekOrigin.Begin);
        var allLines = await reader.ReadToEndAsync();

the issue is that "allLines" are not proper encoding, I have some issue like : Almac�n
I have try some solution like this one :
C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H
but still not working
(the final goal is to "merge" two csv so I read the stream of both, remove the header and concatenate the string to push it again. If there is a better solution to merge csv in c# that can skip this encoding issue I am open to it also)

A: You are trying to read a non-UTF8 encoded file as if it was UTF8 encoded. I can replicate this issue with
var s = "Almacén";
using var memStream = new MemoryStream(Encoding.GetEncoding(28591).GetBytes(s));

using var reader = new StreamReader(memStream, Encoding.UTF8);
var allLines = await reader.ReadToEndAsync();

Console.WriteLine(allLines); // writes "Almac�n" to console

You should be attempting to read the file with encoding iso-8859-1 "Western European (ISO)" which is codepage 28591.
using var reader = new StreamReader(Stream, Encoding.GetEncoding(28591));
var allLines = await reader.ReadToEndAsync();


text:
Q: how to find least significant byte of an integer in Java? I need help with the following problem:
Write an expression that results in the least significant byte of an integer x being set to 0, but all other bits unchanged.
For example: 0x98234493 becomes 0x98234400.
I am confused on how to access the least significant byte.
public static int Q3(int x) {
    return (x & 0xFFFFFFFF);
}

What am i doing wrong?

A: The solution will be
public static int Q3(int x) {
    return (x & OxF);
}

A: You could do
public static int Q3(int x) {
    return (x & ~255);
}

255 in binary would have all the bits in the least significant byte set while all others are zero.
Therefore ~255, which is the complement of 255, will have all bits except those in the least significant byte set while all bits of the least significant byte are zeros.
This ~255 can be &ed with the input number n to set all bits in the least significant byte to zero while the other bits remain unchanged.

A: If all you want is the least significant byte of an integer (as your question is stated),
then it's very simple:
byte b = (byte) (x & 0xFF);
This works because all the high bits of 0xFF will be set to 0 by default, so you are masking out everything but the bottom byte. A byte is 8 bits and each 'F' is 4 bits (written in hexadecimal). In binary, an F is 1111, so FF masks out everything but the bottom 8 bits.


text:
Q: How do I make user controls for both ListView and ListViewItem work with each other? I have all the styling, triggers, etc. down for ListView and ListViewItem, and I want to turn them into user controls. How do I make sure that these two "match up" with each other, so that MyListView accepts MyListViewItems as content? Also, considering that I must end the ListView tag by the end of the user control XAML file, I am not sure how I would add items to it.

A: If you want them to be reusable with different data sets, especially through binding, you should stay away from UserControls and just make custom controls derived from the original types. In that case you create a standalone MyListView.cs and MyListViewItem.cs and all of the XAML for the controls goes into default Styles (usually also containing a ControlTemplate) in Themes/Generic.xaml. You can see an example of this setup by just adding a WPF Custom Control to your WPF project from Add New Item.
Once you've created the .cs files for your custom controls you just need to override a few methods from the base ItemsControl to use MyListViewItem as the item container control. The ListView would end up like this:
public class MyListView : ListView
{
    static MyListView()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyListView), new FrameworkPropertyMetadata(typeof(MyListView)));
    }

    protected override DependencyObject GetContainerForItemOverride()
    {
        return new MyListViewItem();
    }

    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return item is MyListViewItem;
    }
}

You can now use your custom MyListView exactly as you would a normal ListView, including binding to ItemsSource.

A: Inheritance should take care of that for you. In other words, if you have two user controls, the first one with a basic element of ListView (not UserControl) and the other of ListViewItem (again, not UserControl), and you make sure they extend ListView and ListViewItem respectively in the .cs code, the following should work equally:
ListView lv = new ListView();
lv.Items.Add(new ListViewItem());

or
MyListView mlv = new MyListView();
mlv.Items.Add(new myListViewItem()); //If your myListView extends ListView, and myListViewItem extends ListViewItem in your user control files, of course

In case you are looking for a XAML solution, you should import your namespace at the top
xmlns:myControls="WhateverYourNamespaceAndAssemblyAre"

and on you page/window/whatever
<myControls:myListView>
    <myControls:myListViewItem/>
    <myControls:myListViewItem/>
</myControls:myListView>


text:
Q: Why is Pressure a state function? Could someone give me a proof to justify that pressure is a state function?
Thanks in advance.

A: A state function in thermodynamics is a property that changes irrespective of the path taken. Thus anything that is used to represent states in thermodynamics has to be a state function, and Pressure is one of those state variables. Hence Pressure is a state function.

A: Although we can define a state function but ther also exists some mathematical criterias for any thermodynamic variable to be a state function.This site enlists them. They are :

*

*State functions are exact differentials.

*The cyclic integral of state function is zero.

*If the state function is a dependent variable , then the differential of the function can be represented as the partial differentials of the independent state functions on which the function depends.

*The mixed derivative(second partial derivatives) of the independent variables are equal.

Based on the above four criterias , you can check whether pressure is a state function or not.
The second one is much helpful if mathematics is not your subject. So I will expand it a bit.
We define a cyclic process as a process in which the thermodynamic parameters of the system reaches its initial values and pressure is one of the known thermodynamic parameters. So in cyclic process, the change in pressure is zero and hence it is a state function.


text:
Q: Find if value in nested sublist is greater than X within Pandas Column dataframe:
col1
[[0.43], [0.46], [1.0], [0.323]]
[[0.33], [0.66], [1.0], [0.3412]]
[[0.27], [0.42], [0.13], [0.332]]

I'm trying to create a column based on: if there's a number in the nested list of col11 >= .5 then "yes" else "no".
Result:
col1                                col2
[[0.43], [0.46], [1.0], [0.323]]    yes
[[0.33], [0.66], [1.0], [0.3412]]   yes
[[0.27], [0.42], [0.13], [0.332]]   no

It would also be good to have a column with the location of where the number was in nested list that was >= .5. for the above df, this would be col3: 3,3,N/A
Thinking something like this:
for i in df.col1:
    print(i)
    if j in i >= .05:
        print(i,"yes")
    else:
        print(i,"no")

A: You can do
sub_df = df[pd.DataFrame(df['col1'].apply(lambda x : sum(x,[])).tolist()).ge(0.5).any(1).values]

A: A simple apply should do
df['col2'] = df['col1'].apply(lambda x: max(e[0] for e in x) > 0.5)

Output
                                col1   col2
0   [[0.43], [0.46], [1.0], [0.323]]   True
1  [[0.33], [0.66], [1.0], [0.3412]]   True
2  [[0.27], [0.42], [0.13], [0.332]]  False

A: Use list comprehension with any. any is faster than max due it short-circuits on True
df['col2'] =  [any(y[0] >= 0.5 for y in x) for x in df.col1]

Out[1815]:
                                col1   col2
0   [[0.43], [0.46], [1.0], [0.323]]   True
1  [[0.33], [0.66], [1.0], [0.3412]]   True
2  [[0.27], [0.42], [0.13], [0.332]]  False

Some timings:
df = pd.concat([df]*10000, ignore_index=True)

In [1820]: %timeit  [any(y[0] >= 0.5 for y in x) for x in df.col1]
41.2 ms ± 1.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [1823]: %timeit df['col1'].apply(lambda x: max(e[0] for e in x) >= 0.5)
51.9 ms ± 1.58 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

side-test list comprehension with max
In [1827]: %timeit [max(y[0] for y in x) >= 0.5 for x in df.col1]
49.9 ms ± 2.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

So, any is faster although not significant.


text:
Q: Access writing violation when using INVOKE currently messing around with x86 assembly and I'm having some issues identifying the reason why the following code is causing a write access violation:

A: main PROC
INVOKE minmax,
        OFFSET array,
        LENGTHOF array,
        OFFSET msg1,
        OFFSET msg2

main ENDP

Look at your proc carefully...  Your missing something, do you realize what?  Well, your missing a ret right before main endp!  Without a ret the cpu will continue executing what ever is after main endp.
main PROC
INVOKE minmax,
        OFFSET array,
        LENGTHOF array,
        OFFSET msg1,
        OFFSET msg2

ret
main ENDP

is correct


text:
Q: How to return objects in an NSArray at specified indexes? Example:
I have an NSArray with 40 objects.  What is the most efficient way to return ONLY those objects with index equal to a number specified in another NSArray (e.g {0, 27, 36} for example)?
Can a predicate be used here?  Or is there a more simple and efficient approach?

A: Why don't you just iterate over the index array and look up each index in the data array replacing the index with the looked-up object.
In the end, the array that held the indices now holds the objects. If you don't want to wipe out your index array, then just create a new array of the same size as the index array and put the objects there.
You might be over-thinking the design of this and falling prey to micro-optimization. (Which is a bad thing.)

A: There is a method (objectsAtIndexes) for returning specified indexes from an original array, but it requires an NSIndexSet as its argument, and there isn't a built-in way to convert your array of indices to an index set. On the plus side, you can generate the index set with a short loop, as follows:
NSMutableIndexSet indexes = [NSMutableIndexSet indexSet];
for (NSNumber * number in indexArray)
{
    [indexes addIndex:[number intValue]];
}
return [originalArray objectsAtIndexes:indexes];

Is this any more efficient than simply looping through the original array? I have no idea. You would have to profile your app to be sure.

A: I remember reading one time, and I cant say where but it stuck in my mind, that if this was something you need to do many times and the array is fairly large that there is a more efficient way. You could create a new dictionary from that array where each entry has the key of the index number and the value is the array item. You only create the dictionary once so the hard work is over in one shot. Then every time you need to access values at certain indexes you just ask for valueForKey:@"indexNumber". But I never had a need for this so I never tested if it was more efficient in the long run... it's just a thought.


text:
Q: Froala editor doesn't work for Angular 4 with typescript I using angular 4 with type script and I installed ng2-froala-editor and when I want to npm start occurs error
[at-loader] ./node_modules/ng2-froala-editor/ng2-froala-editor.d.ts:1:1
TS6053: File './node_modules/typings/globals/core-js/index.d.ts' not found.
errors @ client?0fb1:119
sock.onmessage @ socket.js?e5d0:37
EventTarget.dispatchEvent @ eventtarget.js?3e89:51
(anonymous) @ main.js?45b8:274
SockJS._transportMessage @ main.js?45b8:272
EventEmitter.emit @ emitter.js?927b:50
WebSocketTransport.ws.onmessage @ websocket.js?c17e:35
wrapFn @ zone.js?fad3:1075
ZoneDelegate.invokeTask @ zone.js?fad3:424
Zone.runTask @ zone.js?fad3:191
ZoneTask.invokeTask @ zone.js?fad3:498
invokeTask @ zone.js?fad3:1370
globalZoneAwareCallback @ zone.js?fad3:1388

I imported this:
import {FroalaEditorModule} from 'ng2-froala-editor/ng2-froala-editor';

into module.ts and this into component
import {FroalaEditorComponent} from 'ng2-froala-editor/ng2-froala-editor';

Anyone know how to solve this error?

A: You can use angular-froala-wysiwyg (i am using it in my project)
install it via
npm install angular-froala-wysiwyg

and import in app.module.ts
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';

and also import in @ngModule decorator
FroalaEditorModule.forRoot(), FroalaViewModule.forRoot()

hope I will solve your issue


text:
Q: pandas dataframe print repeats values I have the following source CSV
"TreeDepth","PID","PPID","ImageFileName","Offset(V)","Threads","Handles","SessionId","Wow64","CreateTime","ExitTime"
0,4,0,"System","0xac818d45d080",158,,,False,"2021-04-01 05:04:58.000000 ",
1,88,4,"Registry","0xac818d5ab040",4,,,False,"2021-04-01 05:04:54.000000 ",
1,404,4,"smss.exe","0xac818dea7040",2,,,False,"2021-04-01 05:04:58.000000 ",
0,556,548,"csrss.exe","0xac81900e4140",10,,0,False,"2021-04-01 05:05:00.000000 ",
0,632,548,"wininit.exe","0xac81901ee080",1,,0,False,"2021-04-01 05:05:00.000000 ",
1,768,632,"services.exe","0xac8190e52100",7,,0,False,"2021-04-01 05:05:01.000000 ",
2,1152,768,"svchost.exe","0xac8191034300",2,,0,False,"2021-04-01 05:05:02.000000 ",
2,2560,768,"svchost.exe","0xac8191485080",6,,0,False,"2021-04-01 05:05:03.000000 ",

In my python script I've trying to print the 4th cell value of every row (i.e. the process name). the following function prints it fine but it repeats it self for like 3 times.. What am i doing wrong?
dfProcs = pd.read_csv( args.path + '/windows.pstree.PsTree.csv')
for ImageFileName in dfProcs:
    print(dfProcs[ImageFileName].values[0])

Get a list of all the Image File Names from csv data.

A: Your for loop is iterating over the column names and it just seems that you are just printing out the column value for the first row.
Instead it seems like you want to iterate over the fourth column and print every value. This is one way of doing that
for fileName in dfProcs["ImageFileName"]:
   print(fileName)

A: I would recommend you to use itterrows() because it's more versatile, and quite often you will use other parameters like just index that itterrows returns (index, Series)
How to use it in your case ->
for index, row in dfProcs.iterrows():
    print(row["ImageFileName"])

return
System
Registry
smss.exe
csrss.exe
wininit.exe
services.exe
svchost.exe
svchost.exe

How to use it and theory -> https://towardsdatascience.com/how-to-iterate-over-rows-in-a-panas-dataframe-6aa173fc6c84


text:
Q: Relative tangent space to proper morphism and irreducibility of fibers Let $f:X \to Y$ be a proper surjective morphism of reduced connected noetherian schemes. Assume $Y$ is irreducible. Let $y \in Y$ be a closed point. Denote by $X_y$ the fiber over $y$ to the morphism $f$. Suppose that $X_y$ is a non-singular, irreducible variety and for every closed point $x \in X_y$, the tangent space $T_xX$ have the same dimension. Does this imply that any irreducible component of $X$ intersecting $X_y$ contains the whole of $X_y$? Can we drop the assumption of reducedness of $X$ or $Y$?

A: That is certainly not true.  Let $Y$ be $\mathbb{A}^2$ with coordinates $(s,t)$.  Denote by $[u_0,u_1]$ homogeneous coordinates on $\mathbb{P}^1$.  Let $X$ be the hypersurface of $\mathbb{A}^2\times \mathbb{P}^1$ with homogeneous defining equation $stu_1 = 0$.  Let $f:X\to Y$ be the restriction to $X$ of the projection to $Y$.  Let $y$ be the closed point with associated maximal ideal $\langle s,t \rangle$.
The fiber $X_y$ of $f$ over $y$ is $\mathbb{P}^1$.  The Zariski tangent space to $X$ at every point of $X_y$ equals the entire Zariski tangent space to $\mathbb{A}^2\times \mathbb{P}^1$, and this is $3$-dimensional.   The irreducible component where $u_1$ equals $0$ intersects $X_y$, but it does not contain $X_y$.
There is a similar example where $Y$ is an irreducible nodal curve and $y$ is the node.


text:
Q: AWS errors LimitExceededException and EntityAlreadyExistsException I have been having problem deploying my python project unto aws
It has been giving me the error NotAuthorizedError: Operation Denied. Access Denied
But on getting into amazon I saw these errors. These are just the summary
{"Records":[
{"eventName":"AddRoleToInstanceProfile",
"errorCode":"LimitExceededException",
"errorMessage":"Cannot exceed quota for InstanceSessionsPerInstanceProfile: 1",
"requestParameters":{
    "instanceProfileName":"aws-elasticbeanstalk-ec2-role",
    "roleName":"aws-elasticbeanstalk-ec2-role"}},
{"eventName":"CreateRole",
"errorCode":"EntityAlreadyExistsException",
"errorMessage":"Role with name aws-elasticbeanstalk-ec2-role already exists.",
"requestParameters":{"roleName":"aws-elasticbeanstalk-ec2-role",}},
{"eventName":"CreateInstanceProfile",
"errorCode":"EntityAlreadyExistsException",
"errorMessage":"Instance Profile aws-elasticbeanstalk-ec2-role already exists."}]}

Please how can i overcome this problems since I am doing it programmatically through ebcli and I am not creating it manually
Any help would be appreciated


text:
Q: import caffe, error _message.so I installed caffe from source code on my Mac os x, but when I type this command:
python -c "import caffe"
I got this error:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/junhao.wen/Hao/Docker/Caffe/Caffe_source/caffe/python/caffe/__init__.py", line 1, in <module>
    from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver
  File "/Users/junhao.wen/Hao/Docker/Caffe/Caffe_source/caffe/python/caffe/pycaffe.py", line 15, in <module>
    import caffe.io
  File "/Users/junhao.wen/Hao/Docker/Caffe/Caffe_source/caffe/python/caffe/io.py", line 8, in <module>
    from caffe.proto import caffe_pb2
  File "/Users/junhao.wen/Hao/Docker/Caffe/Caffe_source/caffe/python/caffe/proto/caffe_pb2.py", line 7, in <module>
    from google.protobuf import descriptor as _descriptor
  File "/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7-macosx-10.6-x86_64.egg/google/protobuf/descriptor.py", line 46, in <module>
    from google.protobuf.pyext import _message
ImportError: dlopen(/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7-macosx-10.6-x86_64.egg/google/protobuf/pyext/_message.so, 2): Symbol not found: __ZNK6google8protobuf10TextFormat17FieldValuePrinter10PrintBytesERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
  Referenced from: /Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7-macosx-10.6-x86_64.egg/google/protobuf/pyext/_message.so
  Expected in: flat namespace
 in /Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7-macosx-10.6-x86_64.egg/google/protobuf/pyext/_message.so

Any suggestion will be appreciated:)
Thanks in advance

A: Make sure that the Python path is pointing to $CAFFE_HOME/Python


text:
Q: Connecting an Oracle DB Container and a Java application Container (Docker) I am now working on a docker project with two docker containers - one for the oracle db and the other with a java application.
The container for oracle db is working ok. I used the already built image for oracle and created my tablespaces and users in it.
Commands I used to pull and use the oracle db container is as given below:
docker pull wnameless/oracle-xe-11g

docker run -d -p 49160:22 -p 49161:1521 -e ORACLE_ALLOW_REMOTE=true wnameless/oracle-xe-11g

Now I have my own Java application that interacts with the oracle db and I run it using the command given below:
docker run -it --name mypgm myrepo/oracletesting

It runs an interactive java program that asks for the Oracle DB details and allows users to interact with the DB.
However I could not figure out how I have to specify details such as
Driver Name, Connection URL, Username, and Password
The values I gave are as given below:

Driver Name:  oracle.jdbc.OracleDriver
  Connection URL:jdbc:oracle:thin:@localhost:1521:orcl11g
  Username: imtheuser
  Password: **********

I dont know whats going wrong where but its not working.
I tried giving different inputs for Connection URL after inspecting the docker container ip address as well:

Connection URL: jdbc:oracle:thin:@172.17.0.2:1521:orcl11g

Am I giving the Connection URL and/or the port number correct? Can someone help me out to correctly connect these two containers and to get the project moving?
Thanks for your kind help..

A: You have to link the containers.
 The oracle container should have a name.
try the following:
    docker network create my-network # Create a network for containers
    docker run -d -p 49160:22 -p 49161:1521 --network my-network --name oracle-db -e ORACLE_ALLOW_REMOTE=true wnameless/oracle-xe-11g
    docker run -it --network my-network --name mypgm myrepo/oracletesting

Use  as connection url to following string jdbc:oracle:thin:@oracle-db:1521:orcl11g

A: You can use a domain name in oracle connection string: oracle.dbhost.com, and use a --addhost oracle.dbhost.com:[ip address] when running your app in docker, or configure a dns to resolve the domain name.


text:
Q: Prevent some elements from being rendered canvas This is my website.
I want the background of my nav-element to be blurred... I used html2canvas and stackblur for this, and you can find the tutorial here.
My problem is now that I want to exclude the nav-element from being rendered in canvas, so it only shows the background when scrolling. Currently it's only working in WebKit browsers, because I don't know how to add multiple properties to:

"-webkit-transform",

This is my code:

A: Let us say you want to hide the following div.

Then, just add the following line in the div.

And that's it! Your problem is solved.

A: I found this in html2canvas updates: Added support for "data-html2canvas-ignore" attribute
For preventing render of a DOM element, you need add the data-html2canvas-ignore attribute in your element:

var test = document.getElementById("test");
var content = document.getElementById("content");

test.onclick = function () {
    html2canvas(content, {
        "onrendered": function(canvas) {
            document.body.appendChild(canvas);
        }
    });
};

  test

1. Is visible

2. No visible

3. Is visible


text:
Q: jsp how to creat a log.txt file in openshift I need to save something for every request in a log.txt file.
index.jsp in the below do that (which runs in localhost) correctly.
StringBuilder html =  new StringBuilder();
ServletContext context = request.getServletContext();
        String file = context.getRealPath("/");
        html.append(html);
        file += "log.txt";
        System.out.println(file);
        html.append("
\n____________________________________
\n");//file path
        html.append(file.toString());//file path
        html.append("
\n____________________________________
\n");//file path

        FileWriter filewriter = new FileWriter(file, true);
        filewriter.write(html.toString());
        filewriter.close();

But when i push my project in Openshift it return null as file path:
I create log.txt manually and set 777 for its permission near index.jsp but it is always empty!!

A: According to the developer center [1] you should use the data folder if you want to have persistent storage of your uploaded/dynamically created files. Or else they will be wiped every time you perform a git push.


text:
Q: What is the equivalent HttpClient JSON POST to this RestClient JSON POST? Given:
Uri location = ...; // Remote 3rd party HTTP Rest API
string body = "SOME JSON";

The following RestClient code generates HTTP traffic that is accepted by the server.
var client = new RestClient(location);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json; charset=utf-8");
request.AddParameter("application/json; charset=utf-8", body,
   ParameterType.RequestBody);
var restResponse = client.Execute(request);

However, the HttpClient code below must be generating different HTTP traffic (indicated by the server rejecting the request).
using (var client = new HttpClient())
{
  var request = new HttpRequestMessage();
  request.Method = HttpMethod.Post;
  request.RequestUri = location;
  var bodyContent = new StringContent(body, Encoding.UTF8, "application/json");
  request.Content = bodyContent;
  request.Headers.Add("cache-control", "no-cache");
  client.Timeout = TimeSpan.FromMinutes(5.0);
  var response = await client.SendAsync(request);
}

Why is the HttpClient code serializing differently?

A: A simple way to find the precise differences is to run Fiddler or another debugging proxy and check the raw request. Here's what I got with HttpClient:
POST http://example.com/ HTTP/1.1
cache-control: no-cache
Content-Type: application/json; charset=utf-8
Host: example.com
Content-Length: 4
Expect: 100-continue
Connection: Keep-Alive

test

And with RestSharp:
POST http://example.com/ HTTP/1.1
cache-control: no-cache
Content-Type: application/json; charset=utf-8
Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml
User-Agent: RestSharp/106.6.9.0
Host: example.com
Content-Length: 4
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

test

Your results may differ depending on your system configuration, versions etc., so you should try it yourself to make sure.


text:
Q: Using GNU assembler for shellcode Is it possible to use the GNU assembler for shellcode without too much headache? I prefer the AT&T syntax to Intel syntax. I'm working through Hacking the Art of Exploitation, so they wrote their shellcode to assemble with NASM.
However, the problem is that when using the GNU assembler, I get massive binaries of around 480 bytes in size compared to NASM's output of about 35 bytes in size. Alarmingly, many of these bytes appear to be 0000, or null bytes! Also, it seems to not be possible to assemble programs without an _start label- but this defines a procedure that would not really work well as a shellcode exploit.
Here is Hacking the Art of Exploitation's code:
BITS 32
xor eax, eax
xor ebx, ebx
xor ecx, ecx
cdq
mov BYTE al, 0xa4
int 0x80
push BYTE 11
pop eax
push ecx
push 0x68732f2f
push 0x6e69622f
mov ebx, esp
push ecx
mov edx, esp
push ebx
mov ecx, esp
int 0x80

My translation:
.code32
.section .text
    .globl _start
_start:
    xorl %eax, %eax
    xorl %ebx, %ebx
    xorl %ecx, %ecx
    cltd
    movb $0xa4, %al
    int $0x80
    push $11
    popl %eax
    pushl %ecx
    pushl $0x68732f2f
    pushl $0x6e69622f
    movl %esp, %ebx
    pushl %ecx
    movl %esp, %edx
    pushl %ebx
    movl %esp, %ecx
    int $0x80


text:
Q: Why isn't Modus Ponens valid here I have the following:
$(\neg A \lor B) \rightarrow (\neg A \lor B) \\ (\neg A \lor B) \\ \vdash \neg A \lor B $
And in my mind this seems like a legitimate use of the Modus Ponens rule. But the textbook I'm using disagrees.
Why is this wrong?
Edit:
The textbook has the following line in it as a part of a larger exercise:

The exercise asks to state whether the use of a giving rule is valid in each case. In the answer section it is marked as an invalid use.

A: Note that $$(\lnot A \lor B) \rightarrow (\lnot A \lor B) \equiv \lnot(\lnot A \lor B) \lor (\lnot A \lor B) \equiv \top$$ In other words, the first premise is a tautology. It says nothing more than "either $\lnot(\lnot A \lor B)$ or else $(\lnot A \lor B)$ holds.  And in assuming the law of the excluded middle, one of the two disjuncts must be true, and thus the entire  statement is tautologically true.
The second premise is $\lnot A \lor B$.
The argument then can be stated as follows:
$\quad \top\tag{premise 1} $
$\quad \lnot A \lor B\tag{premise 2}$
$\therefore \lnot A \lor B\tag{repetition of premise 2}$
So the conclusion becomes a reiteration of the second premise.
Perhaps that is what your book was attempting to convey?

A: To infer $p$ from $p \rightarrow p$ and $p$ is a legitimate application of modus ponens. It isn't a particularly useful inference, but it is a correct one.

A: It doesn't appear to be wrong. If $C=C'=\neg A\vee B$, then a correct use of modus ponens is simply $(C'\to C)\wedge C'$ gives $C$, which is what you have.


text:
Q: Plotting the solution of a cubic equation against a coefficient in the equation I have to plot the solution of the following equation against the coefficient $L$. Since it's a cubic equation, I'd like to filter out the real solution first and plot that then. The equation is $L r^3 - 3 r + 6 M = 0$.
PS: I have been trying various variants over the following piece of code, but to no use:
f[L_, M_, r_] := L r^3 - 3 r + 6 M
Plot[r /.NSolve[f[L,10,r] == 0, r,Reals], {L,-1,1}]

Could you let me know what I might be doing wrong?

A: It works fine in Mathematica 10. Even as 3D Plot as function of parameters L and M:
Plot3D[r /. NSolve[f[L, M, r] == 0, r, Reals], {L, -1, 1}, {M, 0, 10}]

A: May be that will do:
    Clear[ss, n];
eq = L r^3 - 3 r + 6 M == 0;
ss[L_, M_] = Solve[eq, r];

Manipulate[
 Plot[{ss[L, M][[1, 1, 2]], ss[L, M][[2, 1, 2]],
   ss[L, M][[3, 1, 2]]}, {L, 0, 1},
  PlotStyle -> {Red, Blue, Green}], {{M, 0.6}, 0, 1}]

giving

Have fun!


text:
Q: gcloud configuration project filter When listing projects, we can filter on name using: gcloud projects list --filter='name:xxxx*'
How to store this filter in gcloud configuration so everytime we run gcloud projects list we get filtered projects ?
Note: I don't want a command alias, I need a "per gcloud configuration" filter.
Thanks

A: @guillaume-blaquiere is correct, you cannot.
However, users are only able to list projects to which they have access.
So, if you're trying to limit the list of projects that your users(' credentials) can list, a more robust solution would be to consider limiting the projects to which the users(' credentials) have access.
Depending on whether you're using a organization you can do this either at the organization/folder(s) level or at the project-level directly.


text:
Q: Improving distribution array element distribution I am trying to write a command in Python that would calculate the distribution.
For an example the call:
n=10
x = [1]*3 # returns [1,1,1]
y = [s/sum(a)*n for s in x] # returns [3.3,3.3,3.3]

The problem is that this way, the program I am using would round down the values to 3 and basically, the sum of the array would be 9 instead of 10. How could I improve the call so that I get whole values like [4.0,3.0,3.0]?

A: The problem is to find which elements to round up while rounding all the rest down. One way to decide is that the element with the largest fractional part gets rounded up but no element is rounded up more than once.
import numpy as np

def distribute(weights, total):
    # calculate the distribution as you have done
    dist = np.array(weights) / sum(weights) * total

    # separate the fractional parts
    fracs, dist = np.modf(dist)

    # adjust if necessary
    while dist.sum() != total:
        # find the index of the maximum value of the fractional parts
        max_idx = np.argmax(fracs)

        # increment just that one value
        dist[max_idx] += 1

        # zero out that fractional part so we don't use it twice
        fracs[max_idx] = 0

    return dist

>>> distribute([1]*3, 10)
array([4., 3., 3.])

>>> distribute([1, 2, 3], 16)
array([3., 5., 8.])

>>> distribute([1, 2, 3, 1, 1], 21)
array([3., 5., 8., 3., 2.])


text:
Q: Getting data passed to web site form I am trying to pass data into a form that is on the fourth page.  I have successfully navigated through the macro signing me in, searching for specific page based on data entered, going to that specific page, and pulling up the form in which I want to enter data into multiple spots.
Sub Test()
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.Navigate "http://mywebsite.com/Pages/MainSite/Default.aspx"
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)
    Loop
    IE.document.getElementById("txtUserName").Value = "dummyusername"
    IE.document.getElementById("txtPassword").Value = "password"
    IE.document.getElementById("btnLogin").Click
End Sub

Sub Next2()
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.Navigate "mywebsite.com/pages/hr/TimeEntryDashboard.aspx"
    Do While IE.Busy
        Application.Wait DateAdd("s", 2, Now)
    Loop
    IE.document.getElementById("MainContent_MainContent_txtStartDateFilter").Value = "10/13/2018"
    IE.document.getElementById("MainContent_MainContent_txtEmployeeNameFilter").Value = "122631"
    IE.document.getElementById("MainContent_MainContent_btnFind").Click
End Sub

Sub Next3()
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.Navigate "mywebsite.com/pages/hr/TimeAndInspectionWizard.aspx?id=0245b750-4cde-47da-a754-fb7f8bfecfc9"
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)
    Loop
    IE.document.getElementById("imgGridTimeDetailsArrow0").Click
    IE.document.getElementById("MainContent_MainContent_tcMain_tpValidation_rptInspectionDetails_imbGridInspectionDetailsOptionsAdd_0").Click
End Sub

Sub Next4()
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
  ' IE.Visible = True
  ' IE.Navigate "mywebsite.com/pages/hr/TimeAndInspectionWizard.aspx?id=0245b750-4cde-47da-a754-fb7f8bfecfc9"
    Do While IE.Busy
        Application.Wait DateAdd("s", 2, Now)
    Loop
    IE.document.getElementById("MainContent_MainContent_tcMain_tpInspectionDetails_txtInspectionDetailsLotNumber").Value = "12345"
    IE.document.getElementById("MainContent_MainContent_tcMain_tpInspectionDetails_txtInspectionInspectedQuantity").Value = "1"
    IE.document.getElementById("MainContent_MainContent_tcMain_tpInspectionDetails_txtGoodWithoutReworkQuantity").Value = "1"
    IE.document.getElementById("MainContent_MainContent_tcMain_tpInspectionDetails_txtAddInspectionResult").Click
End Sub

This part above is producing an error at the first section where it is supposed to input data onto the screen.

A: You must check whether an element exists or not as part of code validation and that will also lead you to identifying the problem in better manner. Here is your code re-written with validation for example.
Sub Next4()
    Dim IE As Object, Elem As Object
    Set IE = CreateObject("InternetExplorer.Application")

    With IE
        Do While .Busy
            Application.Wait DateAdd("s", 2, Now)
        Loop

        With .document

            Set Elem = .GetElementById("MainContent_MainContent_tcMain_tpInspectionDetails_txtInspectionDetailsLotNumber")
            If Not Elem is nothing Then
                Elem.Value = "12345"
                Set Elem = Nothing
            End If

            Set Elem = .GetElementById("MainContent_MainContent_tcMain_tpInspectionDetails_txtInspectionInspectedQuantity")
            If Not Elem is nothing Then
                Elem.Value = "1"
                Set Elem = Nothing
            End If

            Set Elem = .GetElementById("MainContent_MainContent_tcMain_tpInspectionDetails_txtGoodWithoutReworkQuantity")
            If Not Elem is nothing Then
                Elem.Value = "1"
                Set Elem = Nothing
            End If

            Set Elem = .GetElementById("MainContent_MainContent_tcMain_tpInspectionDetails_txtAddInspectionResult")
            If Not Elem is nothing Then
                Elem.Click
            Else
                MsgBox "Can't Click as Element Missing : " & "MainContent_MainContent_tcMain_tpInspectionDetails_txtAddInspectionResult"
            End If
       End With
    End With
End Sub

A: You haven't stated the error or shown any HTML. It could be that your element is within a parent frame/iframe.

*

*You do want a proper wait for page load While .Busy Or .readyState < 4: DoEvents: Wend. If you join your subs togther you will need this after each .Click/.Submit/.Navigate

*If it is a timing issue then you can have a loop timer, as shown, to loop until element set or timeout reached - to avoid infinite loop

*You do want a test for if element was set

*You do want the attempt to assign an object reference wrapped within an On Error Resume Next to keep the code running and prevent users from seeing error messages if element not set.

*Your question is about this first part so that I have addressed but I echo the sentiment in the comments that you only need one IE instance and should work with that unless these subs are unrelated and run independently. You may still consider whether they can be joined in that case using one instance.

VBA:
Option Explicit
Public Sub LoopUntilSet()
    Dim IE As New InternetExplorer, t As Date
    Const MAX_WAIT_SEC As Long = 5

    With IE
        .Visible = True
        .navigate "yourURL"

        While .Busy Or .readyState < 4: DoEvents: Wend

        t = Timer
        Do While x Is Nothing
            DoEvents
            On Error Resume Next
            Set ele = .document.getElementById("txtUserName")
            On Error GoTo 0
            If Timer - t > MAX_WAIT_SEC Then Exit Do
        Loop

        If ele Is Nothing Then
            Exit Sub
        Else
            ele.Value = "dummyusername"
            'other code
        End If
        .Quit
    End With
End Sub


text:
Q: Handlebars.js JSON setting class(es) based on value/pair Just starting to look at Handlebars.js today and wanted a clear approach. Assume the following: We don't have control over how the JSON was created (So no server side solutions). JSON will have 1 or more records in it. In each record, there will be a Message_Type name/value pair the value of which would be useful in some function which css class(es) are used in the presentation.
ex: message_type: basic, ad, notification, warning, critical. Each message_type will have a css class(es). So critical message type might get classes .msg_box .critical_msg.
How should I do this (remember, we can't change the original source).? Option 1: process json data before handlebars and add name/value pair for each that contains the appropriate classes.  Option 2: some way in handle bars that is unclear to me.

A: I believe the handlebars convention would be to parse your JSON and add the appropriate class name to the resulting object prior to passing it to the Handlebars template. Handlebars can be hacked to include the necessary logical operators, but I think it's generally frowned upon.

var messageMapping = {
  basic: 'msg_box',
  ad: 'msg_box',
  notification: 'msg_box',
  warning: 'critical_msg',
  critical: 'critical_msg'
};

//Your data from the server
var yourJSON = '[{"message_type":"basic", "value":"test"},{"message_type":"warning", "value":"test"}]';

var data = JSON.parse(yourJSON),
    i = 0,
    l = data.length;

//Update the class names
for(; i < l; i++){
  data[i].msgClass = messageMapping[data[i].message_type];
}

//Add to the DOM
var source   = $('#template').html();
var template = Handlebars.compile(source);

$('body').append(template({messages:data}));
.critical_msg{
  background-color:red;
}

.msg_box{
  background-color:green;
}

A: Handlebars is designed to be fairly "logic-less" which means it doesn't come with built in capabilities to make decisions based on the data passed in other than a simple if based on whether something exists or not in the data.  Deciding what class to put in the HTML based on what the value is of some data structure element is not a built-in capability.
As such your options are:

*

*Assuming the templates are being used client-side, you can pre-process the JSON on the client side to put it into a no-logic needed form before it is sent to the template.

*Create helper methods that you can pass data to and they can make decisions based on it that are communicated back to the template.

*Add helper methods that can add logic capabilities to your template (you can find some pre-built ones).

*Switch to a template engine that has more logic capabilities built in.


text:
Q: using APNS function to navigate to desired content I am wondering, how to use APNS function to navigate to desired content, like strait times apps, which it only push the title of the news to the user(I've managed to do this part), but when the user click view, it'll directly fire the apps and go directly to the content which title being shown as the alert in push. I only managed to go to the main page of my apps.
Thanx in advance.

A: You can add custom data in the payload, for example the id of the news to show.
Example :
 {
    "aps":
        {"alert":"test",
        "badge":1,
        "sound":"default"
        },
    "Value1":info,
    "Value2":3,
      "myDict":
       {
         "key1":"val1",
         "key2":val2
       }
    }

And to access in the code :
- (void)receivedRemoteNotification:(NSDictionary *)userInfo {

NSDictionnary *myDict = [userInfo valueForKeyPath:@"aps.myDict"];

}


text:
Q: MOSFET PWM issue I want to dim an LED and have connected a P-channel MOSFET to switch the high side. I added a N-channel MOSFET as a driver. The schematic is attached below.
I'm applying a PWM sine signal from an STM32.
Problem:
If I measure the voltage on the drain of the N-channel SI2302 to ground, I see that the voltage is increasing from 0 to around 1.5 V and after that it's saturated at 5 V for the rest of the cycle until the duty cycle drops again. So instead of a nice oscillating sine curve from 0 to 5 V, I get a partial sine curve which is somehow clipped...
The voltage between drain of the P-channel MOSFET and ground is always at 5 V except for a short drop to 0 V.
How do I prevent the circuit from saturating?

A: That 10 kΩ pull-up resistor (R29) is too high value for any somewhat high frequency switching.
A MOSFET has some gate capacitance, that must be charged/discharged for the device to switch on/off. Charging that capacitance takes some time, and with low enough drive capability, pretty long time.
With low PWM frequency and  lower value of R29 you could possibly get away with driving the MOSFET like this.
For less heat losses in the P-MOSFET and/or for higher PWM frequency, you should use proper push/pull driving for the gate of Q7.


text:
Q: Cloud Database Service Latency/Performance I am running a heavy traffic site and our server is beginning to get to its limits, at the moment the entire LAMP stack is on one box (not ideal).
I would like to move the database onto it's own box or onto a cloud service, but from my previous experience moving the database off the same box as the webserver increases the latency of reads quite dramatically slowing down the site.
Is using a cloud service for this going to overcome this problem, because as far as I can tell its essentially the same situation (as moving it onto a separate box in my control)? In which case why is there so much popularity around cloud based database services at the moment?
Are cloud based database services so quick that the latency of reads is so low that its almost like having it on the same box in the same datacentre?

A: Using a cloud service just for your database won't help your situation.
If you only move the database, you're physically placing it in a remote location - which will always increase latencies, no matter how powerful the hardware serving the content.
I would suggest that you will see a benefit in hosting your database on a separate machines from your web server, so long as they are physically next to each other sharing a dedicated network (as already suggested).
If you wanted to explore the benefits of cloud services, I would suggest only doing so if you can move both database and web server together. Furthermore, it's really only of benefit if you explore load balancing across multiple web-servers and/or replicated databases. (The ability to scale dynamically is a major benefit of cloud based platforms).

A: Clouds are about paying someone else to manage the infrastructure so you don't have to. They also come with some nice benefits about being able to rapidly acquire infrastructure since you don't have to wait for physical machines to be landed you can simply tap into the "cloud's" unused capacity. Sure people build features on top of this infrastructure to make it easier to scale (this is usually programming against a certain model).
If you are thinking about a cloud when are you planning on moving to 10 servers...or 100? Do you deal with traffic that comes in large bursts where the peaks in your traffic are very high?
Since you are talking about moving to a second box I don't think you need to have the cloud discussion yet. Just add a database server and use caching like e4c5 recommended.

A: There will be increased latency going across the network, but it shouldn't be that noticeable. Gigabit ethernet is pretty fast. When you have tried splitting the boxes, how did you access the other box? You should be using a local, internal IP address (i.e. 192.168.#.#). If you are not, then your requests may get routed over the internet, even though the boxes are physically next to each other.
Moving to a cloud won't solve your problems if the servers aren't networked properly.


text:
Q: Why does xcode 4.3.2 hang when archiving? When I attempt to archive a build, xcode hangs with the colorful spinny wheel of death. It used to work fine, but I can no longer browse the archive anymore unless I delete the archive files manually. I can build to a device fine without problems though. I deleted all content from the archives manually (by deleting the actual archive files) and the archive/organizer pane shows fine, because nothing is in it (because I deleted the archives). But when I attempt to archive again, it builds, then attempts to open the archive/organizer window again, and it hangs. The archive file it does produce though is about a 30 meg archive file... But I'm afraid to use it..
While the spinny wheel of death is spinning, opening "Activity Monitor" shows the following:
"xcodebuild" has about 80% CPU usage
"opendirectoryd" has about 30% CPU usage.
I have uninstalled and reinstalled XCode 4.3.2 on Lion with no results.
I'm also building projects from Unity3D..
Someone mentioned the following in a different thread: "I had similar problems I found that a symbolic link I did was the cause of the problem from /Developer/usr/bin to /usr/bin (because Xcode 4.3 moved some of the execs)"
I have nothing like this going on. And moving all of the classes to a new "project" doesn't help because the project is created brand new each time when I build from within Unity.
XCode 4.3.2
Mac OS X (10.7.3)
Any ideas or suggestions would be very helpful to me. Anything at all.
Thanks.

A: Quick Solution: execute the following: xcode-select -switch /Applications/Xcode.app/Contents/Developer/
How I came to the solution:
Turned on opendirectoryd debug logging: "odutil set log debug"
Searched around inside the /var/logs/opendirectoryd.log files.
I kept seeing this block of logs spammed over and over again:

2012-04-12 11:29:28.420 CDT - 31053.1185984, Module: SystemCache - Signaling semaphores for more work
2012-04-12 11:29:28.420 CDT - 31053.1185984, Module: SystemCache - Finalizing response object 0x7fae5b21acb0, request is complete
2012-04-12 11:29:28.420 CDT - 31053 - Client: 'xcodebuild', exited with 0 session(s), 0 node(s) and 0 active request(s)
2012-04-12 11:29:28.421 CDT - Trigger - new node trigger watching for 'opendirectoryd:nodes;(register|unregister);.*'
2012-04-12 11:29:28.421 CDT - semaphore_wait will wait - maximum number of membership calls are already in flight
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - Client: xcodebuild, UID: 501, EUID: 501, GID: 20, EGID: 20
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - Adding to global request list - new count 1
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - mbr_identifier_to_uuid request, UID: 501
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - semaphore_wait will wait - max_active_work
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - semaphore_wait will wait - workq
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - Submitting to pipeline
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - executing request pipeline
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - Cache hit - dev14 (0x59574CC0)
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - Submitting to response pipeline
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - executing response pipeline - 0x10ba2f670
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - mbr_identifier_to_uuid completed, delivered 1 result
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - Removing from global request list
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - Signaling semaphores for more work
2012-04-12 11:29:28.421 CDT - 31053.1185985, Module: SystemCache - Finalizing response object 0x10ba2f670, request is complete
2012-04-12 11:29:28.421 CDT - 31053 - Client: 'xcodebuild', exited with 0 session(s), 0 node(s) and 0 active request(s)
2012-04-12 11:29:28.422 CDT - Trigger - new node trigger watching for 'opendirectoryd:nodes;(register|unregister);.*'
2012-04-12 11:29:28.422 CDT - semaphore_wait will wait - maximum number of membership calls are already in flight
2012-04-12 11:29:28.422 CDT - 31053.1185986, Module: SystemCache - Client: xcodebuild, UID: 501, EUID: 501, GID: 20, EGID: 20
2012-04-12 11:29:28.422 CDT - 31053.1185986, Module: SystemCache - Adding to global request list - new count 1
2012-04-12 11:29:28.422 CDT - 31053.1185986, Module: SystemCache - mbr_identifier_to_uuid request, UID: 501
2012-04-12 11:29:28.422 CDT - 31053.1185986, Module: SystemCache - semaphore_wait will wait - max_active_work
2012-04-12 11:29:28.422 CDT - 31053.1185986, Module: SystemCache - semaphore_wait will wait - workq
I searched for one of these strings in google and came up with the following solution hidden away on apple's developer forum:
"It seems that the old xcodebuild command was left lying around by the new Xcode installer. After executing 'xcode-select -switch /Applications/Xcode.app/Contents/Developer/' and a 'make clean' the project built perfectly."
Indeed, it works now. Must have been some weird symbolic link that wasn't correct. Lots of other people seem to have issues with opendirectoryd and a broken sym link causing a large CPU spike.


text:
Q: ColdFusion - Inserting arabic/persian characters to mysql I insert my data into mysql db with this code:
<cfprocessingdirective pageEncoding="utf-8">
<cfset setEncoding("URL", "utf-8")>
<cfset setEncoding("Form", "utf-8")>
<cfcontent type="text/html; charset=utf-8">

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>

<cfparam name="postTextBox" default="" type="String">

<cfoutput>
    <form action="index.cfm" method="POST" name="form">
        <input name="postTextBox" type="text"/>
        <input name="" type="submit" value="Submit" />
    </form>
</cfoutput>

<cfquery name="myQuery" datasource="hello">
    insert into ad (name)
    values(N<cfqueryparam value=#postTextBox# cfsqltype="cf_sql_varchar">)
</cfquery>

</body>
</html>

The problem is when I insert arabic or persian characters that's store in database something like "?????" but there is no problem with english characters.
I use ColdFusion 10 and mysql.
Regards

A: (From comments ...)
Check the charset of your column or table. Make sure it supports unicode characters. For example, UTF-8:
CREATE TABLE ( name varchar(500) CHARSET UTF8, ....)

Also, instead of using N'literal' syntax, you may as well use the new cfsqltype cf_sql_nvarchar. With those changes, it should work fine.
    INSERT INTO ad ( name )
    VALUES
    (
       <!--- always scope variables --->
       <cfqueryparam value="#FORM.postTextBox#" cfsqltype="cf_sql_nvarchar">
    )

Side note - Nothing to do with your question, but cfprocessingdirective has no effect here. It is used when you need to embed, or hard code, Unicode characters within a CF script. Since you are not doing that, you do not need it.

A: The issue of having "????" marks instead of Arabic Characters could be two issues; With the assumption that you are using MySQL 5, with ColdFusion 10 or 11:
First Issue: It could be that you have not setup the MySQL database to UTF-8, in order to convert all your DB to UTF-8, use the following commands on MySQL:
Use the ALTER DATABASE and ALTER TABLE commands.
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Second Issue: The ColdFusion DataSource has not been setup properly and it will need two more additional strings to be added using the ColdFusion Data Source options.
Go to the ColdFusion Administrator, and open the Data Source page and click on the data Source that you have setup already.
Data & Services > Datasources > MySQL 5
Click the Data Source Name and click Show Advanced Settings, on the Connection String feild add the following two sting values.
useUnicode=true&characterEncoding=utf8

Once after you have saved the configuration details, the ColdFusion will start converting the data in to UTF-8 charachter set, and you will have proper Arabic or Persian characters.
Note: If you are hosting with some hosting service providers, such as my hosting company, you will have to request this to be added to the Data-source for your DB from the hosting support teams, I'm sure most of the hosting companies will have no issue in adding them to you. Also note they might have a load-balancing environment, and in this case you might some times get the '????' and some times the proper 'Arabic' characters, in this case make sure they add the above string to all their CF servers on the H/A environment (i.e. this happened to me).
Hope this helps resolve the issue.


text:
Q: **STM32f427 UART with DMA** The highest bit sometimes is 1 when receive data from console I got a problem when using STM32f427 UART with DMA(using stm cube HAL library).
I would like make a console echo function, so I reply received data immediately in uart idle interrupt handler function.
But sometimes, the highest bit of received data will be 1, when I input any key in keyboard.
such as following
0x31 -> 0xB1
0x32 -> 0xB2
0x40 -> 0xC0

Does someone have any idea? the code segment as following.
Thank you very much.
My uart configuration as following
uart_handler.Instance          = USARTx;
uart_handler.Init.BaudRate     = baudrate;
uart_handler.Init.WordLength   = UART_WORDLENGTH_8B;
uart_handler.Init.StopBits     = UART_STOPBITS_1;
uart_handler.Init.Parity       = UART_PARITY_NONE;
uart_handler.Init.HwFlowCtl    = UART_HWCONTROL_NONE;
uart_handler.Init.Mode         = UART_MODE_TX_RX;
uart_handler.Init.OverSampling = UART_OVERSAMPLING_8;

My PIN and DMA channels configuration as following
GPIO_InitStruct.Pin       = USARTx_TX_PIN;
GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull      = GPIO_PULLUP;
GPIO_InitStruct.Speed     = GPIO_SPEED_HIGH;
GPIO_InitStruct.Alternate = USARTx_TX_AF;
HAL_GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStruct);
GPIO_InitStruct.Pin = USARTx_RX_PIN;
GPIO_InitStruct.Mode      = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull      = GPIO_NOPULL;
GPIO_InitStruct.Alternate = USARTx_RX_AF;
HAL_GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStruct);
hdma_tx.Instance                 = USARTx_TX_DMA_STREAM;
hdma_tx.Init.Channel             = USARTx_TX_DMA_CHANNEL;
hdma_tx.Init.Direction           = DMA_MEMORY_TO_PERIPH;
hdma_tx.Init.PeriphInc           = DMA_PINC_DISABLE;
hdma_tx.Init.MemInc              = DMA_MINC_ENABLE;
hdma_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_tx.Init.MemDataAlignment    = DMA_MDATAALIGN_BYTE;
hdma_tx.Init.Mode                = DMA_NORMAL;
hdma_tx.Init.Priority            = DMA_PRIORITY_LOW;
hdma_tx.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;
hdma_tx.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
hdma_tx.Init.MemBurst            = DMA_MBURST_INC16;
hdma_tx.Init.PeriphBurst         = DMA_MBURST_INC16;
HAL_DMA_Init(&hdma_tx);

/* Associate the initialized DMA handle to the UART handle */
__HAL_LINKDMA(huart, hdmatx, hdma_tx);

/* Configure the DMA handler for reception process */
hdma_rx.Instance                 = USARTx_RX_DMA_STREAM;
hdma_rx.Init.Channel             = USARTx_RX_DMA_CHANNEL;
hdma_rx.Init.Direction           = DMA_PERIPH_TO_MEMORY;
hdma_rx.Init.PeriphInc           = DMA_PINC_DISABLE;
hdma_rx.Init.MemInc              = DMA_MINC_ENABLE;
hdma_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_rx.Init.MemDataAlignment    = DMA_MDATAALIGN_BYTE;
hdma_rx.Init.Mode                = DMA_NORMAL;
hdma_rx.Init.Priority            = DMA_PRIORITY_HIGH;
hdma_rx.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;
hdma_rx.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
hdma_rx.Init.MemBurst            = DMA_MBURST_INC16;
hdma_rx.Init.PeriphBurst         = DMA_MBURST_INC16;

And use uart idle interrupt to receive data.
uint32_t temp;
if((__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) != RESET))
{
__HAL_UART_CLEAR_IDLEFLAG(huart);
HAL_UART_DMAStop(&uart_handler);
temp = uart_handler.hdmarx->Instance->NDTR;
g_usart_info.rx_len =  USART_DMA_RECV_LEN - temp;
g_usart_info.receive_flag = 1;
g_usart_info.usart_dma_tx_buff = g_usart_info.usart_dma_rx_buff[0] ;
memset(g_usart_info.usart_dma_rx_buff, 0,
sizeof(g_usart_info.usart_dma_rx_buff));
__HAL_UART_CLEAR_FLAG(&uart_handler, UART_FLAG_RXNE);
g_usart_info.usart_dma_rx_buff[0] = 0;
HAL_UART_Receive_DMA(&uart_handler, g_usart_info.usart_dma_rx_buff,
USART_DMA_RECV_LEN);
}

Thank you.
I traced the function of UART_Receive_IT and added debug code.
and insert break point for int a = *(huart->pRxBuffPtr - 1);
I found huart->Instance->DR is 0x31 but int a is 0xB1.
I tried to disable other interrupt but it still cannot be solved.
if(huart->Init.Parity == UART_PARITY_NONE)
      {
        *huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
                if(*(huart->pRxBuffPtr - 1) != 0x31)
                {
                    int a = *(huart->pRxBuffPtr - 1);
                    a = a;
                }
      }
      else
      {
        *huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x007F);
      }

========================================================================
I found the problem point
RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 /*| RCC_CLOCKTYPE_PCLK2*/);

If I comment RCC_CLOCKTYPE_PCLK2, this problem could be solved.
But I don't know why, it is official sample code. I think it should be right.

A: Okay, then it does sound like a clock issue.

*

*Do you have an oscilloscope? Instead of doing an echo test you could just send a known byte from the STM32. I usually send 0xAA or 0x55. Then you can measure the timing of your STM32's UART and verify if it is correct.

*Sometimes at higher clock speeds the accuracy of the peripheral's clock will decrease. You could also try to increase the speed of your system clock.

Thought: Looking at your code again I think I might have found the problem. In your UART config change
uart_handler.Init.OverSampling = UART_OVERSAMPLING_8;

to
uart_handler.Init.OverSampling = UART_OVERSAMPLING_16;

This will force the STM32 to look more finely at the incoming bytes and could resolve your problem. In my understanding 16x oversampling is the typical configuration used, even at lower UART speeds.

A: Finally, I got the root cause for this question.
I use official sample code for my board but those sample code is for official development board the board is with embedded stlink/v2 circuit and it will pass 8M hz to the STM32F4 chip for HSE clock.
But my board does not have the circuit , so I have to use external stlink/v2 module to develop my board.
So, I need to do below change.
WAS:
RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS;
IS:
RCC_OscInitStruct.HSEState = RCC_LSE_ON;
After change, my problem is be solved.
And thanks Hein Wessels for watching and help :).


text:
Q: Executing Password Change over Ruby Net-SSH I am looking to execute a password change over Net-ssh and this code seems to hang:
Net::SSH.start(server_ip, "user", :verbose => :debug ) do |session|

  session.process.popen3("ls") do |input, output, error|

    ["old_pass","test", "test"].each do |x|

        input.puts x

    end

  end

end

I know the connection works because using a simple exec I can get the output from ls on the remote server, but this hangs.
Any ideas?
The last message from debug is that the public key succeeded.

A: This one will solve your issue ,, note this script to change password for a list of servers list in file
#~~~~~~~~~~~~~~~~~~~~~~~
# Change  Password is a simple script to change the password for a list of servers
# Coded by : Sabry Saleh
# License : GPL2
#~~~~~~~~~~~~~~~~~~~~~~~
#=-Notes-=
# You have to install ruby + net-ssh gems
# sudo gem install net-ssh
#~~~~~~~~~~~~~~~~~~~~~~~

require 'net/ssh'

host = IO.readlines('test1.txt') # full path of servers' list
port = 22       # SSH port
user = 'username'   # username
  i  = 0

while i < host.length

  Net::SSH.start(host[i], user , :password => "User pass" , :port=> port) do |ssh|
    ssh.open_channel do |channel|
    channel.on_request "exit-status" do |channel, data|
      $exit_status = data.read_long
    end
      channel.request_pty do |channel, success|
      channel.exec("sudo passwd UserName")  # Logged user shuold be root or sudoers memeber
      if success
        channel.on_data do |channel, data|
          puts data.inspect.chomp("\r\n")
          channel.send_data("New pass\n") # put the New password you need to set
          sleep 0.1
        end
      else
        puts "FAILED!!"
      end
    end
    channel.wait
    puts "SUCCESS!!" if $exit_status == 0
    end
  end
i += 1
end