text:
Q: Show points (layer) from PostgreSQL database on OpenLayers map I have this code, I want to load a collection of points stored in a table in PostgreSQL database, I retreive the GeoJSON format succesfully, but the points never show up on the map!
The three files are included below: (Php file + html file + js file)
// my php file to generate the geojson format

<?php

require_once "connection.php";

// bd table to php array

function colsTabVersArray($nom_table){
    $res = array();
    $req = executerRequete("SELECT column_name FROM information_schema.columns WHERE table_name = '$nom_table'");
    while($ligne = pg_fetch_row($req)){
        $res[] = $ligne[0];
    }
    return $res;
}

// requete sql

function executerRequete($requete){
    return pg_query($GLOBALS["db"], $requete);
}

// test

        $feature = array();
        $result = executerRequete("SELECT st_asgeojson(geom) AS geom FROM nyc_subway_stations");
        if($result)

        {
            while($row = pg_fetch_assoc($result)) {
                $type = '"type": "Feature"';
                $geometry = '"geometry": '.$row['geom'];
                unset($row['geom']);
                $properties = '"properties": '.json_encode($row);
                $feature[] = '{'.$type.', '.$geometry.', '.$properties.'}';

            }
            $header = '{"type": "FeatureCollection", "features": [';
            $footer = ']}';
            if(count($feature) > 0) {
                echo $header.implode(', ', $feature).$footer;
            }
            else {
                echo '{"type":"FeatureCollection", "features":"empty"}';
            }

        }

?>

**************************************************************************

// File Map.js

data = {
    layer: true
}

actualiserCouche("couchePoint", 'couchePoint', 'Couche Point', data);
// /L'AJOUT D'UNE COUCHE

function actualiserCouche(couche, name, title, data) {

    geojson = new ol.format.GeoJSON();
    source_couche = new ol.source.Vector();

    // DÉFINITION DU STYLE DE LA COUCHE
    var myStyle = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 20,
        fill: new ol.style.Fill({color: 'black'}),
        stroke: new ol.style.Stroke({
        color: [255,0,0], width: 2
        })
      })
    })
    // /DÉFINITION DU STYLE DE LA COUCHE

    // DÉFINITION DE LA COUCHE ARRONDIS
    window[couche] = new ol.layer.Vector({
        name: name,
        title: title,
        visible: true,
        source: source_couche,
        style: myStyle
    });
    // /DÉFINITION DE LA COUCHE ARRONDIS

    // SUPPRESSION DU CONTENU DE LA COUCHE
    source_couche.clear();
    // /SUPPRESSION DU CONTENU DE LA COUCHE

    // L'APPEL AJAX AVEC LES PARAMÈTRES
    success = function (result) {
        console.log(result);
        var features = geojson.readFeatures(result, { featureProjection: 'EPSG:26918' });
        source_couche.addFeatures(features);
    }
    error_fatale = function (jqXhr) {
        console.log(jqXhr);
    }
    ajax("index2.php", data, error_fatale, success);
    // /L'APPEL AJAX AVEC LES PARAMÈTRES

    // L'AJOUT DE LA COUCHE À LA CARTE
    map.addLayer(window[couche]);
    // /L'AJOUT DE LA COUCHE À LA CARTE

}

function ajax(url, data, error, success = function (resultat) {
    if (resultat.type == "erreur") {
        console.log("erreur", resultat.msg);
    }
    else if (resultat.type == "succes") {
        console.log("succes", resultat.msg);
    }
}, complete = null, beforeSend = null) {

    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        dataType: 'JSON',
        beforeSend: beforeSend,
        success: success,
        error: error,
        complete: complete
    });
}

**********************************************************************

//File : index.html to load the map

   <link rel="stylesheet" href="plugin/open-layers/css/ol.css">

       <title>OpenLayers example</title>

My Map

Here is a part of the geojson I get in tho log on browser
{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type":"Point","coordinates":[583521.854408956,4507077.86259909]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[583324.48663246,4506805.37316021]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[583304.182399475,4506069.65404812]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590250.10594797,4518558.01992433]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590454.739989117,4519145.71961785]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590465.893419111,4519168.6974832]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590573.169495527,4520214.76617728]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[591252.83141041,4520950.35335555]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590946.3972263,4521077.31897688]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[591583.611145281,4521434.84662681]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[591242.929957587,4521581.88593774]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[593778.100679278,4521296.80231282]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[591869.966492465,4522223.76481329]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":

A: What you have got wrong is CRS specification when reading features from GeoJSON with readFeatures method. This method has two CRS options: dataProjection tells projection of GeoJSON data and featureProjection tells projection of generated features.
In your case dataProjection should be 'EPSG:26918' and featureProjection default 'EPSG:3857':
var features = geojson.readFeatures(result, {dataProjection: 'EPSG:26918', featureProjection: 'EPSG:3857' });

Here is the picture of markers, based on your sample GeoJSON:

For EPSG 26918 to work you need to define it with proj4.js library:

proj4.defs("EPSG:26918","+proj=utm +zone=18 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
ol.proj.proj4.register(proj4);


text:
Q: How can I make Cygwin pass the home directory as a path that other applications will understand, as opposed to what amount to relational links? I'm currently using Cygwin in my Z drive, but let's say I want to create and open a file in Sublime that is located in my Cygwin home directory (or somewhere in relation to it, such as through a symbolic link).
Manic@Babbage /cygdrive/z
$ ls ~
bin  desktop  programming  z

Manic@Babbage /cygdrive/z
$ touch ~/test

Manic@Babbage /cygdrive/z
$ subl ~/test

However, this simply has Sublime create a new file: Z:\home\Manic\test
Is there any way to get Cygwin to pass a full Windows-style path?  This is not an issue with Sublime--every other application I've tried to use this with has also failed.

A: cygpath converts paths. Try capturing its output by $():
subl $(cygpath -w ~/test)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kindly provide the stepwise solution for this integral. $$\int_{-b}^b\int_{-a}^a\frac{1}{(x^2+y^2+h^2)^{3/2}}dxdy$$
First I put x=$\sqrt{y^2+h^2}tan\theta$ and arrive at:
$$\int_{-b}^b\frac{2a}{(y^2+h^2)(y^2+h^2+a^2)^{1/2}}dy$$
Can you please tell me what to do after this?

A: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

Note that
  $\ds{\pars{~\mbox{with}\ a\,,\ b > 0~}}$ and
  $\ds{\pars{p \equiv {a \over \verts{h}} > 0\,,\
q \equiv {b \over \verts{h}} > 0}}$:

$$
\int_{-a}^{a}\int_{-b}^{b}{\dd x\,\dd y \over
\pars{x^{2} + y^{2} + h^{2}}^{3/2}} =
{4 \over \verts{h}}\bbox[5px,#ffd]{\ds{\int_{0}^{q}\int_{0}^{p}{\dd x\,\dd y \over
\pars{x^{2} + y^{2} + 1}^{3/2}}}}
$$

\begin{align}
&\bbox[5px,#ffd]{\ds{\int_{0}^{q}\int_{0}^{p}{\dd x\,\dd y \over
\pars{x^{2} + y^{2} + 1}^{3/2}}}} \,\,\,\stackrel{y\ \mapsto\ {1/y}}{=}\,\,\,
\int_{0}^{p}\int_{1/q}^{\infty}{y\,\dd y \over
\bracks{\pars{x^{2} + 1}y^{2} + 1}^{3/2}}\,\dd x
\\[5mm] \stackrel{y^{2}\ \mapsto\ y}{=} &\
{1 \over 2}\int_{0}^{p}\int_{1/q^{2}}^{\infty}{\dd y \over
\bracks{\pars{x^{2} + 1}y + 1}^{3/2}}\,\dd x =
-\int_{0}^{p}{1 \over x^{2} + 1}\left.%
{1 \over \bracks{\pars{x^{2} + 1}y + 1}^{1/2}}
\right\vert_{\ y\ =\ 1/q^{2}}^{\ y\ \to\ \infty}\,\dd x
\\[5mm] = &\
q\int_{0}^{p}{1 \over x^{2} + 1}
{1 \over \bracks{\pars{x^{2} + 1} + q^{2}}^{1/2}}\,\dd x
\,\,\,\stackrel{x\ \mapsto\ {1/x}}{=}\,\,\,
q\int_{1/p}^{\infty}
{x\,\dd x \over \pars{x^{2} + 1}\bracks{\pars{q^{2} + 1}x^{2} + 1}^{1/2}}
\\[5mm] \stackrel{x^{2}\ \mapsto\ x}{=}\,\,\,&
{1 \over 2}\,q\int_{1/p^{2}}^{\infty}
{\dd x \over \pars{x + 1}\bracks{\pars{q^{2} + 1}x + 1}^{1/2}}
\end{align}

With the change of variable
  $\ds{x \equiv {t^{2} - 1 \over q^{2} + 1}}$:

\begin{align}
&\bbox[5px,#ffd]{\ds{\int_{0}^{q}\int_{0}^{p}{\dd x\,\dd y \over
\pars{x^{2} + y^{2} + 1}^{3/2}}}} =
q\int_{\root{p^{2} + q^{2} + 1}/p}^{\infty}{\dd t \over t^{2} + q^{2}} =
{\pi \over 2} - \arctan\pars{\root{p^{2} + q^{2} + 1} \over pq}
\\[5mm] = &\
\arctan\pars{pq \over \root{p^{2} + q^{2} + 1}}
\end{align}

$$
\bbx{\ds{\int_{-a}^{a}\int_{-b}^{b}{\dd x\,\dd y \over
\pars{x^{2} + y^{2} + h^{2}}^{3/2}} =
{4 \over h}\,\arctan\pars{ab/h \over \root{a^{2} + b^{2} + h^{2}}}}}
$$

A: If we substitute
$$y=\sqrt{a^2+h^2}\tan u$$
$$dy=\sqrt{a^2+h^2}\sec^2u \text{ }du$$
We get the integral
$$\int \frac{2a(\sqrt{a^2+h^2}\sec^2u)}{((a^2+h^2)\tan^2u+h^2)((a^2+h^2)\tan^2u+a^2+h^2)^{1/2}}du$$
Remembering that $\tan^2x+1=\sec^2x$, we get
$$\int \frac{2a\sqrt{a^2+h^2}\sec^2u}{((a^2+h^2)\sec^2u -h^2)((a^2+h^2)\sec^2u)^{1/2}}du$$
Now you can simplify quite a bit.
Hope this helps!


text:
Q: htaccess rewriterule and directoryindex I'm having issues with my rewriterule and directory index
DirectoryIndex invite.php about.php account.php

RewriteRule ^/?([a-z0-9_-]+)/?$ /user.php?u=$1 [L]

Lets say about.php is in the about folder. When i go to www.url.com/about/about.php, it works fine. But when I go to www.url.com/about/, it goes to my user.php page. When I go to www.url.com/about, (without ending slash), it goes to www.url/about/?u=about
Can anyone help me?
At the same time, I'm trying to set up where user can go to www.url.com/andrewliu instead of www.url.com/user.php?u=andrewliu
I guess I need to somehow fix my ending slash and the redirect?
Thanks!
EDIT
I have this
DirectoryIndex invite.php about.php account.php

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteRule ^/?([a-z0-9_-]+)/?$ /user.php?u=$1 [L]
RewriteCond %{QUERY_STRING} !^b= [NC]
RewriteRule ^(business)/(.*)$ /$1/index.php?b=$2 [L,NC,QSA]

A: You need to add a check to see whether the request is for a file or directory that exists. You need to add these conditions before your rule:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([a-z0-9_-]+)/?$ /user.php?u=$1 [L]

This makes it so when you go to /about/, since it's a directory that exists, this rule won't be applied. But if you go to /andrewliu, it will be as long as that's not a file or directory.


text:
Q: Sending a post request with parameters in php to get Json data I'm trying to get some json data from another server that needs 3 parameters so that I can access it. I saw this code in internet but its not working. I have searched a lot and I haven't found a solution. When I run this code I get :

use pass and code are missing

(is the response from the server I'm requesting), I hope I made things clear if there's anything I didn't explain please do tell.
    $url = 'http://xxxx/.js';
    $data =http_build_query(array('user' => 'xx',
            'pass' =>'xxx ',
               'code' =>'xxx')
  );

    $options = array(
   'http' => array(
    'header'  => "Content-type: application/json\r\n",
    'method'  => 'POST',
    'content' => $data
    )
    );
     $context= stream_context_create($options);
     $result = file_get_contents($url, false, $context);
      if ($result === FALSE) { }

     echo $result ;

A: Try to change your payload to json...
$data = json_encode( array(
  'user' => 'xxx',
  'pass' => 'xxx',
  'code' => 'xxx'
) );

and to remove \r\n from your content type
"Content-type: application/json"


text:
Q: AWS Mobile Hub - How to Implement User Sign In Without Storyboard I am currently working on a project that does not include storyboards and I am trying to create a user authentication and sign-in method. I was initially going to use FireBase but they did not have Carthage support so I decided to try out AWS. I initially tried using AWSCognitoIdentityProvider framework with my custom UI but the passwordauthentication method for signing in would not trigger a result. I moved onto the AWSAuthUI framework (plus AWSAuthCore, AWSFacebookSignIn, AWSGoogleSignIn, AWSUserPoolsSignIn) with the built in UI but I keep getting the error below before even getting to the login screen.
" Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Could not find a storyboard named 'SignIn' in bundle NSBundle "
From all the documentation and demo applications that I've seen, I guess this is not possible without using storyboards? Can someone please confirm this.

A: You will need to add the Storyboard files in the Build Phases if you are using Carthage: See an example here: https://github.com/aws/aws-sdk-ios/pull/733/files. Currently the AuthUI implements the UI components in a storyboard file.


text:
Q: Specifying directory as an input within Python Regex I am trying to extract a particular text from a filename using regex and I am able to do so if I pass only one filename as an input. However, I want to do the same for all the filenames in a particular directory. I understand that re.search can only accept string as an input? Is there a way to pass the directory as an input?
Below is the code I am using,
import os
import sys
import re
firstarg=sys.argv[1]
a = str(firstarg)
m = re.search(r'(?<=T)(.*)(?=\()', os.listdir( a )).group()
print (m)

A: This will print an array of strings that match the regex.
This will run the regex over each file and folder in the directory,
and if any file or folder contains a match, that match is appended to the array 'm'
Note: Not Recursive.
import os
import sys
import re

firstarg=sys.argv[1]
a = str(firstarg)
files = os.listdir(a)
m = []

for f in files:
    match = re.search(r'(?<=T)(.*)(?=\()', f)
    if( match != None):
        m.append( match.group() )

print (m)

Example:
sys.argv[1] = '/'

File Tree:

*

*/

*

*File_Tvalue1(

*File_Tvalue2(

*Folder_Tvalue3(

*

*File_Tvalue4(

Result:
['value1', 'value2', 'value3']
If you want it to be Recursive and a function.
import os
import sys
import re
def FindMatchesInDirectory(directory, afterRegex, beforeRegex, recursive=True):
    results = []
    for r, d, f in os.walk(directory):
        for path in f:
            match = re.search(r'(?<='+str(afterRegex)+')(.*)(?='+str(beforeRegex)+')', str(path))
            if( match != None):
                results.append( match.group() )
        for path in d:
            match = re.search(r'(?<='+str(afterRegex)+')(.*)(?='+str(beforeRegex)+')', str(path))
            if( match != None):
                results.append( match.group() )
        if ( recursive != True):
            break
    return results

Example: Get All matches recursively. Any value Between 'T' and '('
print (FindMatchesInDirectory(sys.argv[1], 'T', '\('))

Result:
['value3', 'value2', 'value1', 'value4']
Example: Get All matches without recursion
print (FindMatchesInDirectory('/', 'T', '\(', False))

Result:
['value3', 'value2', 'value1']


text:
Q: W, A, S, D, keys and shift aren't working together W, A, S, D, left Shift, left Ctrl keys work individually, but when pressed together, it does not work. This prevents me from sprinting. Right shift and ctrl works fine with other keys. I have a Coolermaster keyboard, not even a year old. Should I take it to the service centre? Anyone have any solutions to offer?

A: This is a lmitation related to the construction method of the keyboard.
Most consumer keyboards will not allow you to press more than 3 closeby buttons because it uses a grid system to understand which button you are pressing.
So for example if you are pressing QDB and 9 would work as they do not share any "coorinates" immagine every row and every column of Keys being connected and your keyboard knows which key you are pressing only based on these coordinates trough electric signals.
If you press for example WS and D  most keyboard will not be able to notice all of these Keys since there are overlapping connections (namely W,  and S share vertical and S and D share horizontal).
You can easily see this on a text editor: press and keep down the W and S Keys and then start hittind the D key.
Chances are you will not see any "D" characters being written.
the exact combination of characters may vary depending on the way your particular keyboard has been built, CTRL ALT and some other buttons have their own dedicated "lines" so they will generally not have issues of this kind.
What you need to look for in your keyboard when buying one is:

*

*The key rollover as this is the name of this issue, 3KRO is most likely what you have, NKRO is a keyboard that would allow you to press multiple Keys at once.

An anti-ghosting function, on the other side, prevents your keyboard from registering Keystrokes you are not in fact pressing.
This could happen because both the coordinates corresponding to the character are shown as "connections".
Almost every keyboard has this feature nowadays since it is considered a critical failure when ghosting happens.
In definitive this is a physical problem and you need an N-KRO (no key rollover)keyboard to press all the Keys and not have this issue or at the very least a higher number of Keys before rollover.
Taking your keyboard to the service center will solve nothing and depending on the shop and how long you've had your peripheral you might not be able to get a refund either
You can find more informations here, particularly on why this is not a problem you can solve trough software: How do I remove the limit on PC keyboard button presses?


text:
Q: Interactive, restrictive, dynamic user input I provided a link to a PDF of the assignment instructions.
[TL;DR]
Ask two questions: Are you afraid of the dark? Do you exercise?
Input: 'Y' for yes, 'N' for no.
If input to second question is 'Y', One additional question:  Minutes per day exercised?
Input: Integer > 0. However, if less than 10 per day, unqualified.
Output: Tells the user whether they can to enter ninja training or not.

What I'm having difficulties with:

*

*Dynamically Allocating a Multidimensional String Array

I have only been coding for about a week, and I understand it's probably overkill for this assignment. With that being said, I got an idea while doing this assignment, and while I find it rather challenging to articulate my idea with words, here's an image that I feel captures what I am "visualizing."
Visual posted on https://www.eskimo.com/~scs/cclass/int/sx9b.html by Steve Summit
In this particular assignment, I think it's a waste of memory to keep the user's answer's. Nevertheless, what if I want to write a program that ask the user for a series of inputs, and at the end, correlate them, or make spurious correlations for teh lulz?
Spurious Correlations http://www.tylervigen.com/spurious-correlations by Tyler Vigen
A more practical reason, however, an MBTI Personality Type test? I don't know exactly all the possibilities, but they seem exciting.
That's what I want to achieve with dynamically allocating a multidimensional string array

Will update later
Original post follows...
The code works but some inputs are still allowed, namely any characters entered  if the the first element is either Y or N.
Here's the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char reference[][2] = { "Y", "N" };
    char (*ptr_reference)[2] = reference;

    int reference_minutes[1] = { 10 };
    int *ptr_reference_minutes = reference_minutes;

    char **user_input;

    user_input = (char**)malloc(3 * sizeof(char*));

    int i;
    for (i = 0; i < 3; i++)  {
        user_input[i] = (char*)malloc(4 * sizeof(char));
    }
    if (!user_input) {
        printf("Could not allocate memory!/n");
        exit(1);
    }

    i = 0;
    while (i == 0) {
        printf("\nAre you afraid of the dark? Choose either [Y/N], and press enter when finished: \n");
        fgets(user_input[i], 4, stdin);
        user_input[i] = realloc(user_input[i], sizeof(char));

        if (strncmp(user_input[i], *ptr_reference, 1) == 0) {
            printf("\nPatience, Young Grasshoper! You are not ready to become a ninja.");
            i = 3;
            break;
        } else if (strncmp(user_input[i], *(ptr_reference + 1), 1) == 0) {
            i++;
            break;
        } else {
            printf("\nPlease enter Y for yes or N for no.\n\n");
            continue;
        }
    }
    while (i == 1) {
        printf("\nDo you exercise? Input [Y/N], and press enter when finished: \n");
        fgets(user_input[i], 4, stdin);

        if (strncmp(user_input[i], *ptr_reference, 1) == 0) {
            i++;
            break;
        } else if (strncmp(user_input[i], *(ptr_reference + 1), 1) == 0) {
            printf("\nDo you even lift, Bro?");
            i = 3;
            break;
        } else {
            printf("\nPlease enter Y for yes or N for no.\n\n");
            continue;
        }
    }
    while (i == 2) {
        int sscanf_result, answer;

        printf("\nHow many minutes a day do you exercise? Type an integer greater than 9 and press enter when finished.\n");
        fgets(user_input[i], 4, stdin);

        sscanf_result = sscanf(user_input[i], "%d", &answer);

        if ((sscanf_result == 0) | (sscanf_result == EOF)) {
            /* either a non-integer entered or an end-of-line */
            printf ("\nYou have to enter an integer!\n");
            i = 2;
            continue;
        } else if (answer < *ptr_reference_minutes) {
            printf("\nCome on! You kids are soft! You lack discipline!\n");
            i = 3;
            break;
        } else {
            printf("\nYou are a good fit for ninja training.\n");

            for (i = 0; i < 3; i++) {
                free(user_input[i]);
            }
            free(user_input);
            user_input = NULL;
            break;
        }
    }
    return 0;
}

A: Ok, I could have a look at your program. The problem is not really in allocation but is indeed in string management. In C a string is a null terminated char array (please copy this 100 times...).
When you read a line with fgets, you get the new line character (\n) in your buffer, so if user types Y Enter you get {'Y', '\n', '\0', undeterminated_char }. The following realloc is then plain wrong:

*

*it is likely to be a noop: the compiler shall only give you a buffer at least as large as your requirement. As 4 > 1, it can (and my implementation did) give the original buffer unchanged

*you are not allowed to use anything past what you have required, and in particular, you shall not assume that there is a null!

So if you insist in doing a string comparison, you should only ensure that the second char is null: user_input[i][2] = '\0';
But IMHO what is required here is just:
if (user_input[i][0] == 'Y') {
    ...

That is not all. You try to do a great job in input processing, but just forgot one detail: if a line is longer than the declared size, fgets fills its buffer and leaves the remaining part of the line available for next read.
What follows is only my advice:
You have tried to use everything you know (and probably things you do not fully master...) into a single and simple program. Don't. Keep each program as simple as possible (Keep It Stupid Simple is a general good practice...), and trust your learner to give you other assignments for other patterns. So here you should:

*

*read a line until you find the \n (it might require several fgets)

*test the first character of the buffer to be 'Y' or 'N'

*test the second one to '\0'
As it is a common requirement in real world, and only after your program works, you could considere:

*

*ignoring initial blank characters

*accept lower case as upper case

*accept any character after first one (in order to accept Yes and No)

Last advice if nice coding matters for you: once your program works correctly, you should considere posting it in Code Review to get interesting comments on it.

A: @Serge Ballesta @Serga Ballesta Thank you kindly for your feedback. It was extremly helpful. After following your advice,  I was able to write a better program, although, I'm not sure if I was successful in "Keep It Simple, Stupid."
I still can't figure out how to restrict characters after 'Y' or 'N', i.e., Nnb or Nq is accepted as N and goes through to the second question.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main (void) {

char *user_input = NULL;
user_input = (char*)malloc(3*sizeof(char));

int sscanf_result, answer;
int i;
while (!*user_input)
{
printf("\nAre you afraid of the dark? \n\nInput Specifications: Please type 'Y' to indicate yes, or 'N' to indicate no, and then press the 'Enter' or 'return' key when finished.\n\n");

i = 0;
fgets(user_input, sizeof(user_input), stdin);

/* trim off last character */
user_input[strlen(user_input)-1] = '\0';

if (user_input[i]  == 'Y')
{
printf("\nFear of the dark? Fear those who lurk in the dark, my friend. Ninjas! You may not train as a ninja!");

free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
}
exit(0);
}
else if (user_input[i]  == 'N')
{
free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
}
printf("\nDo you exercise?\n\nInput Specifications: Please type 'Y' to indicate yes, or 'N' to indicate no, and then press the 'Enter' or 'return' key when finished.\n\n");

i = 0;
fgets(user_input, sizeof(user_input), stdin);
user_input[strlen(user_input)-1] = '\0';
if (user_input[i]  == 'N')
{
printf("\nDo you even lift, Bro?\n");

free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
}
exit(0);
}
else if (user_input[i]  == 'Y')
{
free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
}
printf("\nHow many minutes a day do you exercise?\n\nInput Specifications: Please type a positive integer and press the 'Enter' or 'return' key when finished.\n\n");

i = 0;
fgets(user_input, sizeof(user_input), stdin);
user_input[strlen(user_input)-1] = '\0';

sscanf_result = sscanf(user_input, "%d", &answer);

if ((sscanf_result == 0) | (sscanf_result == EOF))
{
/* either a non-integer entered or an end-of-line */

printf ("\nPlease type a positive integer and then press the 'Enter' or 'return' key when finished.\n");

free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
}
continue;
}
if (answer < 10)
{
printf("\nCome on! You kids are soft! You lack discipline!\n");

free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
 }
 exit(0);
 }
else
{
printf("\nYou may begin training as a ninja!\n");

free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
}
exit(0);
}
}
else
{
printf("\nInput Error: Please carefully read the input specifications that are provided after each question prompt and then try again.\n");

free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
}
continue;
}
}
else
{
printf("\nInput Error: Please carefully read the input specifications that are provided after each question prompt and then try again.\n");

free(user_input);
for (i = 0; i < 3; i++)
{
user_input[i] = '\0';
}
continue;
}
}
return 0;
}


text:
Q: C passing structure to a callback function (Tizen) I'm writing an app for Tizen (smart watches). Can't pass a structure to a callback.
My typedef:
typedef struct _Health {
    ...;
    const char *data;
} health_s;

Declaring a structure and initializing it:
health_s health = {
    ...,
    .data = "steps"
};

Passing it to a function:
_app_check_and_request_permission("http://tizen.org/privilege/healthinfo", &health);

Getting and checking if the struct address passed well:
void _app_check_and_request_permission(const char *privilege, void *user_data)
{
    health_s *p_health = user_data;
    dlog_print(DLOG_INFO, LOG_TAG, "Health data: %s", p_health->data);
    ...

And here I see in the log "Health data: steps". Passed well. Then I'm trying to pass user_data to a callback function
    ...
    ppm_request_permission(privilege, _app_request_response_cb, p_health);
}

From function description in Tizen docs:
...
* @param[in]   user_data   User specific data which will be passed to
*                          the given callback.
int ppm_request_permission(const char *privilege,
                           ppm_request_response_cb callback,
                           void *user_data);

Callback declaration:
static void _app_request_response_cb(ppm_call_cause_e cause, ppm_request_result_e result,
                             const char *privilege, void *user_data);

And in the callback I'm getting Health data: NULL. Tried to pass p_health->data to the callback and that's ok. The problem is with passing the whole structure.
What am I doing wrong? Thanks.
Update:
Checked the addresses of the passed structure in the _app_check_and_request_permission function and in the callback and they are the same. But the struct in the callback is still empty...

A: Probably the lifetime of health has ended before _app_request_response_cb is called by the system on completion of the request. This is, for example, the case if the shown definition of health is contained in a function which returns before the request completes. Simple remedy: define health with storage class static.


text:
Q: Cannot get image to save in desired directory using imagepng() I am converting text to image using PHP's imagettftext function and then saving it to the server. The problem I'm having is getting it to save in the directory that I want, it has no problems saving to the current directory where the script runs.
Here is my code:
function txt2img($text, $fSize)
{
// Path to our font file
$fType = 'verdana.ttf';

// First we create our bounding box for the text
$bbox = imagettfbbox($fSize, 0, $fType, $text);

// We calculate the width and height using the x and y points.
// Width is: upper right corner, X position - upper left corner, X position
$width = $bbox[4] - $bbox[6] + 8;

// Height is: lower left corner, Y position - upper left corner, Y position
$height = $bbox[1] - $bbox[7] + 4;

// Determine the x position for the text to start
$x = 2;

// Determine the y position for the text to start
$y = $height - 4;

// Create the image
$im = imagecreatetruecolor($width, $height);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Create the background color to match the website
$default = imagecolorallocate($im, 255, 238, 198);

// Set the background color
imagefilledrectangle($im, 0, 0, $width, $height, $default);

// Write it
imagettftext($im, $fSize, 0, $x, $y, $black, $fType, $text);

// Set the location to save the image.
//$save = "email_address.png";
$save = "../images/contact/email_address.png";

// Set the folder permissions to allow us to write to the folder.
chmod("../images/contact/",0755);

// .png tends to look better than a .jpg
imagepng($im,$save);
imagedestroy($im);
// Return the image dimensions so they can be stored in the database. This is used to properly diplay the image on the front end.
return ($width."+".$height);
}

If I use the $save location that is commented out, it works perfectly fine, it just isn't in the directory that I want it to be in. I have tried other paths, such as "/images/contact/email_address.png" but no joy. This also worked without the "chmod" permission change, I just added it as another option for troubleshooting. I have also gone directly to the folder and set the permissions for the user, again, no joy.
I'm running this on a local WAMP server. Also, $text has been checked and $fSize is the font size, which has also been checked. Because this works so well in the current directory, I feel this is not a coding issue as much as it is a directory issue, but that's just my view.

A: So it does save in the folder you're working in as per the commented out save. Have you tried images/contact/email_address.png"; and /images/contact/email_address.png"; without the dots ? The dots are going up a level and if that's above the root it will be unaccesable to php


text:
Q: Почему z-index не работает? Здравствуйте!
Подскажите, почему в данном случае свойство z-index, присвоенное блоку, в котором выводится карта ОСМ, не перекрывает карту и не отображает внутреннюю тень блока? Спасибо.
A: Внутренняя тень не будет работать при такой верстке, можете даже не мучатся. Рамку с тенью можете наложить отдельно. Либо целиком, совместив со св-вом pointer-events: none; (которое не везде работает). Либо добавив каждую сторону отдельно


text:
Q: How to add icons to the launcher on Ubuntu Touch? I would like to add an icon for Terminal and a couple of icons
for my own scripts to the launcher on my Ubuntu Touch. How can I
do that?

A: In recent builds, when you launch an app from the dash it's icon will appear in the Launcher while it is running.  You can then long-press on it's icon to get a menu which has an option to "Pin to Launcher".


text:
Q: Date/time conversion to user's local time - issue My application grabs a date / time from a remote server which is alway in GMT +1 (UTC/GMT +1 hour) timezone.
The format the server is providing is :

24 08 2011 08:45PM

I would like to convert this time stamp into the equivalent time/date of the users time zone (the user can be anywhere in the world).
thus as an example :
24 08 2011 08:45PM coming from the server should be presented
24 08 2011 09:45PM to an Italian user (rome) (GMT + 1)
This code works on some timezones but i have a bad feeling that there is something very wrong about it and that there is a much more elegant way to do it
NSString *dateString = @"24 08 2011 09:45PM";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
    NSDate *dateFromString = [[[NSDate alloc] init] autorelease];
    dateFromString = [dateFormatter dateFromString:dateString];

    NSDate* sourceDate = dateFromString;
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;
    NSString *thePubDate =  [dateFormatter stringFromDate:destinationDate];//[appLogic getPubDate];
    NSLog(@"Result : %@",thePubDate);
    [dateFormatter release];
    //[dateFromString release];
    [destinationDate release];

I will appreciate your thoughts and suggestions on the matter

A: Just set the timeZone in the dateFormatter, This code is enough
NSString *dateString = @"24 08 2011 09:45PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"];
[dateFormatter setTimeZone:sourceTimeZone];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];

The dateFromString will now have the date 24 08 2011 08:45PM(GMT).. Then to convert this to string with local time just code the following,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSString *stringFromDAte = [dateFormatter stringFromDate:dateString];


text:
Q: Can not start mysqld, unsupported engine InnoDB I am trying to start mysqld on one of my data nodes in NDBCluster.  The node connects to the management server correctly, but when trying to start mysqld, the start fails when it encounters an old InnoDB table I have.  I have edited my.cnf to include
[mysqld]
innodb=OFF
default-storage-engine=ndbcluster

and these changes are noted in the output of the mysqld start, yet it continues to fail when encountering the InnoDB table later.  Any thoughts?
Included below is the output of
mysqld --defaults-file=/etc/my.cnf

2015-11-02 11:43:11 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2015-11-02 11:43:11 6089 [Warning] Can't create test file /usr/local/mysql-cluster-gpl-7.3.7-linux-glibc2.5-i686/data/tigershark.lower-test
2015-11-02 11:43:11 6089 [Warning] Can't create test file /usr/local/mysql-cluster-gpl-7.3.7-linux-glibc2.5-i686/data/tigershark.lower-test
2015-11-02 11:43:11 6089 [Warning] Buffered warning: Changed limits: max_open_files: 1024 (requested 5000)

2015-11-02 11:43:11 6089 [Warning] Buffered warning: Changed limits: table_cache: 431 (requested 2000)

2015-11-02 11:43:11 6089 [Note] Plugin 'FEDERATED' is disabled.
2015-11-02 11:43:11 6089 [Warning] The option innodb (skip-innodb) is deprecated and will be removed in a future release
2015-11-02 11:43:11 6089 [Note] Plugin 'InnoDB' is disabled.
mysqld: Can't find file: './mysql/plugin.frm' (errno: 13 - Permission denied)
2015-11-02 11:43:11 6089 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
2015-11-02 11:43:11 6089 [Note] NDB: Changed global value of binlog_format from STATEMENT to MIXED
2015-11-02 11:43:11 6089 [Note] NDB: NodeID is 5, management server '10.0.1.211:1186'
2015-11-02 11:43:12 6089 [Note] NDB[0]: NodeID: 5, all storage nodes connected
2015-11-02 11:43:12 6089 [Warning] NDB: server id set to zero - changes logged to bin log with server id zero will be logged with another server id by slave mysqlds
2015-11-02 11:43:12 6089 [Note] Starting Cluster Binlog Thread
2015-11-02 11:43:12 6089 [Note] NDB Binlog: Ndb object created with reference : 0x80040005, name : Ndb Binlog schema change monitoring
2015-11-02 11:43:12 6089 [Note] NDB Binlog: Ndb object created with reference : 0x80050005, name : Ndb Binlog data change monitoring
2015-11-02 11:43:12 6089 [ERROR] Unknown/unsupported storage engine: InnoDB
2015-11-02 11:43:12 6089 [ERROR] Aborting

2015-11-02 11:43:12 6089 [Note] Binlog end
2015-11-02 11:43:12 6089 [Note] Stopping Cluster Utility thread
2015-11-02 11:43:13 6089 [Note] Stopping Cluster Binlog
2015-11-02 11:43:13 6089 [Note] Stopping Cluster Index Stats thread
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'partition'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'BLACKHOLE'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'ARCHIVE'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'ndb_transid_mysql_connection_map'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'ndbinfo'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'ndbcluster'
2015-11-02 11:43:13 6089 [Note] Stopping Cluster Index Statistics thread
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_METRICS'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_CMPMEM'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_CMP'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_LOCKS'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'INNODB_TRX'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'MRG_MYISAM'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'CSV'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'MyISAM'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'MEMORY'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'sha256_password'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'mysql_old_password'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'mysql_native_password'
2015-11-02 11:43:13 6089 [Note] Shutting down plugin 'binlog'
2015-11-02 11:43:13 6089 [Note] mysqld: Shutdown complete

A: The entire tree needs to have suitable file/directory permissions for mysqld.
Also, you should probably allow MySQL to open more than 1024 files.


text:
Q: How to fix nuxt auth page reload problem? When I log in with nuxt auth, I redirect the user to his profile page. But after reload on the profile page I get an error like the screenshot:

I have searched this problem related to @nuxtjs/auth-next ssr problem. Most of the solution is to downgrade the @nuxtjs/axios version. I have already tried this but not fixed.
Here is my profile page code:
<template>

Profile Details

{{$auth.user.name}}

Email: {{$auth.user.email}}

Phone: {{$auth.user.phone}}

Last Login: {{$auth.user.lastLoginForHuman}}

                <nuxt-link to="/customer/change-password" class="block mt-3 text-primary-500 text-sm hover:underline">Change Password</nuxt-link>

                <input-field label="First name"></input-field>
                <input-field label="Last name"></input-field>
                <input-field type="email" label="Email"></input-field>
                <input-field label="Phone"></input-field>

                <button-field label="Update" class="bg-primary-500 text-white py-3 px-10"></button-field>

</template>

"@nuxtjs/auth-next": "^5.0.0-1624817847.21691f1",
"@nuxtjs/axios": "^5.13.6",
"nuxt": "^2.15.7"


text:
Q: Autowired Jersey ContainerRequestContext into Spring bean I have a Jersey+Spring project and I would like to retrieve some data from ContainerRequestContext without passing the ContainerRequestContext instance all the way from the controller to the bottom layer spring service. So is there any way that I can inject/autowired ContainerRequestContext into a Spring bean?
Or any other more proper solutions which meet the requirement are welcome.


text:
Q: How to run two PostGIS versions in parallel on Windows? I'm trying to understand how to install PostGIS2.0 on Windows7. The PostGIS site has the following suggestions:

PostGIS Experimental Binaries PostGIS 2.0.0SVN Binaries with Raster,
  Topology support + Extras (Tiger Geocoder 2010) As of November 25th,
  2011 (r8242) includes GEOS 3.3.2dev r3516, Proj 4.6.1, JSON-c 0.9,
  libgdal 1.9 SVN r23320 (VERSIONS prior to (r7923) require a dump
  reload since operators have changed. We now have the 3D spatial
  indexes, 3D box operators, KNN GIST for 9.1, and 2 raster map algebra)
More details about what has been fixed/added can be found at PostGIS
  2.0.0 and PostGIS 1.5.3/1.5.4 fixes , What is new in PostGIS 2.0, PostGIS Raster support, and improved Topology support These are 32-bit
  binaries so will not work on 64-bit PostgreSQL. We are working on
  getting 64-bit binaries out as well, but are running into some
  stumbling blocks. For the time being -- if you are on Windows 64-bit,
  you must install the 32-bit PostgreSQL to use these.
For PostgreSQL 8.4 w/ Loader/Dumper including GUI
For PostgreSQL 9.0 (compiled against PostgreSQL 9.0.3) w/ Loader/Dumper including GUI
For PostgreSQL 9.1 (compiled against PostgreSQL 9.1.0 - note 9.1 structure changed in beta 1 so this will not work with alpha releases

but should be fine for all beta, release candidate releases and final
  9.1.0 release) w/ Loader/Dumper including GUI. Also includes extensions files to install using new PostgreSQL 9.1+ CREATE EXTENSION
  syntax. To install:
First copy the share/extension files into your PostgreSQL share/extension folder.

Then in any database you'd like to spatially enable, run at least postgis (which contains both geometry and raster support) and

optionally postgis_topology commands.
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_topology;

I currently have PostGIS 1.5 installed on PostgreSQL 8.4. This is what my folder structure looks like:

I don't fully understand these instructions:

First copy the share/extension files into your PostgreSQL
  share/extension folder.
Then in any database you'd like to spatially enable, run at least
  postgis (which contains both geometry and raster support) and
  optionally postgis_topology commands.

I've downloaded postgisgui_pgadmin-2.0.0svn and postgis-pg84-binaries-2.0.0svn. In my original folder structure I don't have a folder extension within share. Do I just copy the contents of postgis-pg84-binaries-2.0.0svn into this folder? What does it mean to run at least postgis? I've also tried to follow the detailed instructions at the following blog.

EDIT: I have installed Postgresql 9.1 with PostGIS 1.5.3. I am trying to figure out where to copy the PostGIS 2.0 binaries. It seems like I should be copying them into the folders here:

but the advice suggests placing them in the share/extension folder.
I tried copying the entire folder into share/extension/ and then editing the makepostgis.bat file to make it relevant to my file system (the port is 5434 as I have two instances of Postgresql running).
set PGPORT=5434
set PGHOST=localhost
set PGUSER=postgres
set PGPASSWORD=****
set THEDB=template_postgis20
set PGBIN=C:\Program Files (x86)\PostgreSQL\9.1\bin\
set PGLIB=C:\Program Files (x86)\PostgreSQL\9.1\lib\

When I run this file as an administrator, I get the following error:
C:\Windows\system32>set PGPORT=5434
C:\Windows\system32>set PGHOST=localhost
C:\Windows\system32>set PGUSER=postgres
C:\Windows\system32>set PGPASSWORD=****
C:\Windows\system32>set THEDB=template_postgis20
C:\Windows\system32>set PGBIN=C:\Program Files (x86)\PostgreSQL\9.1\bin\
C:\Windows\system32>set PGLIB=C:\Program Files (x86)\PostgreSQL\9.1\lib\
C:\Windows\system32>set POSTGISVER=2.0
C:\Windows\system32>xcopy bin\*.* "C:\Program Files (x86)\PostgreSQL\9.1\bin\"
File not found - *.*
0 File(s) copied

C:\Windows\system32>xcopy /I /S bin\postgisgui\* "C:\Program Files (x86)\PostgreSQL\9.1\bin\\postgisgui"
File not found - *
0 File(s) copied

C:\Windows\system32>xcopy lib\*.* "C:\Program Files (x86)\PostgreSQL\9.1\lib\"
File not found - *.*
0 File(s) copied

C:\Windows\system32>"C:\Program Files (x86)\PostgreSQL\9.1\bin\\psql"  -c "CREATE DATABASE template_postgis20"
ERROR:  database "template_postgis20" already exists

C:\Windows\system32>"C:\Program Files (x86)\PostgreSQL\9.1\bin\\psql"  -d "template_postgis20" -c "CREATE LANGUAGE plpgs
ql"
ERROR:  language "plpgsql" already exists

C:\Windows\system32>"C:\Program Files (x86)\PostgreSQL\9.1\bin\\psql"  -d "template_postgis20" -f "share\contrib\postgis
-2.0\postgis.sql"
share/contrib/postgis-2.0/postgis.sql: No such file or directory

....the errors continue....

A: I've updated the instructions on the website.  Hope it's a bit clearer.
Nicklas is right you don't really need the makepostgis.bat if you just copy the like folders to your postgresql install  (you could also remark out the create db in it since it does copy all the files).  You should be able to just overlay ontop since the zip structure is the same as standard windows enterprisedb packaged PostgreSQL binaries.  What I neglected to mention in the instructions is that you do still need the binaries and libs.  This I have updated so its should be clearer.
We don't have the create extension approach as the official for PostgreSQL 9.1 yet since we are working out some issues with using the ALTER EXTENSION postgis UPGRADE .. syntax
which is more of an issue with PostGIS 2.0 non-released since there are no official freeze points yet.  In the currently packaged it works fine but its harder to ensure it works given all the flux of stuff going on in PostGIS 2.0 in the past month.

A: Edit:
The reason that you don't have the extension folder is that you are not on PostgreSQL 9.1 when the extension feature was introduced.
What you should do is put the binaries in the bin-folder as described in the beginning of the readme-file.
Then running postgis means that you are supposed to run the sql-code in the file postgis.sql to install the types and functions in PostGIS into the database. To install raster and topology you will also have to run thosose files.
You can read about that in the installation part of the doc.
/Nicklas


text:
Q: $\lim_{x\to0}\dfrac{1}{x}-\lim_{x\to0}\dfrac{1}{x}$ $\lim_{x\to0}\dfrac{1}{x}-\lim_{x\to0}\dfrac{1}{x}$
Can we say answer is $0$ as $\lim_{x\to0}\dfrac{1}{x}-\dfrac{1}{x}=0$ or undefined because of $\infty-\infty$?

A: First of all $\lim_{x \to 0} \dfrac{1}{x}$ is NOT $\infty$. The limit from the right and left are $\infty$ and $-\infty$ respectively, and hence not equal.

Next, the expression $\lim_{x \to 0}\dfrac{1}{x} - \lim_{x \to 0}\dfrac{1}{x}$ is undefined, but not because it is "$\infty - \infty$". The symbol $\lim_{x \to 0}\dfrac{1}{x}$ itself has no meaning, because this limit doesn't exist. SO, logically it doesn't even make sense to write things like the difference of undefined things.
I'd say  the expression $\lim_{x \to 0}\dfrac{1}{x} - \lim_{x \to 0}\dfrac{1}{x}$ has as much meaning as $\ddot{\smile} * \text{apple}$ (which in a math context, is no meaning whatsoever). As another illustration: what is spongebob times jupiter? You'll think I'm crazy for asking this question... like what is that even supposed to mean? That's the point I'm trying to illustrate here (although in your case it is much worse, because jupiter actually exists, whereas $\lim_{x\to 0}1/x$ doesn't)
Now, $\lim_{x \to 0} \left( \dfrac{1}{x} - \dfrac{1}{x} \right)$ on the hand does make sense, and this limit exists and is equal to zero.
Now, when applying calculational rules, you need to know when exactly they are valid. Knowing the hypotheses of theorems is very important. Writing

$\lim_{x \to a} (f(x) + g(x)) = \lim_{x \to a} f(x) + \lim_{x \to a}g(x)$

alone is meaningless. This is the analogue of writing an incomplete sentence in English (they are formally incorrect, and they make no sense strictly speaking).
A more complete statement is that

If $\lim_{x \to a} f(x)$ and $\lim_{x \to a}g(x)$ exist (and note that "exist" means they have to be real numbers, which by definition are all finite), then $\lim_{x \to a}( f(x)+ g(x))$ also exists (i.e is a finite real number), and
  \begin{align}
\lim_{x \to a} (f(x) + g(x)) = \lim_{x \to a} f(x) + \lim_{x \to a}g(x)
\end{align}

You see, theorems are supposed to be full English sentences. I could rewrite the entire theorem above using only words and no mathematical symbols (it would be very cumbersome to read and write math this way... but it is possible).
So, before you apply the "sum rule of limits", ALWAYS ALWAYS ALWAYS check that the limits exist first. Only after that apply the rule. In your case $\lim_{x \to 0} \dfrac{1}{x}$ doesn't even exist, so the sum/difference rule cannot be applied to it.

A: The limit of a difference is the difference of the limits and conversely provided these limits exist.


text:
Q: C++ Network program runs but give no output My simple program gives no errors through the compiler and runs fine but it does not give the output it is supposed too until someone is connected. I have done a good bit of research and editing but can not figure it out.Also how do I let more than one person connect? Any help to get this to work would be appreciated. Thanks in advance!!! Code is below.
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>

char msg[20];

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Made it to main!";

    int listener_d = socket(PF_INET, SOCK_STREAM, 0);

    struct sockaddr_in name;
    name.sin_family = PF_INET;
    name.sin_port = (in_port_t)htons(30000);
    name.sin_addr.s_addr = INADDR_ANY;
    if(bind (listener_d, (struct sockaddr *) &name, sizeof(name)) == -1)
    {
        cout << "Can't bind the port!";
    }
    else
    {
        cout << "The port has been bound.";
    }

    listen(listener_d, 10);
    cout << "Waiting for connection...";

    while(1)
    {
        struct sockaddr_storage client_addr;
        unsigned int address_size = sizeof(client_addr);
        int connect_d = accept(listener_d, (struct sockaddr *)&client_addr, &address_size);
        cin >> msg;

        send(connect_d, msg, strlen(msg), 0);
    }
    return 0;
}

A: Maybe you should try flushing the output.
std::cout << "Waiting for connection..." << std::flush;


text:
Q: Google says JDO doesn't do cascading deletes from Datastore. So how do you do it? Google says:

Note: The JDO implementation does the work to delete dependent child objects, not the datastore. If you delete a parent entity using the low-level API or the Admin Console, the related child objects will not be deleted.

So how DO I delete an Entity which has child entities that are ArrayList ???
Shouldn't this be a basic feature - to delete the dependent child entities from a parent Entity?

A: Its not saying that JDO doesn't do cascading dependent children. In fact, it's saying that it does indeed do them, but it's the code in the JDO that does such. As such, if you touch the database directly (SQL or admin tool), the dependant children won't be deleted.

A: I actually solved this by getting all the dependent children in separate queries and deleting them.  Just deleting the parent didn't delete the dependent children from the datastore.
This was accomplished using the setAncestor() function
    // delete all children phrases

    Query phrase = new Query("Phrase");
    phrase.setAncestor(parentKey);
    results = datastore.prepare(phrase).asList(FetchOptions.Builder.withDefaults());
    for (Entity result : results)
        datastore.delete(result.getKey());


text:
Q: Issue in checking out a file after cleartool startview command I want to checkout a Clearcase file through unix command using cleartool co but I ended up seeing the following error message.
cleartool: Error: To operate on UCM branch, must be set to an activity and a UCM view.
I ran cleartool startview myview and cleartool setactivity myactivity and then I am trying to checkout a file.
Is file check out and check in commands tagged to setview instead of startview?
I am using startview command after going thru the following post Do not use setview instead use startview

A: As explained before (in your previous question), do not use cleartool setview
You just need to make sure that myview is indeed an UCM view (meaning lsstream is not empty)
cd /path/to/view
cleartool lsstream -cview

Also, do the cleartool setact inside the view.

A: Just wanted to list down the steps to get the solution working.
1) Created new view (myview) for a dynamic view/Integration View.
2) Navigate to the view folder which will be like homedirofserver/view/myview.
3) Created a new activity say myActivity(My initial problem was working with an activity which was previously set to another view.
4) set myActivity to myview and received message set activity 'myActivity' in view 'myview'
5) Then Navigated down to my scripts folder which is under homedirofserver/view/myview/vobs/vobname/myapp/WEB-INF
6) Ran scripts to checkout the scripts file.
It worked!!


text:
Q: String Searching Okay, I'm writing a language compiler in C# that converts my language into MSIL and then calls the MSIL compiler. But that's beside the point. I created some code to show you want I'm going to be working with:
module myApplication

  [EntryPoint]
  function void start
    write("Hello World!\n")
    wait(5) // wait 5 seconds
    ret()
  endfunction
endModule

Okay, I'm trying to scan through that code and find where "[EntryPoint]" is and then find all the "function void start" after it. So I can find the function type ("void") and name ("start"). The [EntryPoint] tag will always be above the function that will be defined as the applications entry point. And I will have to make it trim the whitespace and stuff. This is also scanning through using '\n' so the function MUST be under the tag.
And I also have another question, how would I make it separate the code inside the function from "function void start" and "endfunction"?

A: There is a lot more to writing a compiler than simple string manipulation - for example what if your source instead looked like this:
module myApplication
  string myString = "[EntryPoint]
  function void start
    write("Hello World!\n")
    wait(5) // wait 5 seconds
    ret()
  endfunction"
endModule

I.e. your source defines a string containing the source for a program - you can't just look through for something that looks like an entry point, you need to actually parse your source.
See Learning to write a compiler for good resources on getting started.


text:
Q: Weird undefined error on server I have the following meteor method
hasNoPendingPayments: function() {
    var userId = Meteor.userId();
    console.log(userId); <---------------------- correctly logs userId
    var user   = Users.findOne({_id: userId }, { fields: { services: 0 } });
    console.log(user); <-------------------------- logs 'undefined'
    return hasNoPendingPayments(user);
  },

This private helper I call from the above
hasNoPendingPayments = function(user) {
  // console.log('hasNoPendingPayments ');
  // console.log(user);
  var payments = Payments.find({ userId: user._id, status: {
    $in: [Payments.States.PENDING, Payments.States.PROCESSING]}
  });

  return payments.count() === 0;
};

And I call it from the client here
Template.payments.created = function() {
  this.hasNoPendingPayments      = new ReactiveVar(false);v
};

Template.payments.rendered = function () {
  Session.set('showPaymentRequestForm', false);

  var self = this;
  Meteor.call('hasNoPendingPayments', function(error, result) {
    if (result === true) { self.hasNoPendingPayments.set(true); }
  });
  ...

However, I get an undefined error on the server when I load the template initially (I marked where in code). Although, when I try call the same query on the client with the same userId, i correctly gets the user record
Any idea as to why this is?

A: Try with this.
Template.payments.rendered = function () {
  Session.set('showPaymentRequestForm', false);

  var self = this;
if(Meteor.userId()){
  Meteor.call('hasNoPendingPayments', function(error, result) {
    if (result === true) { self.hasNoPendingPayments.set(true); }
  });
}else{
console.log("Seems like user its not logged in at the moment")
}

Maybe when you make the Meteor.call, the data its not ready
Also just to be sure, when you run Users.findOne({_id: userId }, { fields: { services: 0 } }); on console.log what you get?
Maybe the find is wrong or have some typo
update
Router.map(function()
    {
    this.route('payments',
        {
        action: function()
            {
            if (Meteor.userId())
                this.render();
            } else{
                this.render('login') // we send the user to login Template
         }
        }
    }

or waitOn
Router.map(function () {
  this.route('payments', {
    path: '/payments',
    waitOn: function(){
        return Meteor.subscribe("userData"); //here we render template until the subscribe its ready
    }
  });
});

A: Meteor stores all the user records in Meteor.users collection
so try Meteor.users.findOne({_id: userId }....)
Instead of Users.findOne({_id: userId }, { fields: { services: 0 } });
in your server method


text:
Q: Reading csv files into table in GAMS I am having trouble reading CSV files into table. Suppose I have csv file looking like:
;c1;c1;c3;c4
r1;(some numeric values separated by ";")
r2;(some numeric values separated by ";")

I have tried to rewrite the csv into a .inc file and replacing ;with spaces. And then do something like this:
set col /c1 * c4/
set row /r1 * r2/

table(row, col)
   $include("myfile.inc")
;

But this doesn't work because my collins are not aligned and I can't do it manually because I have more than 500 columns.
My problem can be solved by

*

*finding a way to define table entries without the text being aligned

*find way to read csv directly into GAMS
What you suggest I do?

A: There are two things that could help you:

*

*Setting $onDelim (https://www.gams.com/latest/docs/UG_DollarControlOptions.html#DOLLARonoffdelim)

*Using csv2gdx (https://www.gams.com/latest/docs/T_CSV2GDX.html)


text:
Q: Call VF remoting based on action function result I am trying to create a Case creation form along with drag n drop file attachment to the case.
Case creation happens using Action of command button and what I want is if there is any attachment that needs to be processed using Remoting (drag n drop), then it should get the Case id just inserted.
So is there any way I can create the case get Id on VF page, pass it to VF remoting where I can attach the file to the case.??
Thanks in advance.
Ray

A: Oncomplete attribute on action function allows us to call a javascript function on action complete
Best example is in Jeff blog on how to do this
http://blog.jeffdouglas.com/2011/01/17/passing-values-to-javascript-from-apex-controller-method/
I have tweaked this for your case so that it  allows you to call javascript remoting after you obtain parent Id
<apex:page controller="ActionFunctionDemoController">
 <apex:sectionHeader title="Action Function Demo"
subtitle="Save a New Record"/>

 <apex:form >

  <apex:outputPanel id="jspanel">
 <script>
  function onControllerReturn() {
   alert('{!Id}');
   // This remoting call will use the page's timeout value
    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.AccountRemoter.getAccount}',
        Id,
        handleResult
    );
    function handleResult(result, event) { ... }
 }
 </script>
 </apex:outputPanel>

 <apex:actionFunction name="doControllerSave" action="{!save}"
rerender="jspanel"/>

 <apex:pageBlock id="blockSection">

 <apex:pageBlockButtons >
   <apex:commandButton onclick="doControllerSave();"
  oncomplete="onControllerReturn()" value="Save"/>
</apex:pageBlockButtons>
<apex:pageMessages />

 <apex:pageBlockSection columns="1">
   <apex:inputField value="{!cat.name}"/>
   <apex:inputField value="{!cat.Cat2__c}"/>
  </apex:pageBlockSection>

 </apex:pageBlock>
 </apex:form>

 Submit the form to successfully create a record. To generate an error,
  remove the value for 'Cat2' and save.

 </apex:page>


text:
Q: Mass and distance of the bodies of the solar system? This might be a bit of a historical question in nature.
Obviously given that we know the constant G, the mass of the sun, and the distance between a solar body and the sun we can calculate it's mass. Ditto if one of the other variables are missing.
What I don't understand however is how we managed to find the initial variables that we used to calculate all other variables? E.g. how did we find the distance between the Earth and sun and the sun's mass?
Sorry if the question is more historical than physical, but I couldn't find a place that describes how we arrived at our current knowledge.

A: $G$ was historically calculated from the Cavendish experiment, involving balls and a torsion balance. The earth's mass was actually calculated before the sun's mass. Using the assumption that the earth was a sphere, its circumference and thus its radius could be determined through geodesy, as was done historically even before Newton. The acceleration of an object, and thus the average force exerted on the object, is easy to compute and was done so by Galileo and others. With these facts, the earth's mass could be calculated. We can use Kepler's laws and geometry to determine the earth-sun distance, or parallax. Since we obviously know the period, from this, we can easily determine the sun's mass. Finally, as for determing the distances to other space bodies, for planets we use Kepler's laws and geometry or parallax and for other bodies in modern times we use more sophisticated apparatus.


text:
Q: Storing Selected items in Database in a same row I am having a problem.
I have some items in checklist box and i want to add the name of the selected items in a table. But when i use this code.
        con.Open();

        foreach (object item in chkOrder.CheckedItems)
        {
            string selectedItems = item.ToString();

            SqlCommand cmd = con.CreateCommand();

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT INTO Kitchen (Order_ID,Customer_ID,Reservation_ID,Customer_Name,Charges,Order_Name) VALUES ('" + txtOrderID.Text + "','" + txtCustomerID.Text + "','" + txtReservationID.Text + "','" + txtCustomerName.Text + "','" + allOrders + "',@Order_name)";
            cmd.Parameters.AddWithValue("@Order_Name",selectedItems);
            cmd.ExecuteNonQuery();
        }

        con.Close();

it throws an exception.
Note: "Order_ID" is a primary key.
System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK_Kitchen'. Cannot insert duplicate key in object 'dbo.Kitchen'. The duplicate key value is (1).
The statement has been terminated.'

what should i do?
Please Help.

A: You can either add parameter AUTO_INCREMENT to your PRIMARY KEY, and not insert it manually, so your database will handle it, or you can increment it in your code.


text:
Q: Average geometric efficiency in Positron Emission Tomography While researching for my thesis I am using the book "Physics in Nuclear Medicine" by Simon R. Cherry, James A. Sorenson and Michael E. Phelps. In Chapter 18.8 they talk about the average geometric efficiency, luckily the content I am referring to can also be found on this website. They calculate the average geometrical efficiency with
$$
\bar{g}_{ACD} = \frac{1}{3} \cdot \frac{2 \cdot A_{det}}{\pi D^2}.
$$
Where D is the distance between the detector pairs, $2 \cdot A_{det}$ is the area of the detectors and $\frac{1}{3}$ is the factor for averaging the efficiency. The formula is basically the solid angle from the center of the detector ring (or the two detectors) and the Area of the detector is multiplied by two because coincidence detector involves two detectors. Now, I understand that this is only true for a point source at the center of the ring and therefore the average should be used as an estimation which considers the whole field of view. But I can't seem to figure out how they have come up with the factor of $\frac{1}{3}$. They say it is "the average height of a pyramid" but how does this relate to the average geometric efficiency? A little note on the side, the equation above is only true if the distance to the detector is large compared to the size of the detector.


text:
Q: Why is device firmware often distributed on CDs with the device? Often, when any low-cost computer peripheral device is sold, it is sold with a CD containing the device's controlling firmware. Why can't it simply be sold with the firmware pre-installed by the manufacturer so that it does not rely on the host system itself to do this task? Does this have to do with price/memory constraints of the device, and if so, does it really impact the cost so much that firmware must be distributed on CDs?

A: Hardware is made in Taiwan and software is made in the US. While the hardware bounces around in a shipping container the code monkeys come out with yet another software version. This new version is lovingly installed at the distribution center by dropping a CD in the box. Or by posting it on a web site.
Why the new version? Because software is never finished. Only abandoned. Always room to improve. This is why our probes let us update software even in deep space.

A: This is a very broad question, so there are multiple possible answers.
First off, I want to challenge your assumption that devices ship without firmware pre-installed. Typically, the code that initializes the device such that it can be detected by the host is part of the firmware, so if there were no firmware pre-installed, then the host wouldn't detect the device and you couldn't update the firmware.
Likewise, the code for updating the firmware is often part of the firmware itself, so again, without firmware pre-installed, you wouldn't be able to update the firmware.
One or both of these is the reason that typically, when there is an error during firmware update, the device will be bricked and needs to be sent in for repair.
Secondly, there is this part of the question:

Why can't it simply be sold with the firmware pre-installed by the manufacturer

And the answer is that often, the manufacturer of the device is not the manufacturer of the firmware. In fact, specifically for cheap and simple peripherals, it is quite common to have the manufacturing outsourced to a third party in a different country where manual labor is cheap, but the distinguishing features of the product are part of the firmware, and are written in-house. Some of these third-party manufacturers are in a country where there is, let's say, a very "flexible" interpretation of intellectual property, so the company whose name is on the packaging may not actually want to give the manufacturer access to the firmware.
Then there is the fact that hardware evolves much slower than firmware. It's easier to throw an updated CD into the package than to update the firmware image used in the manufacturing process. Especially if devices are expected to sit on the shelve for some time.


text:
Q: passing 2 inputStreams to symfony Process I'm trying to execute a diff between two remote files with symfony Process.
Executing the command from command line works, but when I try using php I have an empty output..
$process = new Process('diff <(ssh user@remote1 "cat /my/remote1/file.txt") <(ssh user@remote2 "cat /my/remote2/file.txt")');
$process->run();
$output = $process->getOutput();

So I tried with setInput:
$process = new Process('diff');
$process->setInput('(ssh user@remote1 "cat /my/remote1/file.txt")');
$process->setInput('(ssh user@remote2 "cat /my/remote2/file.txt")');
$process->run();
$output = $process->getOutput();

but still same result..

A: Have You tried get content of files by PHP and then set them as input? Documentation not mention that bash commands can be used as input nor it will be executed.
Additionally: what are You using to pass parameters to setInput? I see there is a class InputStream - which could make a magic.


text:
Q: HasMany relationship attach model without saving directly The following is just an example: Take the following two models with their relationships:
User => hasMany('Address', 'user_id')
Address => => belongsTo('User', 'user_id')

I want to be able to link an address with an user with out directly saving it.
something like:
$user = new User();
$user->name = "John";

$address1 = new Address();
$address1->street = "Foo street";

$address2 = new Address();
$address2->street = "Bar street";

$user->addresses()->push($address1);
$user->addresses()->push($address2);

//do some stuff to maybe validate some things or pass the user object to some other controllers that handels it

//Save the user and the addresses here.
$user->save()

So this different that $user->addresses()->saveMany([$address1, $address2]);
Hope you anyone give me an elegant solution.

A: You should distinguish your validation action from the save action. You can achieve this by creating different methods in the Object Controller. One for the validations that you will check for duplicates,similar etc and then if validation passes you should redirect to a store route where you 'll create and save the objects.


text:
Q: How to grant user permission to certain folders using Client Object Model? So far I am able to grant user certain permission with the following code:
    ClientContext context = new ClientContext("http://myRealURL");
    Principal user = context.Web.EnsureUser(@"myLoginAccout");

    RoleDefinition readDef = context.Web.RoleDefinitions.GetByName("Read");
    RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(context);
    roleDefCollection.Add(readDef);
    RoleAssignment newRoleAssignment = context.Web.RoleAssignments.Add(user, roleDefCollection);

    context.ExecuteQuery();

The code above works fine, now my task is to add the user permission only to certain folders with C# code. For example, under Libraries, I have a library called JZhu, and inside JZhu, I have two folders folder1 and folder2. Is it possible to change the access permission on these two folders with Client Object Model?

A: The following example demonstrates how to customize access to folder via CSOM. There are two steps:

*

*assign unique permissions for a Folder since by default folder
inherits permissions from the parent object (List)

*grant user permissions to a folder

Example:
Principal user = ctx.Web.EnsureUser(accountName);
var folder = ctx.Web.GetFolderByServerRelativeUrl(folderUrl);
var roleDefinition = ctx.Site.RootWeb.RoleDefinitions.GetByType(RoleType.Reader);  //get Reader role
var roleBindings = new RoleDefinitionBindingCollection(ctx) { roleDefinition };
folder.ListItemAllFields.BreakRoleInheritance(true, false);  //set folder unique permissions
folder.ListItemAllFields.RoleAssignments.Add(user, roleBindings);
ctx.ExecuteQuery();

, where folderUrl parameter corresponds to server relative url for a folder,
for example /news/documents/archive for the following structure:
News (site)
  |
  Documents (library)
     |
     Archive (folder)


text:
Q: What can cause Rails 3.1 "= require jquery" to stop working? I'm porting a Rails 3.0.9 app to Rails 3.1.rc5.  My application.js is exactly the same as one generated by Rails 3.1 itself:
// This is a manifest file ...
//
//= require jquery
//= require jquery_ujs
//= require_tree .

But when I run my app and look at the application.js in Firebug or Chrome Developer Tools, all I see is:
// This is a manifest file ...
//

The directives are gone, so it would seem that the file has been processed by Sprockets, but the directives have not been replaced by the contents of jquery et al.  There are no errors appearing on the server console or in the logs.
Curiously, when I run a blog app (you know, the canonical tutorial app) it works fine (that is, when I examine application.js in Firebug, it contains the text of jQuery.)  This would seem to indicate that something in my app is somehow interfering with Sprockets.  Has anyone out there heard of such an issue (and hopefully a workaround)?
Here's my setup:
$ gem list jquery

*** LOCAL GEMS ***

jquery-rails (1.0.12)
$ ruby -v
ruby 1.9.2p290 (2011-07-09) [i386-mingw32]
$ rails -v
Rails 3.1.0.rc5

I'm at a loss as to what might be wrong.  I've triple checked my Gemfile; I've run and re-run bundle install and bundle update; I've tried rc3, rc4 and now rc5;  I'm running Ruby 1.9.2p290.  Any ideas?

A: One workaround: include JavaScript files with the old-skool tag.  For example, in my (Haml) layout:
= javascript_include_tag '/assets/jquery.js'
= javascript_include_tag '/assets/jquery_ujs.js'
= javascript_tag 'jQuery.noConflict();'

The /assets/ prefix tells Rails 3.1.x to look on the asset path, which includes gems, so you'll get the same files as with Sprockets directives.  But you won't get concatenation or any other Sprockets preprocessing.
Still looking for better solutions.


text:
Q: create importable python library I followed this article to create a python package.
https://packaging.python.org/tutorials/packaging-projects/
I created a new project and set up a new virtual environment.
Instead of uploading it to pip and installing it from there i installed it from my local file system with:
python -m pip install path/to/.whl

retrieving the message:
Installing collected packages: alexs-utils
Successfully installed alexs-utils
I am not able to import my function from my_utils
This is my setup.py:
import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="alexs_utils",
    version="0.0.1",
    author="Example Author",
    author_email="author@example.com",
    description="A small example package",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/pypa/my_utils",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    py_modules=['my_utils']
)

This is my my_utils.py:
def foo():
    print('bar')

This is my init.py:
name = "example_pkg"


text:
Q: Migration Problem: Cannot add foreign key constraint in laravel I'm trying to create foreign keys in Laravel 5.7 however when I migrate my table using artisan i am thrown the following error:

Illuminate\Database\QueryException:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table gateway_transactions add constraint gateway_transactions_user_id_foreign foreign key (user_id) references users (id) on delete CASCADE)

my migration :
    public function up()
    {
        Schema::create('gateway_transactions', function (Blueprint $table) {
            $table->engine = "innoDB";
            $table->unsignedBigInteger('id', true);
            $table->integer('user_id')->unsigned();
            $table->enum('provider', \Parsisolution\Gateway\GatewayManager::availableDrivers());
            $table->decimal('amount', 15, 2);
            $table->integer('order_id')->nullable();
            $table->string('currency', 3)->nullable();
            $table->string('ref_id', 100)->nullable();
            $table->string('tracking_code', 50)->nullable();
            $table->string('card_number', 50)->nullable();
            $table->enum('status', \Parsisolution\Gateway\Transaction::availableStates())
                ->default(\Parsisolution\Gateway\Transaction::STATE_INIT);
            $table->string('ip', 20)->nullable();
            $table->json('extra')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->nullableTimestamps();
            $table->softDeletes();
        });
        Schema::table('gateway_transactions', function(Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
        });
    }

users migration :
        Schema::create(config('access.table_names.users'), function (Blueprint $table) {
            $table->increments('id');
            $table->uuid('uuid');
            $table->string('first_name')->nullable();
            $table->string('last_name')->nullable();
            $table->string('email')->unique();
            $table->string('avatar_type')->default('gravatar');
            $table->string('avatar_location')->nullable();
            $table->string('password')->nullable();
            $table->timestamp('password_changed_at')->nullable();
            $table->tinyInteger('active')->default(1)->unsigned();
            $table->string('confirmation_code')->nullable();
            $table->boolean('confirmed')->default(config('access.users.confirm_email') ? false : true);
            $table->string('timezone')->nullable();
            $table->text('National_Code')->nullable();
            $table->char('phone_number', 11)->nullable()->unique();
            $table->integer('phone_verify')->default(0);
            $table->char('mobile_number', 11)->nullable()->unique();
            $table->integer('mobile_verify')->default(0);
            $table->text('state')->nullable();
            $table->text('city')->nullable();
            $table->text('address')->nullable();
            $table->text('path')->nullable();
            $table->char('postal_code', 10)->nullable();
            $table->timestamp('last_login_at')->nullable();
            $table->string('last_login_ip')->nullable();
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });

A: Change your code for this :
public function up()
{
    Schema::create('gateway_transactions', function (Blueprint $table) {
        $table->engine = "innoDB";
        $table->unsignedBigInteger('id', true);
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
        $table->enum('provider', \Parsisolution\Gateway\GatewayManager::availableDrivers());
        $table->decimal('amount', 15, 2);
        $table->integer('order_id')->nullable();
        $table->string('currency', 3)->nullable();
        $table->string('ref_id', 100)->nullable();
        $table->string('tracking_code', 50)->nullable();
        $table->string('card_number', 50)->nullable();
        $table->enum('status', \Parsisolution\Gateway\Transaction::availableStates())
            ->default(\Parsisolution\Gateway\Transaction::STATE_INIT);
        $table->string('ip', 20)->nullable();
        $table->json('extra')->nullable();
        $table->timestamp('paid_at')->nullable();
        $table->nullableTimestamps();
        $table->softDeletes();
    });
}

I THINK - The following section is how I understand the way Laravel work.
Since you are creating your table into the first Schema, you have to put your foreign key into the creation.
The problem is that Laravel Migration will verify that everything will work before applying code, but the stage is the function up(). So everything in it is at the same stage. The migration think that your gateway_transactions doesnt exist, and it doesnt at the moment it verify everything is ok. It will when the code will exist.

A: The type of the foreign key column must be exactly the same as the reference table.
If the ID of the Users table is a big integer:
$table->bigIncrements('id');

Your foreign key must be:
$table->unsignedBigInteger('user_id');

Then the migration will work correctly.


text:
Q: Rescheduling cron jobs in nodejs on server restart I have node js application where a user can schedule 4-5 different cron jobs. A user selects a start_date, end_date, start_time, and end_time, and accordingly, the cron functions are scheduled and some campaigns are generated to connect with leads (or other users). I am using npm package node-schedule to achieve the desired cron-job execution but the issue arises if my web application crashes in between.
As per the official documentation of node-schedule,

Note that Node Schedule is designed for in-process scheduling, i.e. scheduled jobs will only fire as long as your script is running, and the schedule will disappear when execution completes.

The solution I can come up to resolve this is to call the cron functions using server.js file which restarts every time the server script is executed. But I am unable to resolve some of the following issues:

*

*A scheduler is an individual function, not campaign-specific, so how will the application know which cron-function to start if it has not been completed?

*A scheduler is a single function, that will be called every time as soon as the server is restarted. If 6 instances of a server are created, it will be called 6 times.

Suppose, my scheduler is due to execute between 28th May 11:00 AM to 31st May 12:00 AM. The scheduler starts its job and some of the campaigns are executed in between. If my server goes down on 30th May, how can I pick up from the remaining date-time and campaigns and complete it from there?
So I am concerned about how to schedule or handle the cron job functions for the campaigns? If any of the campaign cron jobs is crashed in between if the server is stopped, how should I be able to re-schedule or execute that cron function from the time or date that has been left of it?
I am not much experienced with cron jobs, hoping for some handy solutions.

A: Here some advice, that you could review or implement depending of your hardware capabilities:
Decoupling
Decouple your current application in two separated artifacts: web and campaign. This allows each service to be deployed, rebuilt, re-deployed and managed independently. And also to have autonomous or cross-functional Teams.
source: https://skelia.com/articles/5-major-benefits-microservice-architecture/
Fault tolerance
If you need an app that doesn't affect a failure , crash or any event who needs a restart, you must use something outside to your app.
Commonly this outside is a database. You could use a json file if a database is not an option for you.
Campaign
We have two entities here:
campaign_configurations

| identifier        | desc           | cron_expression |
|-------------------|----------------|-----------------|
| month_discounts   | discounts ...  | 0 0 1 * *       |
| reminder_shop_car | a reminder ... | */10 * * * *    |
|                   |                |                 |

Also you can add a column to control the period validity of the cron with a start and end date.
campaign_executions

| execution_date      | execution_status | execution_log |
|---------------------|------------------|---------------|
| 10-10-2020 01:00:00 | finished         | ...           |
| 10-10-2020 14:30:00 | error            | ...           |
| 10-10-2020 14:35:00 | executing        | ...           |

App startup
When your nodejs campaign starts/restarts due to failure or scheduled maintance, this must be the flow:

*

*read campaign_configurations table and get all of cron expressions in a valid period.

*use an algorithm to detect if today your cron expressions must be executed. Example:

*

*a cron only in December (Christmas) should not run today: June 03

*a cron for every 5 minutes, should execute in the next 5 minutes

*Every execution at the start must create an entry in campaign_executions table with a status: pending

*Every execution could use node-schedule to execute it logic.

*New executions should not execute if there is a previous execution in pending or error. According to your internal business logic.

App is healthy
When app is healthy, its must query to the campaign_configurations table in order to execute new or modified cron expressions (previous explained flow)
This could be at every 30 minutes, more and less, according to your internal business logic.
You could use node-schedule for this task.


text:
Q: Reduce inner margins of the tokens of NSTokenField I feel the tokens in NSTokenField have way too much inner margins, i.e. i believe the two semicircles (on the each side) should be closer to the text. The default setting wastes way too much space.
How do I reduce these margins, and make the tokens more compact?

A: With the Objective-C runtime, there seems to be a way to accomplish this without subclassing a private class. This may not get around App Store requirements, though.
To use the Objective-C runtime, add
#import <objc/runtime.h>

to the top of the file where you want to make the modification to tokens. In an @implementation of a class or category in this file (perhaps a category on NSTokenField or NSTokenFieldCell), add
static NSSize (*kOriginalCellSizeForBounds)(id, SEL, NSRect);

NSSize cellSizeForBounds_override(id self, SEL _cmd, NSRect rect)
{
    NSSize size = kOriginalCellSizeForBounds(self, _cmd, rect);
    size.width -= 10;
    return size;
}

static NSRect (*kOriginalTitleRectForBounds)(id, SEL, NSRect);

NSRect titleRectForBounds_override(id self, SEL _cmd, NSRect rect)
{
    NSRect titleRect = kOriginalTitleRectForBounds(self, _cmd, rect);
    titleRect = NSInsetRect(rect, -5, 0);
    return titleRect;
}

+ (void)load
{
    Class tokenAttachmentCellClass = objc_getClass("NSTokenAttachmentCell");

    SEL selector = @selector(cellSizeForBounds:);
    Method originalMethod = class_getInstanceMethod(tokenAttachmentCellClass, selector);
    kOriginalCellSizeForBounds = (void *)method_getImplementation(originalMethod);
    if(!class_addMethod(tokenAttachmentCellClass, selector, (IMP)cellSizeForBounds_override, method_getTypeEncoding(originalMethod))) {
        method_setImplementation(originalMethod, (IMP)cellSizeForBounds_override);
    }

    selector = @selector(titleRectForBounds:);
    originalMethod = class_getInstanceMethod(tokenAttachmentCellClass, selector);
    kOriginalTitleRectForBounds = (void *)method_getImplementation(originalMethod);
    if(!class_addMethod(tokenAttachmentCellClass, selector, (IMP)titleRectForBounds_override, method_getTypeEncoding(originalMethod))) {
        method_setImplementation(originalMethod, (IMP)titleRectForBounds_override);
    }
}

What's happening here is that we're reducing the original width of the token (in cellSizeForBounds_override()) and proportionally increasing the width of the cell's "title" (in titleRectForBounds_override()). The result is a token with reduced horizontal margins that still works properly in an NSTokenField. You can tinker with the amount of reduction in width to get the effect you want.
You can read more about method swizzling in Mike Ash's article, "Method Replacement for Fun and Profit"; I'm using "Direct Override" method swizzling.

A: The answer is similar to this one: How do I set the column margins in an NSTableView?
You'll need to subclass NSTextFieldCell and override -titleRectForBounds: to pass a width-inset copy of the rectangle super returns.

A: I had to do some subclassing of a class which is not a part of the public API. I got an idea of what to do through the code of BWTokenField in BWToolkit. It works, but I would have wanted to do it without public APIs, as I might want to go on the Mac App Store one day. I have submitted a bug report asking for making the API public, and they marked the report as a duplicate. I'm not optimistic they'll do anything about it.


text:
Q: Gremlin Python createIndex (Tinkerpop) I'm currently using Tinkerpop with the gremlin python client with the default TinkerGraph-Gremlin(which is running in-memory). I wanted to boost the performance of my queries and read about the createIndex() function which sounds like the perfect it for my use case, sadly I wasn't able to create an index with the python client. I also tried to add these lines into the start-up groovy script (run through the groovy scirpt without errors) but when I run my performance benchmarks I get the same results.
So my question is: Can I create an index with the python client and if not what would be a workaround? Also is there a way to ask gremlin if there are any indices defined?
PS.: For the groovy script I used the default empty-sample.grooy and add these lines before the last call:
graph.createIndex("name", Vertex.class)
graph.createIndex("nap", Edge.class)

Thanks!

A: The python client won't have a createIndex() method as TinkerPop does not provide any abstractions over indices in 3.x. We rely on the index and schema creation methods of the underlying graph database. You have to drop down to that API level and out of TinkerPop.
If you're only determining whether or not indices are created using the speed of your query keep in mind that your graph only has 8800 vertices in it and TinkerGraph is an in-memory graph. You might not see a massively discernible difference in speed with that few a number of vertices. If you want to know if your index is created just look it up:
gremlin> graph = TinkerGraph.open()
==>tinkergraph[vertices:0 edges:0]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> graph.createIndex('name',Vertex.class)
gremlin> graph.getIndexedKeys(Vertex.class)
==>name

A: Using gremlinpython v3.2.6
Searching the github of TinkerPop, I found you can send direct requests as it was the database console using the client object. This behaviour is explained in the GitHub of Tinkerpop. I'll show the synchronous version, in the GitHub there's an asynchronous one also:
from gremlin_python.driver.client import Client

client = Client(url, travelsal_source)
console_command_string = "2*2"  # Write code as it was the console of the database you're using
result_set = client.submit(console_command_string)
future_results = result_set.all()
results = future_results.result()

client.close()

To see what command you have to send, look at the exact database you're using, in case of Janusgraph it is detailed in its indexing documentation.


text:
Q: Windows Server 2012 Remote Desktop Server slow GPO applied I have a Remote Desktop Server 2012 R2. I have a loopback enabled GPO with a few settings. Then I've got a few user-configurated GPO's which are applied. They are working just fine. However, I'm having issues with one specific GPO that runs a .vbs script applying a shortcut on the desktop. I've got to wait around 5-10 minutes before the shortcut appears on the desktop. I a bit blaffeled by it, because all the other GPO's are working just fine.
Does anyone know what the issue might be?

A: Just ran into this.  a new "FEATURE" in Server 2012 R2 and Windows 8.1 is to delay login scripts 5 minutes.  That's helpful.  You have to disable this via GPO here:
Computer Configuration\Policies\Administrative Templates\System\Group Policy\Configure Logon Script Delay
set the value to 0