text:
Q: Same server_name with different applications plugged as separate location blocks in nginx Is it possible to "plug" different web services (exposed from different docker containers) in a same nginx server?
Here's a simple example to get the general idea:
server {
    listen 80;
    listen [::]:80;

    client_max_body_size 10M;
    charset utf-8;

    server_name my.server.org;

    access_log /var/log/nginx/reverse-access.log;
    error_log /var/log/nginx/reverse-error.log;

    location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:8081/;
    }
    location /static/ {
        include proxy_params;
        include /etc/nginx/mime.types;
        alias /var/www/app/static/;
    }
    location ^~ /app2/ {
        include proxy_params;
        proxy_pass http://127.0.0.1:8082;
    }
    location ^~ /app3/ {
        include proxy_params;
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_pass http://127.0.0.1:8083;
    }
}

where location / is the root of a first application along with its static files in the next location block.
This first application is running at http://my.server.org/.
I would like to access two other applications at http://my.server.org/app2/ and http://my.server.org/app3/ while keeping the same server name my.server.org.
These applications are related to the main one, but they are totally independent, i.e. they are served from other docker compositions, with their ports exposed respectively at 8082 and 8083.
Is it possible to achieve such simple task within a unique server block?
For the moment I got 404 when reaching those two other URLs.
I basically want to map those working URLs+ports and all their children elements to named locations:
http://my.server.org:8081/... -> http://my.server.org/...
http://my.server.org:8082/... -> http://my.server.org/app2/...
http://my.server.org:8083/... -> http://my.server.org/app3/...
EDIT:
either this:
    location /app3/ {
        if ($http_referer ~ "^$scheme://$http_host/app3/") {
            rewrite ^/app3/(.*) $scheme://$http_host/app3/$1 redirect;
        }
        include proxy_params;
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_pass http://127.0.0.1:8083;
    }

or this:
    location ~*/app3/(.*)$ {
        include proxy_params;
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_pass http://127.0.0.1:8083/$1;
    }

are "working" the same, but yet not perfectly because there are two issues left:

*

*only raw HTML is served (e.g. no styling: "502 bad gateway" on css files for example)

*links within the pages point to, e.g. http://my.server.org/subfeature/subitem instead of http://my.server.org/app3/subfeature/subitem. Hence, they are "missing" the /app3 prefix and I don't know how to actually add it if it's not present where it should actually be.

A: This is a typical task but you forgot two things:

*

*googling your question.

*adding rewrite clauses into each of the location {} blocks.


text:
Q: Accessing html elements from knockout view models I've created a knockout component that wraps a bootstrap modal dialog, which I'm registering and loading (as an AMD module) as follows:
// Register dialogs as components
ko.components.register('create-user-dialog', {
    viewModel: { require: 'Features/Users/Index/CreateController' },
    template: { require: 'text!Features/Users/Index/CreateDialog.html' }
});

The template HTML contains a tag like:

...

And the knockout view model extends a base class and looks like this (typescript):
export = CreateController

class CreateController extends Controllers.BootstrapModalController {

    constructor() {
        super($('#create-user-modal'));
    }
}

class BootstrapModalController {
    public dialog: JQuery;

    constructor(dialog: JQuery) {
        // Save a reference to the modal element so we can
        // show/hide the dialog from the controller
        this.dialog = dialog;
    }

    // Show the modal window
    showModal = () => {
        this.dialog.modal({
            show: true,
            backdrop: 'static'
        });
    }

    // Close the modal window
    closeModal = () => {
        this.dialog.modal('hide');
    }
}

Finally, I use the component in my page as follows:

This works, but it's a bit messy since the CreateController does something I consider a bit strange in the constructor - namely using a jquery selector which tightly couples it with the html in the template.
To some extent, this is unavoidable, but I think it could be a bit nicer. If possible, I'd like the BootstrapModalController base class to be able to automatically determine the DOM element corresponding to the Bootstrap modal... that way showModal and closeModal would work, as long as the template actually contained a bootstrap modal dialog and descendants wouldn't have to explicitly pass in ids or jquery objects in the constructor.
I figured it might be able to use something like the jQuery find method to hunt for an element with the CSS class modal in the component's HTML template. However in order to do that I need to be able to get the rootNode that Knockout binds the component's view model against (i.e. the

 element).
Is there any way to work out the html rootNode for a component from within the javascript view model for that component?

A: You can use custom binding, as described in the http://www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html article in order to wrap HTML/JS elements with Knockout, e.g. jquery button binding:
ko.bindingHandlers.jqButton = {
    init: function(element, valueAccessor) {
        var options = valueAccessor() || {};
        $(element).button(options);
    }
};

usage:
data-bind="jqButton: { ...some options... }"

In the custom binding you can access the element the binding is applied to.

A: OK so the answer appears to be to use binding handlers. I found this snippet, which appears to do what I want:
ko.bindingHandlers.element = {
    init: function(element, valueAccessor) {
      var value = valueAccessor();
      value(element);
    }
};

Which the author demonstrates:
<canvas width="100" height="60" data-bind="element: yourObservable"></canvas>

All seems to work fairly painlessly... about the only thing is that in my case I have to create a JQuery object from the element as so:
ko.bindingHandlers.element = {
    init: function(element, valueAccessor) {
      var value = valueAccessor();
      value($(element));
    }
};

Thanks for the tips Robert!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Postgres data to csv with force quotes I am trying to fetch postgres table data into CSV by using below query, be default it is giving '|' as delimiter, but in table data there are multiple delimiters, so i want to fetch the data by using "" as delimiter or force_quote
psql -h host -p port -U user -d dbname --no-align -c "SELECT * from sample" > D:\sample.csv

can any one pull me out from this issue..thanks in advance

A: as @a_horse_with_no_name suggested, you can do it with smth like:
psql -h host -p port -U user -d dbname --no-align -c "\copy (select * from sample) to stdout with (format csv, force_quote *, quote \$\$'\$\$)" > D:\sample.csv

or reducing the code to a neater version:
psql -h host -p port -U user -d dbname --no-align -c "\copy sample to 'D:\sample.csv' with (format csv, force_quote *, quote \$\$'\$\$)" >

of course you can change \$\$'\$\$ to '''' if you find it any more readable...

A: Do a job talend like :
tpostgresinput -> tmap -> tfiledelimitedOutput

And put your "Select" condition in the query in the tpostgres input.


text:
Q: How to have form redirect on submit This is my code:
function mySubmit() {
  var myForms = document.getElementsByTagName("form");
  var userEmail = document.getElementById("myEmail").childNodes[0].nodeValue;

  for (var t = 0; t < myForms.length; t++){
    myForms[t].s_emailaddress.value = userEmail
    $.post("http://test.test", $(myForms).eq(t).serialize(), function (data, status) {
      if (status === "success") {

I'd like to add a redirect function to this.  For example, all form data should be submitted and upon submission, redirect to www.google.com

A: if (status === "success") {
  window.location = 'https://google.com';
}

A: Some ways to redirect Page:
// Sets the new location of the current window.
window.location = "http://www.google.com";

// Sets the new href (URL) for the current window.
window.location.href = "http://www.google.com";

// Assigns a new URL to the current window.
window.location.assign("http://www.google.com");

// Replaces the location of the current window with the new one.
window.location.replace("http://www.google.com");


text:
Q: When does jQuery mobile read the hash? If you have a URL with a hash, for example:

www.my_jqm_site.com/#some_page_request

... at what point during the jqm page event sequence does jqm read the hash?
Event sequence when navigating from jqm_page_A to jqm_page_B ... thanks Muhammed Basil.

  - document --- script time (js is readable, but DOM is not ready yet)
  - document --- ready
  - page B   --- pagebeforecreate
  - page B   --- pagecreate
  - page B   --- pageinit
  - page A   --- pagebeforehide
  - page B   --- pagebeforeshow
  - page A   --- pageremove
  - page A   --- pagehide
  - page B   --- pageshow
  - body     --- onLoad

EDIT: if I change the hash at script time:
<script>
  window.location.hash = "#some_other_page_request"
</script>

it will override the incoming hash, '#some_page_request', and thus jqm will navigate to  instead.
This suggests that jqm reads the hash at-or-after script-time (ie. at, or after, $(document).ready(...)).

A: During the pagebeforehide event.
This is the first element to be dispatched during the transition prom page A to page B.

Description: Triggered on the "fromPage" we are transitioning away from, before the actual transition animation is kicked off.

This is the first page to receive data object as their 2nd arg. This data object has the object that contains the page DOM element that we are transitioning to.
Official documentation: http://api.jquerymobile.com/pagebeforehide/
All events before it are events common to page creation and they will also trigger during the initial app loading when first page is about to be shown:
- page B   ---pagebeforecreate
- page B   ---pagecreate
- page B   ---pageinit

During those 3 events system don't have knowledge is this a app loading or page transition. They are here just to create a new page.


text:
Q: Is there a way to shorten these commands so that I don't have to give the list.add repeatedly (for each owner)? The vehicle() class is a superclass as you can see in the code. I want to keep 2 separate classes(at least that's what I think is the most efficient way. Please point out if I'm going the reverse way here!), one for vehicles and one for vehicleOwners, where owners' vehicles are also listed in vehicle() class. Basically, I'm going to put console input to search owners using their unique ownerId and also displaying various information fields(like mpg, top speed, resell value based on purchase date etc.) about their type of vehicle. I want to use efficient coding practices and adding each object item to the list looks a little awkward to me. Is there a different way out?
below is my vehicleOwner class
public class VehicleOwner extends Vehicle{

    private int yearsOwned;
    private String ownerName;
    private int ownerId;

    public VehicleOwner(String ownerBrand, String ownerModelNo,int ownerModelYear, int yearsOwned, String ownerName, int ownerId) {
        super(ownerBrand, ownerModelNo, ownerModelYear);

        this.yearsOwned = yearsOwned ;
        this.ownerName = ownerName;
        this.ownerId = ownerId;

        ArrayList<VehicleOwner> list = new ArrayList<VehicleOwner>();
        VehicleOwner owner1 = new VehicleOwner("Volvo", "XC60", 2014, 3, "Mary", 00011);
        VehicleOwner owner2 = new VehicleOwner("Subaru", "crosstrek", 2015, 2, "John", 00012);
        VehicleOwner owner3 = new VehicleOwner("Mercedes", "Eseries", 2016, 1, "Brandon", 00013);
        list.add(owner1);
        list.add(owner2);
        list.add(owner3);
    }
}

A: The only way you can "shorten" this code is add new objects without creating variables for them:
list.add(new VehicleOwner("Volvo", "XC60", 2014, 3, "Mary", 00011));
list.add(new VehicleOwner("Subaru", "crosstrek", 2015, 2, "John", 00012));
list.add(new VehicleOwner("Mercedes", "Eseries", 2016, 1, "Brandon", 00013));

A: You could use Arrays.asList(T...) and remove the local references and please program to the List interface. Something like
List<VehicleOwner> list = new ArrayList<>(Arrays.asList( //
        new VehicleOwner("Volvo", "XC60", 2014, 3, "Mary", 00011), //
        new VehicleOwner("Subaru", "crosstrek", 2015, 2, "John", 00012), //
        new VehicleOwner("Mercedes", "Eseries", 2016, 1, "Brandon", 00013) //
));


text:
Q: TikZ graph with interesting vertices I'd like to use TikZ to typeset some graphs like this one:

(Sorry for the crappy camera-phone pic)
I am familiar with \node, \path and edge, as well as with getting different arrowhead styles.
The bit that's tripping me up is getting the vertices of the graph to be these little triangular number diagrams. This one is relatively simple (the number diagrams are only 2x2), but I have others where the diagrams are 3x3 and bigger.
Would it be best to use an array environment inside each \node? Is that even possible?
Or is there a better way? Thanks!

A: The new graph drawing library in the CVS version of pgf can do this quite nicely. Exploiting the align key, and setting it to right means the node contents in this specific case can be given quite simply.
However, it does  needs luatex to compile.
\documentclass[border=0.125cm]{standalone}

\usepackage{tikz}
\usetikzlibrary{graphdrawing}
\usetikzlibrary{graphs}
\usegdlibrary{layered}

\begin{document}

\begin{tikzpicture}[>=stealth, every node/.style={align=right}]

\graph [layered layout,grow=up, level distance=0.5in, sibling distance=0.5in]
    {
        "00\\0" -> "01\\0" -> {"01\\1", "11\\0"} -> "11\\1"
    };

\end{tikzpicture}

\end{document}


text:
Q: How does gravatar adjust the colour in your images automatically? I decided I wanted to change my gravatar to be circular. I have it circular on my blog with css and prefer the effect so decided to use a bit of imagemagick to give my image a circular alpha channel (so I could have it on SO, e.t.c. as well). a couple of quick commands later I was sorted:
# crop to square 422x422 with 0x0 offset
convert mike_gravatar.jpeg -crop 422x422+0+0 mike_gravatar_square.jpeg
# give circular alpha channel around it NOTE this is for a 422x422 image (note the 211x211)
convert mike_gravatar_square.jpeg \( +clone -threshold -1 -negate -fill white -draw "circle 211,211,211,0" \) -alpha off -compose copy_opacity -composite mike_gravatar_circle.png

brilliant, now we just upload this to gravatar, I will have a nice circular cropped image and all will be well with the world.

as you have probably guessed from the question all is not well:

ok, I must have clearly messed up my imagemagick and not checked that the before and after image are the same, reopen the images next to one another, and see that they are indeed the same. I try uploading again to gravatar and notice that they seem to process the images after the "cropping" stage, here is what it looks like in the browser after the file upload (before the cropping messes it up):

Alright, lets do some digging, someone else must have stumbled upon this before, so I have a look around and one lone soul in a desolate forum wasteland cries out. Now there is no response to this, but the relevant text is here:

It seems that if a photo or picture uploaded to Gravatar's cropper
  doesn't have jet black, it will auto-level the nearest grey to black
  and darken the whole image, including darkening whites into greys. Can
  confirm that this occurs with any PNG image that has a grey background
  or has a large enough proportion of it, whether or not it has 255
  whites and regardless if it has alpha-blending or not

So it seems like I can fix this by putting in a single black pixel, that sounds alright so I try adding a black pixel, then a single black and a single white pixel, result:

So basically now I'm out of ideas:

*

*does anyone have any idea what post-processing gravatar does, so I can undo it or counteract it's effects with pre-processing?

*is this "feature" documented anywhere, or can it be turned off, or gotten around?

I think it would be quite cool to preprocess the image to counteract the darkening they would do to it but that would require knowing exactly what they do in order to change things and obviously might not be possible (depends on the relative movement of each colour, I suppose)
EDIT:
I tried making an inverse image to see if it was basing the processing on the average or the extreme values and that was also darkened, it seems that it's more likely to be the average:

A: Alright, I've got a solution that "worked for me" unfortunately it is just empirical and "good enough" (I'd quite like to check what's actually happening but unfortunately don't have any more time to devote to being nerd sniped) I'm gonna post what I did, what I think might have happened and how I think this should be solved if someone has enough time.
First off what I did, I simply tried whitening the image by random amounts, what ended up working was a gamma around 2
convert mike_gravatar_circle.png -gamma 2 mike_gravatar_circle_light_2.png

here is what the picture looks like both before and after processing by gravatar:

I feel it's pretty ridiculous that I need to clobber my picture like I do on the left to make it look normal so I'm going to leave this question open to see if anyone can show me a better/cleaner way of doing this.
EDIT: forgot to mention my (completely unfounded) guesses as to how this should be solved. So my guess is that gravatar might try and make the average color of the image some type of midrange value (as that might seem sensible... I guess, I don't know) and picks up the alpha as being all white. trying some experiments to determine could be interesting, but only if they had an api to automate uploading and downloading the images or it would be painful effort, I'm looking forward to any suggestions as to what people think is happening.


text:
Q: def function syntax error in Python 3 I'm in the process of teaching myself to code and am currently working on a dice roller as a learning project. I'm runnng into a bit of an odd snag at the moment the moment. The fourth 'def' in my code, no matter what it actually is (I've tried with several that all work individually) it keeps getting flagged as a syntax error. Here's what I have:
import random

def mult():
    print('How many dice would you like to roll?')
    multiplier = input()
    mod()

def mod():
    print('What modifier, if any, would you like to assign?')
    modifier = input()
    result()

def result():
    total = (roll * multiplier) + modifier
    print('Your result is'
    (str(total)

def menuscreen():
    print("Welcome to Jack's dice roller. What kind of die would you like to roll?")
    print("")
    print("A. d2")
    print("B. d4")
    print("C. d6")
    print("D. d8")
    print("E. d10")
    print("F. d12")
    print("G. d20")
    print("H. d100")

def gen():

    menuscreen()

    if input() == 'a' or 'A':
        roll = random.randint(1,2)
        mult()

    if input() == 'b' or 'B':
        roll = random.randint(1,4)
        mult()

    if input() == 'c' or 'C':
        roll = random.randint(1,6)
        mult()

    if input() == 'd' or 'D':
        roll = random.randint(1,8)
        mult()

    if input() == 'e' or 'E':
        roll = random.randint(1,10)
        mult()

    if input() == 'f' or 'F':
        roll = random.randint(1,12)
        mult()

    if input() == 'g' or 'G':
        roll = random.randint(1,20)
        mult()

    if input() == 'h' or 'H':
        roll = random.randint(1,100)
        mult()

def queryque():

    print('Would you care to roll again?')

    if input == 'yes':
        gen()

    if input == 'no':
        end

gen()

A: It looks like you're missing two closing parentheses at the end of your result() definition. You probably want something like:
def result():
    total = (roll * multiplier) + modifier
    print('Your result is ' + str(total))

A: You're missing 2 closing parentheses ):
(str(total)

Try the following instead:
def result():
    total = (roll * multiplier) + modifier
    print 'Your result is' + str(total)

A: Pencil Von Radiergummi and A.J have addressed the syntax error that prompted your question, but as I mentioned in my comment to your question your code has various other problems, the main one being that variables created in functions are local, which means they only exist within the function and can't be seen in other functions.
srekcahrai attempted to address that problem, but there are (currently) various issues with the code he posted (including a syntax error in the print() call in the result() function). So here's a modified version of the code in srekcahrai's answer. I've fixed various errors in the code but it's still not perfect - it really should have error checking on the inputs, but at least it runs.
I've condensed the gen() function by using a dict to convert the choice letter (which can be in upper or lower case) to the number of sides.
#!/usr/bin/env python

import random

def mod():
    modifier = int(input("What modifier, if any, would you like to assign? "))
    return modifier

def mult():
    multiplier = int(input("How many dice would you like to roll? "))
    return multiplier

def result(roll, multiplier, modifier):
    total = (roll * multiplier) + modifier
    print("Your result is {0}".format(total))

def menuscreen():
    print("Welcome to Jack's dice roller.\n")

    print("A. d2")
    print("B. d4")
    print("C. d6")
    print("D. d8")
    print("E. d10")
    print("F. d12")
    print("G. d20")
    print("H. d100")

def gen():
    menuscreen()
    choice = input("What kind of dice would you like to roll? ")
    kinds = {
        "A":2, "B":4, "C":6, "D":8,
        "E":10, "F":12, "G":20, "H":100
    }
    sides = kinds[choice.upper()]
    multiplier = mult()
    modifier = mod()
    roll = random.randint(1, sides)
    result(roll, multiplier, modifier)

def main():
    while True:
        gen()
        if input("Would you care to roll again? ") != "yes":
            print("Goodbye")
            break

if __name__ == "__main__":
    main()

The logic in your result() function is a little odd, but I've retained it for this program. Realistically, your program should use a loop to roll the die the specified number of times, adding the results to total each time through the loop. If you need help doing this, please ask a new question.


text:
Q: Exception when reading JSON result I am trying to parse the following JSON response: http://www.breakingnews.com/api/v5/items?compact=false.
Here is my code to parse it:
NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.breakingnews.com/api/v5/items?compact=false"] options:NSDataReadingUncached error:&error];
if (error) {
    NSLog(@"%@", [error localizedDescription]);
} else {

    NSError *e = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error: &e];

    if (!jsonArray) {
        NSLog(@"Error parsing JSON: %@", e);
    } else {
        for(NSArray* item in jsonArray) {

            NSLog(@"Item: %@", item);

        }
    }

}

However, I'm getting this error:

-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x101810a40

Why is this - what am I doing wrong?

A: Check the types of the objects you're using. You're assuming that everything is an NSArray, when in fact things in JSON can be NSArray, NSDictionary, NSString, NSNumber, and NSNull.


text:
Q: Error #1064 al crear un procedimiento almacenado Buenas intento hacer un kardex y el proceso de lo movimientos lo quiero realizar con un procedimiento almacenado.
Este es el Modelo relacional de la base de datos:

Donde producto_cod de la tabla kardex es la id_producto de la tabla producto y el campo concepto es de tipo enum('Entrada','Salida') de la tabla kardex.
El procedimiento que necesito hacer es que cada que ingrese en la tabla kardex un producto con su campo cantidad eje:1 y en la opción concepto es igual a 'Entrada' me actualice la tabla producto con la cantidad ingresad. Lo mismo con la opcion salida.
Eje: si en la tabla producto tengo un producto con la cantidad 5 y en la tabla kardex selecciono el producto y le doy la opción de entrada y en la cantidad ingreso 3 entonces la tabla producto de ese producto  la cantidad quedaría en  8, y así mismo en salida ya que en esta se resta.
Actualmente tengo este codigo:
DELIMITER $$
CREATE PROCEDURE ACTUALIZA_STOCK (n_cantidad int,  n_concepto enum, id int)
BEGIN
if n_concepto='Entrada' then
UPDATE producto set cantidad=cantidad+n_cantidad WHERE id_producto=id;
end if
if n_concepto='Salida' then
UPDATE producto set cantidad=cantidad-n_cantidad WHERE id_producto=id;
end if;
END $$

pero me sale el sgte error:
#1064 - Algo está equivocado en su sintax cerca ' id int)
   BEGIN
   if n_concepto='Entrada' then
   UPDATE producto set cantidad=cant' en la linea 1
Se les agradecería su ayuda.

A: Tienes un error mayor, y es que las columnas del tipo ENUM no se crean así, sino con sus valores.
Del tipo de dato ENUM la  documentación de MySQL dice lo siguiente:

Un ENUM es un objeto de cadena con un valor seleccionado de una
  lista de valores permitidos que se enumeran explícitamente en la
  especificación de columna en el momento de la creación de la tabla.

Por ejemplo,, la sintaxis de una columna ENUM  para crear, insertar, seleccionar, es algo como esto:
CREATE TABLE shirts (
    name VARCHAR(40),
    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);

INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),
  ('polo shirt','small');

SELECT name, size FROM shirts WHERE size = 'medium';

Tu declaración de n_concepto enum no cumple con esos criterios, por eso el error. También, te falta un punto y coma al final de un if, pero eso es un error menor que se corrige poniendo el punto y coma.
Probé esto en rextester y funciona, observa la columna del tipo enum como es creada:
VER DEMO
DELIMITER $$
CREATE PROCEDURE ACTUALIZA_STOCK
(n_cantidad int, n_concepto enum('Entrada', 'Salida'),  id int)
BEGIN
if n_concepto='Entrada' then
UPDATE producto set cantidad=cantidad+n_cantidad WHERE id_producto=id;
end if;
if n_concepto='Salida' then
UPDATE producto set cantidad=cantidad-n_cantidad WHERE id_producto=id;
end if;
END;$$

A: El problema principal ve la respuesta de @ACedano
Otro detalle es que en lugar de usar id, usa por ejemplo id_prod, trata de no usar palabras reservadas.
DELIMITER $$
CREATE PROCEDURE ACTUALIZA_STOCK (n_cantidad int,  n_concepto enum, id_prod int)
BEGIN
if n_concepto='Entrada' then
UPDATE producto set cantidad=cantidad+n_cantidad WHERE id_producto=id_prod;
end if
if n_concepto='Salida' then
UPDATE producto set cantidad=cantidad-n_cantidad WHERE id_producto=id_prod;
end if;
END $$

A: le encontré solución al problema y son los "DELIMITER" el problema esta en como abrir y cerrar el mismo---->
DELIMITER //
CREATE PROCEDURE ACTUALIZA_STOCK
(n_cantidad int, n_concepto enum('Entrada', 'Salida'),  id int)
BEGIN
if n_concepto='Entrada' then
UPDATE producto set cantidad=cantidad+n_cantidad WHERE id_producto=id;
end if;
if n_concepto='Salida' then
UPDATE producto set cantidad=cantidad-n_cantidad WHERE id_producto=id;
end if;
END //
DELIMITER ;

ASI ES COMO TENDRIA QUE QUEDAR Y FUNCIONARIA DE MARAVILLA.


text:
Q: Rewriting subdomains to subfolders and parameter in IIS I'm trying to wrap my head around this problem;
I have a default site with an application that resides in a subfolder, e.g. /app/app.html
It also accepts a language parameter, so for example http://192.168.0.1/app/app.html?language=fi would work.
Now I have two subdomains that I need to not only get rewritten to the correct folder, but also include the language parameter. For example:
fi.domain.com -> http://1.1.1.1/app/app.html?language=fi
swe.domain.com -> http://1.1.1.1/app/app.html?language=swe
I've made A records for both subdomains to point to 1.1.1.1
Currently there are no special bindings (only port 80, no hostnames and all IPs) and no special default pages.
EDIT: I've tried using the URL rewriter module, but I haven't been able to get it work as intended.
EDIT 2: My first example of how I need it to work was a bit flawed, here's a better version;
finnishword.domain.com -> http://1.1.1.1/app/app.html?language=fi
otherwordinswedish.domain.com -> http://1.1.1.1/app/app.html?language=swe

A: I'm not sure to well understand your question.
It seems that you need URL rewriting rules.
According to this link
<rule name="CName to URL - Rewrite" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^(?!www)(.*)\.domain\.com$" />
    </conditions>
    <action type="Rewrite" url="/app/app.html?language={C:1}" />
</rule>

I think it's what you need ;)
Edit 24/08/2016
If you can't have a dynmique pattern with RegEx you have to do as many rules as you have subdomains:
<rule name="finnishRule" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^(?!www)(finnishword)\.domain\.com$" />
    </conditions>
    <action type="Rewrite" url="/app/app.html?language=fi" />
</rule>
<rule name="finnishRule" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^(?!www)(otherwordinswedish)\.domain\.com$" />
    </conditions>
    <action type="Rewrite" url="/app/app.html?language=swe" />
</rule>

or you can mixup all together if you want to redirect all subdomains that contains the word "swedish" on url with ?
<rule name="finnishRule" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^(?!www)(.*swedish.*)\.domain\.com$" />
    </conditions>
    <action type="Rewrite" url="/app/app.html?language=swe" />
</rule>

So after all the RegEx pattern is up to you ;)
Edit 25/08/2016
Maybe you have to add condition to skip static files
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
...
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
     <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>

A: <rules>
            <clear />
            <rule name="swedishMainRule" enabled="true" stopProcessing="true">
                <match url="^$" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{HTTP_HOST}" pattern="^(www\.)?swedishword\.domain\.fi$" />
                    <add input="{QUERY_STRING}" pattern="language=" negate="true" />
                </conditions>
                <action type="Redirect" url="?language=sve" appendQueryString="false" logRewrittenUrl="false" />
            </rule>
            <rule name="swedishRule" enabled="true" stopProcessing="true">
                <match url="(.*)" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{HTTP_HOST}" pattern="^(www\.)?swedishword\.domain\.fi$" />
                </conditions>
                <action type="Rewrite" url="/app/{R:1}" />
            </rule>
            <rule name="finnishRule" enabled="true" stopProcessing="true">
                <match url="(.*)" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{HTTP_HOST}" pattern="^(www\.)?anotherfinnishword\.domain\.fi$" />
                </conditions>
                <action type="Rewrite" url="/app/{R:1}" />
            </rule>
        </rules>

This is how I ended up doing it, basically the first rule deal with the language parameter, and the other rules just rewrite the URL. The Finnish rule doesn't need an extra language rule since the default language of the app is Finnish.


text:
Q: Accessing Microsoft Ajax validation object before sending jQuery Ajax call to server I've created a View which I do both server-side and client-side validation on the page using DataAnnotation attributes which decorate each input on the form. The validation take place when user tab out from a form control or when user clicks on "Submit" button which is of type "submit".

                    <%= Html.LabelFor(model => model.From)%>
                    (Email)*

                    <%= Html.TextBoxFor(model => model.From, new { size=30, maxlength=100})%>
                    <%= Html.ValidationMessageFor(model => model.From)%>

                    <input type="button" id="submitFeedback" value="Send" />
                    <input type="button" id="cancelFeedback" value="Cancel" onclick="closePopup();" />

Since I'm posting form data through Async Ajax call using jQuery. It bypasses the validation set on the form. I want the validation to occur when when user clicks on the button that I use in place of "submit" button.
    $(function() {
        $('#submitFeedback').click(function() {
            $.ajax({
                type: "POST",
                url: "/Feedback/SubmitFeedback",
                data: { from: $('#From').val(), to: $('#To').val(), subject: $('#Subject').val(), body: $('#Comments').val() },
                success: function(feedback) {
                    alert(feedback);
                    closePopup();
                }
            });
        });
    });

I need to have access the Validation object of Microsoft Ajax library on the client side and I assume it has to have some "IsValid" method.
Thanks,
Mohammad

A: Set the name of your javascript validation  function in the Ajax.BeginForm() AjaxOptions:
Ajax.BeginForm("ActionMethod", new AjaxOptions(){OnBegin = "validateForm"}) { ...

This will call the validation function before the form is submitted.


text:
Q: Coordinate of $S(s,t)$ for Which Area of Quadrilateral is Maximum.
Let $P(-2,3)\;\;,Q(-1,1)\;\;,R(s,t)$ and $S(2,7)$ be $4$ points in order on the parabola
$y=ax^2+bx+c$. Then the coordinates of $R(s,t)$ such that the area of Quadrilateral
$PQRS$ is maximum.

$\bf{My\; Try::}$ Here $P(-2,3)\;,Q(-1,1)\;\;,S(2,7)$ be the points lie on the parabola $y=ax^2+bx+c$
So Put $(x,y) = (-2,3)$ in $y=ax^2+bx+c\;,$ We get $4a-2b+c=3.................(1)$
Similarly  Put $(x,y) = (-1,1)$ in $y=ax^2+bx+c\;,$ We get $a-b+c=1...........(2)$
Similarly  Put $(x,y) = (2,7)$ in $y=ax^2+bx+c\;,$ We get $4a+2b+c=7...........(2)$
Now Solving These three equation , We get $a=1\;,b=1\;,c=1$
So we get equation of parabola be $y=x^2+x+1$

Now $\bf{Area\; of\; Quadrilateral\; PQRS = Area\; of \; \triangle PQR+Area\; of \; \triangle PRS}$
So  Area Of Quadrilateral $$A(s,t) = \begin{vmatrix}
 -2& 3 & 1\\
 -1& 1 & 1\\
 s & t & 1
\end{vmatrix}+\begin{vmatrix}
 -2& 3 & 1\\
 s& t & 1\\
 2 & 7 & 1
\end{vmatrix}$$
So $$A(s,t) = 2s+t+1+20+4s-4t = 6s-3t+21$$
Now $R(s,t)$ lie on $y=x^2+x+1.$ So we get $t=s^2+s+1$
So we get $$A(s) = 6s-3(s^2+s+1)+21 = -3s^2+3s+18$$
So using Derivative Test $A'(s)=-6s+3$ and $A''(s)=-6$
So for Max. or min., Put $\displaystyle -6s+3=0\Rightarrow s=\frac{1}{2}$ and $\displaystyle t=\frac{1}{4}+\frac{1}{2}+1 = \frac{7}{4}$
My Question is can we solve it any Shorter way, Means Maximise area using Inequality or Geometrically
If yes Then plz explain here.
Thanks

A: All that calculation was really unnecessary. Here's a fast way:
The area of the quadrilateral PQRS is equal to the sum of the areas of the triangles $\triangle RQS$ and $\triangle PQS$. And since the area of the triangle $\triangle PQS$ is fixed, we need only to maximise the area of the $\triangle RQS$
Additionally since the base QS of the $\triangle RQS$ is also fixed, we need to just maximise the height corresponding to it. To do so we find the point R on the parabola where the tangent is parallel to the base QS.
Doing so, we have $y'=2x+1=2\implies x=\frac 12$ and therefore $R\equiv(\frac 12,\frac 74)$


text:
Q: How to disabled prettier import css This is my order of css imports that should be
import '../styles/globals.css';
import '../public/assets/css/site.css';
import '../public/assets/css/responsive.css';
import '../public/assets/css/icons.css';

But prettier makes it this way for me.
import '../public/assets/css/icons.css';
import '../public/assets/css/responsive.css';
import '../public/assets/css/site.css';
import '../styles/globals.css';

Responsive is not working because my responsive.css file is before site.css.
.prettierrc
{
    "trailingComma": "es5",
    "tabWidth": 4,
    "semi": true,
    "singleQuote": true,
    "printWidth": 120,
}

How can i only disable prettier for these imports


text:
Q: $_POST not working? confused? At the advice of a member on here, I have abandoned mysql_ functions and looked into PDO.
I thought id make a simple page to start playing, but I guess i'm the simple one at the moment...
Am I missing something here? it is late, but I just cant work out why this is not working.
PHP:
<?php

session_start();

include"dbconnect.php";

$query = "SELECT * FROM user WHERE username=?";
$statement = $db->prepare($query);

if ($_POST['submit']){

    if ($_POST['name'] === ""){
        echo "Please enter a name";
    }else{

$user=$_POST['name'];

$statement->execute(array($user));
$fuser = $statement->fetchObject();

}
}

?>

HTML:

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

    enter username here

    <input name="name" id="name" type="text" maxlength="20" />

    <input name="submit" id="submit" type="button" value="submit" />
    <? echo "$fuser->online" ?>

</form>

I am connected to the database correctly because if I remove this section:
if ($_POST['submit']){

    if ($_POST['name'] === ""){
        echo "Please enter a name";
    }else{

$user=$_POST['name'];

and replace $user=$_POST with $user="Mike";
It displays Mikes details as it should.
Can anyone help please?
EDIT: found the problem immediately after rereading it on here >_<
I have the submit button as type=button when it should be =submit ...

A: if(isset($_POST['somename'])
{
//dosomething
}

you have to use isset which returns true or false.

A: Looking over the HTML, try this:

    <input name="submit" id="submit" type="submit" value="submit" />
    <? echo "$fuser->online" ?>

Then the form will actually submit when you click the button.
//edit
as mandouh said, I also recomment changing === "" to isset()


text:
Q: How to do Frontend Progressive Loading with Django? Like trello(http://trello.com), my site need to render a lot of "cards". And each "card" contain some "items".
I did that using standard Django template. To render, I basically run a double loop. The problems occur when I have more cards to render and the page loading becomes really slow.
I read about progressive loading here: http://blog.fogcreek.com/we-spent-a-week-making-trello-boards-load-extremely-fast-heres-how-we-did-it/
So how could I achieve something similar in my case as well? Should I just render the container in the django template and the rest using Javascript? I would like to know what's the best strategy to do this.
EDIT
I found this http://blog.fogcreek.com/the-trello-tech-stack/, which is really helpful


text:
Q: Running Vaadin-based Portlet in Liferay got an " Caused by: java.lang.ClassNotFoundException: com.vaadin.ui.CustomComponent "
when trying to run a vaadin-portlet in liferay .

A: Make sure that in your liferay-plugin-package.properties file you have specified vaadin.jar in your portal-dependency-jars= property.  It should look like this:
name=Vaadin
module-group-id=liferay
module-incremental-version=1
tags=
short-description=
change-log=
page-url=http://www.liferay.com
author=Liferay, Inc.
licenses=
portal-dependency-jars=vaadin.jar


text:
Q: Pagination doesn`t work with extra context in Django ListView I am trying to create a simple pagination through a query of filtered instances of Need model.
The problem is that pagination doesn`t work at all, and I guess this is because of extra content.
Here is my current view, which shows pagination on front-end as an empty div:
class CategoryNeeds(ListView):
    model = Need
    template_name = "volunteering/category_needs.html"
    paginate_by = 1
    context_object_name = "needs"

    def get_queryset(self):
        return Need.objects.filter(category__name=self.kwargs["name"].capitalize())

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        category = Category.objects.get(name=kwargs["name"].capitalize())

        self.extra_context = {
            "category": category,
            "needs": self.object_list
        }

        return self.render_to_response(self.extra_context)

And here is the template:
{% extends "index/index.html" %}
{% block content %}

{{ category.name }}

Needs:

                    Photo
                    Title
                    Description
                    Price
                    Donation
                    City
                    {% if user.pk == user_page.pk %}
                        Update
                        Delete
                    {% endif %}

                {% for need in needs %}

                        {% if need.photo %}{% endif %}
                        {{ need.title }}
                        {{ need.description|truncatechars:10 }}
                        {{ need.price }}
                        {{ need.donation }}
                        {{ need.city }}
                        {% if user.pk == user_page.pk %}
                            Update
                            Delete
                        {% endif %}

                {% endfor %}

            {% if page_obj.has_previous %}
                « Previous page
                {% if page_obj.number > 3 %}
                    1
                    {% if page_obj.number > 4 %}
                        ...
                    {% endif %}
                {% endif %}
            {% endif %}
            {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                    {{ num }}
                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    {{ num }}
                {% endif %}
            {% endfor %}
            {% if page_obj.has_next %}
                {% if page_obj.number < page_obj.paginator.num_pages|add:'-3' %}
                    ...
                    {{ page_obj.paginator.num_pages }}
                {% elif page_obj.number < page_obj.paginator.num_pages|add:'-2' %}
                    {{ page_obj.paginator.num_pages }}
                {% endif %}
                Next Page »
            {% endif %}

{% endblock %}

The reason why I think the problem lies in extra content is because this view works perfectly with pagination:
class AllNeeds(ListView):
    model = Need
    context_object_name = "needs"
    paginate_by = 3

Could someone explain, why doesn`t my pagination work, please?
Would be very grateful for all your responce!

A: Yep, it seems that you are overiding normal django flow which adds context, try this:
class CategoryNeeds(ListView):
    model = Need
    template_name = "volunteering/category_needs.html"
    paginate_by = 1

    def get_queryset(self):
        return Need.objects.filter(category__name=self.kwargs["name"].capitalize())

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        category = Category.objects.get(name=kwargs["name"].capitalize())

        context = self.get_context_data()
        context['category'] = category

        return self.render_to_response(context)


text:
Q: Docker: Angular container works, but machine node_modules are empty and a new volume is created each time I have an Angular container for development and hot-reload enabled. one of the problems I've found is that, on Visual Studio code, all my files have a lot of errors, since the node_modules folder is empty. However, the application works and run fine.
The errors go If do npm install directly on my folder. Ideally I'd like to install the components and have them available on my machine and also the container.
In addition, each time I run my container with docker compose -f development.yml up -d a new volume is created, so I end up with a lot of volumes when I constantly turn on and off the service.
My Dockerfile is this:
FROM node:16

WORKDIR /app
COPY package.json ./

RUN npm install

COPY . .

EXPOSE 4200

Then I build the Dockerfile to have an image called angular_frontend.
And my Docker compose file is:
    services:
      angular-frontend:
        image: angular_frontend
        command: "npm run start-docker-dev"
        ports:
          - 4200:4200
        volumes:
          - /app/node_modules
          - .:/app
        hostname: frontend-localhost.domain.com

Also the package.json I'm using is:
    {
      "name": "frontend",
      "version": "0.0.0",
      "scripts": {
        "ng": "ng",
        "start-dev": "PROJECT=frontend ng serve --ssl --host frontend.domain.com",
        "start-docker-dev": "PROJECT=frontend ng serve --ssl --proxy-config docker.dev.proxy.conf.json --host frontend.domain.com --public-host frontend.domain.com",
        "build-prod": "PROJECT=frontend NODE_ENV=production ng build --configuration=production",
        "build-qa": "PROJECT=frontend NODE_ENV=production ng build --configuration=qa",
        "build-dev": "PROJECT=frontend ng build",
        "lint": "ng lint",
        "test": "jest --coverage --reporters=default --reporters=jest-junit --detectOpenHandles",
        "test-watch": "jest --watch",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "~12.2.13",
        "@angular/common": "~12.2.13",
        "@angular/compiler": "~12.2.13",
        "@angular/core": "~12.2.13",
        "@angular/forms": "~12.2.13",
        "@angular/platform-browser": "~12.2.13",
        "@angular/platform-browser-dynamic": "~12.2.13",
        "@angular/router": "~12.2.13",
        "@ed/subtract": "^2.4.1",
        "@fnando/sparkline": "^0.3.10",
        "chart.js": "^3.4.1",
        "chartjs-plugin-datalabels": "^2.0.0",
        "lodash": "^4.17.21",
        "ngx-cookie-service": "^12.0.0",
        "rxjs": "~6.6.6",
        "tailwindcss": "^2.0.4",
        "tslib": "^2.0.0",
        "zone.js": "~0.11.4"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~12.2.13",
        "@angular-eslint/builder": "12.6.1",
        "@angular-eslint/eslint-plugin": "12.6.1",
        "@angular-eslint/eslint-plugin-template": "12.6.1",
        "@angular-eslint/schematics": "12.6.1",
        "@angular-eslint/template-parser": "12.6.1",
        "@angular/cli": "~12.2.13",
        "@angular/compiler-cli": "~12.2.13",
        "@types/chart.js": "^2.9.32",
        "@types/fnando__sparkline": "^0.3.3",
        "@types/jest": "^26.0.20",
        "@types/lodash": "^4.14.168",
        "@types/node": "^12.11.1",
        "@typescript-eslint/eslint-plugin": "4.28.2",
        "@typescript-eslint/parser": "4.28.2",
        "codelyzer": "^6.0.0",
        "eslint": "^7.26.0",
        "eslint-config-airbnb-typescript": "^12.3.1",
        "eslint-plugin-import": "2.22.1",
        "eslint-plugin-jsdoc": "30.7.6",
        "eslint-plugin-prefer-arrow": "1.2.2",
        "jest": "^26.6.3",
        "jest-junit": "^12.0.0",
        "jest-preset-angular": "^8.3.2",
        "ts-node": "~8.3.0",
        "typescript": "~4.3.5"
      },
      "jest": {
        "preset": "jest-preset-angular",
        "setupFilesAfterEnv": [
          "<rootDir>/setup-jest.ts"
        ],
        "roots": [
          "<rootDir>/projects/a",
          "<rootDir>/projects/b"
        ],
        "modulePaths": [
          "<rootDir>/projects/a",
          "<rootDir>/projects/b"
        ]
      }
    }

A: Since you stated that your use case is for development purposes - I recommend to restructure your approach a little.
1. Dockerfile
It only makes sense to run npm install in the Dockerfile if you will be using this image for shipping the complete code with modules. Since you're using it for development - it's useless here. Also - since you will be mounting the entire local folder into the container - remove the ADD and COPY commands.
FROM node:16

WORKDIR /app

EXPOSE 4200

2. docker-compose
You should remove the /app/node_modules volume and change the command the container will use:
services:
  angular-frontend:
    image: angular_frontend
    command: "bash -c 'npm install && npm run start-docker-dev'"
    ports:
      - 4200:4200
    volumes:
      - .:/app
    hostname: frontend-localhost.domain.com

this way - your entire project folder is mapped to the /app folder as a volume. The npm install command will run when the container starts.


text:
Q: Toshiba- battery won't quit charging Toshiba laptop with Windows 10. Battery charges to 94% but will not quit charging and won't go any higher.
What do I do?
My problem has been solved. Thanks.

A: Your battery isn't calibrated anymore. It actually reaches 100% but because it isn't calibrated, it keeps charging, which damages the battery.
Luckily there is a trick you can do for any kind of rechargeable battery (also works for phones).
First, Use up the battery until the laptop turns off. Keep in mind, that it will at some point put the laptop in stand-by to save power. Given that you don't actually want that, at some point when it starts doing this, reboot the laptop and enter the bios so you can keep it on.
Do anything you can do to make the battery drain faster, such as enable bluetooth, put the brightness on highest, and perhaps play some games.
At some point when the battery is near its lowest point, it may turn off the laptop. Without charging, turn the laptop on as many times as you can until it really does not turn on anymore. In odd cases, this can be up to 100 times, so be prepared for that.
When the laptop finally won't turn on anymore, put the charger on and charge it up all the way to 100%. Don't unplug early, make sure you charge up to 100% in one go. You can use the laptop while doing so, but it will make charging take longer. So it is probably better to keep it charging while powered off for an hour before turning it on.
Once the battery is at 100% and you're sure it isn't charging anymore (the icon will change) you can unplug the power, and your battery is calibrated.
Alternatively but definitely not required, you can of course buy a new battery.


text:
Q: Chinese reminder Theorem and primitive roots The problem I am working on is "Let $p$ be a prime such that $p\equiv 1\pmod{105}$. Show that there exist integers $n, x, y, z$ such that $p$ does not divide $n$ and $n \equiv 3x^3 \equiv 5y^5 \equiv 7z^7 \pmod p$.
I'm looking for suggestions on how to approach this. I think I want to set up a series of equations so that I can use the Chinese Remainder theory to reduce them to something I can demonstrate is solvable.
I've also been looking at primitive roots - there is a primitive root, $g$ that generates $\mathbb{Z}_p$ which will have an order $105k$ for some integer $k$, but other than writing $x, y, z$ in terms of $g$, I'm not getting anywhere with this.
My instinct is to take $n = 105$, which would let me reduce to showing 35 has a cube root, 21 has a fifth root and 15 has a seventh root, but I'm not getting anywhere with that approach.
I'd very much appreciate any suggestions.

A: We look for a solution of the shape $n=3^a5^b7^c$.
We want $n$ to be congruent to $3x^3$ modulo $p$. That makes $9n$ a perfect cube modulo $p$. If a number is a plain perfect cube, then it is a perfect cube modulo $p$. It follows that if we take
$$a\equiv -2\pmod{3},\quad b\equiv 0\pmod{3},\quad c\equiv 0\pmod{3},$$
then $9\cdot 3^a5^b7^c$ will be a perfect cube modulo $p$.
Similarly, it is enough to make $5^4n$  a perfect fifth power. That gives the congruences
$$a\equiv 0\pmod{5},\quad b\equiv -4\pmod{5},\quad c\equiv 0\pmod{5}.$$
A similar analysis for $7$ gives
$$a\equiv 0\pmod{7},\quad b\equiv 0\pmod{5},\quad c\equiv -6\pmod{7}.$$
We get a system of $3$ congruences for each of $a$, $b$, and $c$. They are no trouble to solve.
Remark: The modulus $p$ played essentially no role, and the Chinese Remainder Theorem, though in principle present, is not really needed. We can find other solutions by using $k^{105}3^a5^b7^c$ with any $k$ relatively prime to $p$.


text:
Q: How do I get from $f^2 = \mathrm{id}_V$ to $(f- \mathrm{id}_V)$ and $(f+ \mathrm{id}_V)$ Given
$f^2= \mathrm{id}_V$,
I'm asked to prove that the direct sum of the kernels of $(f-  \mathrm{id}_V)$ and $(f+ \mathrm{id}_V)$, is the whole space $V$.
Am I correct that since $f\circ f$ is the identity, then $f$ is it's own inverse? I still get lost at how to arrive to the sum and difference expressions though, any hint would do.
(Edited in response to T.Bongers's comment)

A: We have $f^2-\operatorname{id}_V=(f-\operatorname{id}_V)(f+\operatorname{id}_V)=0\quad(*)$
Now since the polynomial $(x-1)$ and $(x+1)$ are coprime then by Bezout's identity there are $S,T$ two polynomials such that
$$S(x)(x-1)+T(x)(x+1)=1$$
so applying to $f$ and then to $x\in V$ and using $(*)$ we get
$$\underbrace{S(f)(f-\operatorname{id}_V)(x)}_{\in\ker(f+\operatorname{id}_V)}+\underbrace{T(f)(f+\operatorname{id}_V(x))}_{\in\ker(f-\operatorname{id}_V)}=\operatorname{id}_V(x)=x$$
so $$V=\ker(f-\operatorname{id}_V)+\ker(f+\operatorname{id}_V)$$
and since the intersection is trivially $\{0\}$ we get the desired result.

A: Hint: If $x\in V$ is arbitrary, what can you say about the vectors
$$
x_1=\frac{x+f(x)}2\qquad\text{and}\qquad x_2=\frac{x-f(x)}2.
$$


text:
Q: Laravel cache remember forever I have this piece of code that I thought would remember cache forever:
$setting = \Cache::remember('website_description', 0,  function() {
  return App\Models\Setting::where('name', 'website_description')->first();
});

But it doesn't remember at all, someone told me that passing 0 to remember function would make it remember forever. Since this doesn't work what other way can I put an item in cache forever?

A: You can try this:
if (! \Cache::has('website_description')) {
    \Cache::forever('website_description', App\Models\Setting::where('name', 'website_description')->first());
}

A: Just change remember to rememberForever and remove time parameter
 $setting = \Cache::rememberForever('website_description', function() {
            return App\Models\Setting::where('name', 'website_description')->first();
        });

Reference for rememberForever


text:
Q: Optimize deep Q network with long episode I am working on a problem for which we aim to solve with deep Q learning. However, the problem is that training just takes too long for each episode, roughly 83 hours. We are envisioning to solve the problem within, say, 100 episode.
So we are gradually learning a matrix (100 * 10), and within each episode, we need to perform 100*10 iterations of certain operations. Basically we select a candidate from a pool of 1000 candidates, put this candidate in the matrix, and compute a reward function by feeding the whole matrix as the input:

The central hurdle is that the reward function computation at each step is costly, roughly 2 minutes, and each time we update one entry in the matrix.
All the elements in the matrix depend on each other in the long term, so the whole procedure seems not suitable for some "distributed" system, if I understood correctly.
Could anyone shed some lights on how we look at the potential optimization opportunities here? Like some extra engineering efforts or so? Any suggestion and comments would be appreciated very much. Thanks.
======================= update of some definitions =================
0. initial stage:

*

*a 100 * 10 matrix, with every element as empty

1. action space:

*

*each step I will select one element from a candidate pool of 1000 elements. Then insert the element into the matrix one by one.

2. environment:

*

*each step I will have an updated matrix to learn.

*An oracle function F returns a quantitative value range from 5000 ~ 30000, the higher the better (roughly one computation of F takes 120 seconds).
This function F takes the matrix as the input and perform a very costly computation, and it returns a quantitative value to indicate the quality of the synthesized matrix so far.
This function is essentially used to measure some performance of system, so it do takes a while to compute a reward value at each step.
3. episode:
By saying "we are envisioning to solve it within 100 episodes", that's just an empirical estimation. But it shouldn't be less than 100 episode, at least.
4. constraints
Ideally, like I mentioned, "All the elements in the matrix depend on each other in the long term", and that's why the reward function F computes the reward by taking the whole matrix as the input rather than the latest selected element.
Indeed by appending more and more elements in the matrix, the reward could increase, or it could decrease as well.
5. goal
The synthesized matrix should let the oracle function F returns a value greater than 25000. Whenever it reaches this goal, I will terminate the learning step.

A: Honestly, there is no effective way to know how to optimize this system without knowing specifics such as which computations are in the reward function or which programming design decisions you have made that we can help with.
You are probably right that the episodes are not suitable for distributed calculation, meaning we cannot parallelize this, as they depend on previous search steps. However, it might be possible to throw more computing power at the reward function evaluation, reducing the total time required to run.
I would encourage you to share more details on the problem, for example by profiling the code to see which component takes up most time, by sharing a code excerpt or, as the standard for doing science gets higher, sharing a reproduceable code base.

A: Not a solution to your question, just some general thoughts that maybe are relevant:

*

*One of the biggest obstacles to apply Reinforcement Learning in "real world" problems is the astoundingly large amount of data/experience required to achieve acceptable results. For example, OpenAI in Dota 2 game colletected the experience equivalent to 900 years per day. In the original Deep Q-network paper, in order to achieve a performance close to a typicial human, it was required hundres of millions of game frames, depending on the specific game. In other benchmarks where the input are not raw pixels, such as MuJoCo, the situation isn't a lot better. So, if you don't have a simulator that can generate samples (state, action, next state, reward) cheaply, maybe RL is not a good choice. On the other hand, if you have a ground-truth model, maybe other approaches can easily outperform RL, such as Monte Carlo Tree Search (e.g., Deep Learning for Real-Time Atari Game Play Using Offline Monte-Carlo Tree Search Planning or Simple random search provides a competitive approach to reinforcement learning). All these ideas a much more are discussed in this great blog post.

*The previous point is specially true for deep RL. The fact of approximatting value functions or policies using a deep neural network with millions of parameters usually implies that you'll need a huge quantity of data, or experience.

And regarding to your specific question:

*

*In the comments, I've asked a few questions about the specific features of your problem. I was trying to figure out if you really need RL to solve the problem, since it's not the easiest technique to apply. On the other hand, if you really need RL, it's not clear if you should use a deep neural network as approximator or you can use a shallow model (e.g., random trees). However, these questions an other potential optimizations require more domain knowledge. Here, it seems you are not able to share the domain of the problem, which could be due a numerous reasons and I perfectly understand.

*You have estimated the number of required episodes to solve the problem based on some empirical studies using a smaller version of size 20*10 matrix. Just a caution note: due to the curse of the dimensionality, the complexity of the problem (or the experience needed) could grow exponentially when the state space dimensionalty grows, although maybe it is not your case.

That said, I'm looking forward to see an answer that really helps you to solve your problem.


text:
Q: Sending an HTTP Post using Javascript triggered event I'm pretty new to javascript and am working on an embedded system which decodes video over IP.
I have written a small app for setting up and changing channels using javascript and included a key handler for remote controls and an event handler so I can take some action or present a message if video stops or the network goes down, but now I also want to set up an automatic HTTP POST that gets sent when I change channel to include some data about the device and the url currently being played.
This is a small embedded hardware device running busybox, so I can't use Ajax or add any other normal web technologies, I just need to use Javascript to send a HTTP POST triggered by events I am monitoring, so my first goal is to be able to press a button and send that POST message then work out when to trigger it later.
Anyone familiar with doing such things that can give me a quick overview of how to send a post to a known listening device/location and include data in it?
Many thanks

A: This is easy if your Javascript engine supports XMLHttpRequest (XHR), which is ubiquitous on the web. Google it or see this page for details. I've provided a code snippet below. Read it carefully, particularly the comments on "async" being true and closures in response handlers. Also, this code is super lightweight as far as Javascript goes and I would expect it would work fine on just about any contemporary hardware footprint.
var url = "http://www.google.com/";
var method = "POST";
var postData = "Some data";

// You REALLY want shouldBeAsync = true.
// Otherwise, it'll block ALL execution waiting for server response.
var shouldBeAsync = true;

var request = new XMLHttpRequest();

// Before we send anything, we first have to say what we will do when the
// server responds. This seems backwards (say how we'll respond before we send
// the request? huh?), but that's how Javascript works.
// This function attached to the XMLHttpRequest "onload" property specifies how
// the HTTP response will be handled.
request.onload = function () {

   // Because of javascript's fabulous closure concept, the XMLHttpRequest "request"
   // object declared above is available in this function even though this function
   // executes long after the request is sent and long after this function is
   // instantiated. This fact is CRUCIAL to the workings of XHR in ordinary
   // applications.

   // You can get all kinds of information about the HTTP response.
   var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
   var data = request.responseText; // Returned data, e.g., an HTML document.
}

request.open(method, url, shouldBeAsync);

request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// Or... request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
// Or... whatever

// Actually sends the request to the server.
request.send(postData);


text:
Q: Get sibling's name attribute, use it to adjust value of element with equivalent ID I am trying to set up a system such that when a button is clicked, the value of an input field is adjusted.
The ID of the field to be adjusted is equal to the name of the sibling element of the button.
As such, I'm attempting to code:
On button click
 - Get sibling's name
 - Get element with ID equal to siblings name
 - Change value of that element
Here is my attempt:
$(function() {
    $('#values').on('click', '.remField', function() {
        var = $(this).siblings().name()
        $('#var').val('DELETE');
        return false;
    });
});

However this does not work.

A: Your selector creation and retrieval of name is incorrect try:
 $('#values').on('click', '.remField', function() {
        var name = $(this).siblings().attr('name');
        $('#' + name).val('DELETE');
        return false;
    });

Note that siblings may return multiple items as a collection and attr on a collection will get the name of the 1st item in the collection. If you know it is the next of prev element then better use .next() or .prev() to be more specific. var is a keyword you can't use that as a variable name.

A: Use .attr()
$('#values').on('click', '.remField', function () {
    var name = $(this).siblings().attr('name');
    $('#' + name).val('DELETE');
    return false;
});

.siblings() will return multiple items


text:
Q: Construct org.w3c.dom.Document from marshalled object I'd like to construct a org.w3c.dom.Document from my marshalled object.
I've tried what's described in this topic but in vain.
This is my code :
public Document serialise() throws Exception {
    MyClass myObjectToMarshall = this.getObjectToMarshall();
    JAXBContext jc = JAXBContext.newInstance(MyClass.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    m.marshal(myObjectToMarshall , System.out);
    StringWriter xml = new StringWriter();
    m.marshal(myObjectToMarshall , xml);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xml.toString())));
}

When this instruction m.marshal(myObjectToMarshall , System.out); is executed, I get the following result :
<myObjectToMarshall >
    <id>15</id>
    MY_CODE
    MY_LABEL
    <date>2015-09-15+02:00</date>
</myObjectToMarshall >

I guess the marshalling of myObjectToMarshall has been correctly done.
But, when I debug the last instruction using IntelliJ, builder.parse(new InputSource(new StringReader(xml.toString()))), I get a null Document : [#document: null]
Is there other properties to set?
Please could you help me to undestand why document is null?
Thank you in advance.
P.S. I'm using java 7.

A: You Document is fine.
The toString() method is implemented to return "["+getNodeName()+": "+getNodeValue()+"]". The nodeName of a document is #document, and the nodeValue of a document is null. See the javadoc of Node.
If you want a DOM document, don't marshal into a String and then parse the text. Just marshal straight into a DOM tree:
public Document serialise() throws Exception {
    MyClass myObjectToMarshall = this.getObjectToMarshall();
    JAXBContext jc = JAXBContext.newInstance(MyClass.class);
    DOMResult domResult = new DOMResult();
    jc.createMarshaller().marshal(myObjectToMarshall, domResult);
    return (Document)domResult.getNode();
}


text:
Q: Inheritance XML Deserialization by Type Attribute I have XML that looks something like this:
<root>
    <base type="a">
        <common>1</common>
        <concreteA>one</concreteA>
    </base>
    <base type="b">
        <common>2</common>
        <concreteB>two</concreteB>
    </base>
</root>

And classes like this:
public class Root
{
    public List<Base> Bases { get; set; }
}

public class Base
{
    public int Common { get; set; }
}

public class A : Base
{
    public string ConcreteA { get; set; }
}

public class B : Base
{
    public string ConcreteB { get; set; }
}

How can I deserialize this into objects? I've seen many posts on how to do it when each base node has a different name using XmlArrayItemAttribute( ElementName, Type )], but I need to choose it based on the elements type attribute instead.

A: This is a very basic way of doing it, but I think it works. I think if the class type was an element instead of an attribute then you should be able to parse it declaratively.
The code basically switches on the type attribute top determine what subclass to create and then manually populates the concrete properties and the common property.
[System.Xml.Serialization.XmlType("base")]
public class Base
{
    [System.Xml.Serialization.XmlElement("common")]
    public int Common { get; set; }
}

public class A : Base
{
    public string ConcreteA { get; set; }
}

public class B : Base
{
    public string ConcreteB { get; set; }
}

[System.Xml.Serialization.XmlRootAttribute("root")]
public class Root : System.Xml.Serialization.IXmlSerializable
{
    [System.Xml.Serialization.XmlElement("base")]
    public List<Base> Bases { get; set; }

     public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        this.Bases = new List<Base>();
        var document = XDocument.Load(reader);

        foreach (var element in document.Root.Elements())
        {
            Base baseElement = null;

            var attr = element.Attribute("type");

            if(attr.Value == "a")
            {
                var a = new A();
                a.ConcreteA = element.Element("concreteA").Value;
                baseElement = a;
            }
            else
            {
                var b = new B();
                b.ConcreteB = element.Element("concreteB").Value;
                baseElement = b;
            }

            baseElement.Common = int.Parse(element.Element("common").Value);
            this.Bases.Add(baseElement);
        }

        this.Bases.Dump();
    }

    public void WriteXml(XmlWriter writer)
    {
        throw new NotSupportedException();
    }
}

void Main()
{
    var xmlString = @"<root>
    <base type=""a"">
        <common>1</common>
        <concreteA>one</concreteA>
    </base>
    <base type=""b"">
        <common>2</common>
        <concreteB>two</concreteB>
    </base>
</root>";

    var stream = new StringReader(xmlString);
    var deserializer = new System.Xml.Serialization.XmlSerializer(typeof(Root));
    var result = (Root)deserializer.Deserialize(stream);
}


text:
Q: Find the same value in three Colomns with same name but in different tables I am currently making an android app which uses a feed to display statuses made by users. I have three tables within the same database, each has username either as a primary or unique key column, but each table has different information relating to that user.
For instance, the first table ===>> tbl_users:

*

*username

*fname (first name)

*mname (middle name)

*lname (last name)

*etc. (the list is long)

The second table ===>> tbl_userprofilepictures:

*

*profilepictureID

*username

*profilepicturepath

The third table ===>> tbl_user_feed:

*

*postID (the status' unique ID)

*username

*status

*imagepostpath (the path to the image uploaded with the status)

*timestamp

I want to be able to search for the username across all three tables and display the relevant information relating to them on their post. For example I will need their name and surname for tbl_users and I will need their profilepicturepath for tbl_userprofilepictures as well as their status, imagepostpath and timestamp from tbl_user_feed.
Would I need to do this in a seperate PHP file or in the app itself? PS I'm fairly noob at PHP so please feel free to help a bro out.
May the force be with you.

A: You can use JOIN.
What is JOIN ?

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.

Source : w3schools.com Joins
Here is the sample I made base on your tables given. For these one our common field is username.
SELECT CONCAT('a.fname', 'a.lname'), b.profilepictureID, c.status, c.imagepostpath, c.timestamp
FROM
tbl_users as a
LEFT JOIN tbl_userprofilepictures as b ON b.username = a.username
LEFT JOIN tbl_user_feed as c ON c.username = a.username

Using Alias (table_name as custom_name) is a good practice in joining the tables


text:
Q: UIPageViewController hard cover as well as page curl animation I'm trying to give animation like hardcover page turn effect for first and last page and simple page curl (default for UIPageViewController) to give an album type touch. Can anyone help me to do this using UIPageViewController? I need to display like this as in Mosaic photobook app:
For First page ,
http://i.i.com.com/cnwk.1d/i/tim/2012/10/22/PhotoBookCoverShuffle.png
For all pages except last hard cover
http://techpicky.com/wp-content/uploads/2012/10/Mosaic.png
And Last page should close the Album
No one has helped yet. :(

A: There are actually many 3rd party libraries. You can try out and modified that according to your needs. Following are some of them.
https://github.com/mpospese/MPFlipViewController
https://github.com/xissburg/XBPageCurl
https://www.cocoacontrols.com/controls/pagecurl


text:
Q: How do I add smart folders type functionality to windows 8? Is it possible to use a smart folder that you created on a mac and use it on a PC?
Thanks in advance for answer (s)

A: Just as Smart Folders in OS X are saved Spotlight searches, similarly you can save your searches in Windows 8's File Explorer too:

Any searches you've previously saved will be visible in the left navigation pane under Favorites:

Note: Technically speaking they're saved as .search-ms XML files in C:\Users\<UserName>\Searches, and the format is documented here.
Tip: For complex searches you should check out AQS (another article here), although lack of regex support is really frustrating.
You can also use Libraries to aggregate your files from different locations into a single place:


text:
Q: Set Youtube Data API key on Rails using Javascript/jQuery/JSON I am trying to do exactly the same as this tutorial (https://www.youtube.com/watch?v=-vH2eZAM30s&feature=youtu.be) on Rails but I am stuck at a point (see at 1:40) whether I need to specify  in application.html.erb in different format or there is any other way to do it.
First of all, after I have obtained authorisation credentials through creating a project in the google developers console, I began to first proceeded to follow this tutorial (https://www.youtube.com/watch?v=jdqsiFw74Jk). This was fairly easy and I had no problem with it as this tutorial specifies the key in every method or call. (see at 13:30).
However, (www.youtube.com/watch?v=-vH2eZAM30s&feature=youtu.be) when I started learning this second tutorial, I found that the tutorial approached requesting an API call slightly differently from the first tutorial. It set the api key in init() function and onload it with the script file and not specifying the key in methods and calling api requests.

*

*developers.google.com/youtube/v3/guides/auth/client-side-web-apps

*developers.google.com/api-client-library/javascript/reference/referencedocs

I looked up these guides but none of them gave me hints to follow the second tutorial on Rails.
How can I implement the second tutorial on Rails and What are the differences between the methods of setting the api key used in the first and second tutorial??


text:
Q: Alarm pending intent getting called again and again I have added alarms in a project I am currently working on. They are working fine with all my conditions. Facing one small problem. I have added a one-shot alarm, I want it to fire on time, which is working fine and upon reaching its time it is opening an activity with values I am sending through intent. Problem is even after the alarm has been fired, the pending intent is called up again and which opens the activity with null values when I close that activity it again pops up as many times as I close it. The pending intent is not getting cancelled after it has fired at its designated time. Below is my code to set alarm.
public void setAlarm(int hours, int minutes,String AMPM, String alarmType,String message, String extraMessage)
    {

        Random rand = new Random();
        int  n = rand.nextInt(10000) + 1;
        Log.e("HMA",hours+"   "+minutes+"   "+AMPM + " " + message + extraMessage);

//                       Toast.makeText(getApplicationContext(), "Alarm On",
        //   Toast.LENGTH_SHORT).show();
        Calendar calendar = Calendar.getInstance();
        // set selected time from timepicker to calendar
        calendar.set(Calendar.HOUR_OF_DAY, hours);
        calendar.set(Calendar.MINUTE,minutes);
        calendar.set(Calendar.SECOND,00);

        if(AMPM.equals("PM")) {
            Log.e("PM","");
            calendar.set(Calendar.AM_PM, Calendar.PM);
        }
        else
        {
            calendar.set(Calendar.AM_PM, Calendar.AM);
        }
        Intent myIntent = new Intent(this,
                MyReceiver.class);
        AlarmManager alarmManager;
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        myIntent.putExtra("alarmType",alarmType);
        myIntent.putExtra("gifMessage",message);
        myIntent.putExtra("extraMessage",extraMessage);

        PendingIntent pendingIntent;

        // A PendingIntent specifies an action to take in the
        // future
        pendingIntent = PendingIntent.getBroadcast(
                this, n, myIntent, 0);

        // set alarm time
        if(Build.VERSION.SDK_INT<19) {
            alarmManager.set(AlarmManager.RTC,
                    calendar.getTimeInMillis(), pendingIntent);
        }
        else if(Build.VERSION.SDK_INT>=19 && Build.VERSION.SDK_INT<=22)
        {
            alarmManager.setExact(AlarmManager.RTC,
                    calendar.getTimeInMillis(), pendingIntent);
        }
        else if(Build.VERSION.SDK_INT>=23)
        {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC,
                    calendar.getTimeInMillis(), pendingIntent);
        }
    }

A: I solved it using IntentService instead of Service and returning START_NOT_STICKY in onStartCommand.


text:
Q: EnumerateChildNodesWithName access method I want to find some nodes by name and then call a function called update on that node.
have the following code:
encounter.enumerateChildNodesWithName(enemy)
{
    node, stop in
    node.update()
}

I cannot call the method update() my enemy class looks like this
class EnemyPrototype: SKSpriteNode, EnemySprite
{
  func update(){}
}

Why does it not work?
I guess that node is referencing the SKSpriteNode class but not the EnemyPrototype class.
Or am I just using EnumerateChildNodesWithName incorrectly?
Thanks.

A: That is because the node is SKNode. You have to downcast it to EnemyPrototype like this:
encounter.enumerateChildNodesWithName("enemy"){ node , stop in

    if let enemy = node as? EnemyPrototype {

         enemy.update()
    }
}

I assume that downcast can fail (for example if you have other nodes of different types added to encounter node) so I use conditional downcast as? operator rather than as! version (forced downcast) of this operator.


text:
Q: Surjectivity of $\frac{z}{(1-z)^2}$ onto $\mathbb C$ from the open unit disc Can you say something about the surjectivity of $\frac{z}{(1-z)^2}$ onto $\mathbb C$ from the open unit disc?
My attempt:  I am getting $\frac{z}{(1-z)^2}=w \neq 0 \Rightarrow z=\frac{2+\frac{1}{w}\pm \sqrt{\frac{4}{w}+\frac{1}{w^2}}}{2}$, but iam not sure $z$ in open unit disc.

A: $f(z) = \frac{z}{(1-z)^2}$ is the so-called Koebe function. It maps the unit disk conformally to the "slit domain" $\Bbb C \setminus (-\infty, -1/4]$, which can be seen by writing the function in the form
$$
 f(z) = \frac 14 \left( \frac{1+z}{1-z}\right)^2 - \frac 14 \, .
$$

A: It is not onto. Let us first check that this map is injective: $\frac a {(1-a)^{2}}=\frac b {(1-b)^{2}}$ implies that $a+ab^{2}-2ab=b+ba^{2}-2ab$ or $(a-b) (1-ab)=0$. $1-ab \neq 0$ because $|ab| <1$. Hence $a=b$. If this map is onto then  $\mathbb C$ would be conformally equivalent to the unit disk which is false.
[The inverse of this map would be a bounded analytic function, hence a  constant].


text:
Q: How to add custom ttf fonts to iphone application? I have problem of adding fonts to my iphone application
I want to know how to do it, and let me specify that I am not using IB and I have inherited the UILabel and making label of that new class,
Please Help me out,
I have downloaded the ttf and want to use in my app,
I added "Fonts Provided by application" to my app and then added the font name with ttf extension, but still didn't work, what should I do ?
@implementation RRSGlowLabel

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self != nil) {
        self.glowOffset = CGSizeMake(0.0, 0.0);
       self.glowAmount = 0.0;
        self.glowColor = [UIColor clearColor];
   [self setFont: [UIFont fontWithName: @"DS-DIGI" size: self.font.pointSize]];
    }
    return self;
}

Where DS-DIGI.ttf is my font, added tou resources forlder,
and RRSGlowLabel is inherited class of UILabel, now what should I do?

A: In order to call the font in your fontWithName call, the string should be the name of the font as it is displayed in the Mac's 'Font Book' app, and not the actual filename of the referenced font file


text:
Q: Raid Enclosures for running VM's I'm looking at getting a Raid Enclosure for running vm's on.  I have noticed that the ones that I have found, only have 1 sata port on the back of them.  I'm going to be running the hard drives in this enclosure in RAID 0.  Would this 1 sata port be a performance bottleneck when running the vm's?  I will also be getting 3 - 4 250gb 7200rpm drives, and running 6 - 8 vm's on the machine.  I can't have an internal setup because the computer only has 1 hard drive bay.
Basically I'm going to have a test environment.  There will be a Domain Controller server running AD, DNS, DHCP, and will have a couple user accounts.  Then I will have a Windows Deployment Server, Configuration Manager Server, exchange server, and any other server to test and learn how to use.  Those servers will probably not be running at the same time unless there is a good reason to do so.  Then the rest will be dummy win7 machines, to verify servers are running and doing what they are suppose to do.  I'm trying to prepare for microsoft certifications and implement new solutions into my work environment if they work out.

A: The single port will be a bottleneck.  Some VMs may require more or less I/O so more info is needed.
While not as neat as one array, I have used eSATA RAID 1 drives from Western Digital to run multiple VMs.  One external eSATA device per VM.  USB 3.0 devices would work as well.
Not ideal but it works well for teh VMs I have been running

A: I currently use a CFI A7879 Mini-ITX Server Case.
This case supports up to four 3.5" hard drives and one 2.5" SSD/hard drive. This chassis only support ITX boards. I use a Intel Atom based board, which works fine for Windows Server 2008 R2 but obviously won't support Hyper-V. Depending on how you set this up:

*

*You either want to go with the most powerful ITX board you can find (make sure it has enough SATA ports) so you can run some type of visualization software on it.

*Only use it for storage by setting up iSCSI targets and then keeping your VMs on it and using something like VirtualBox to connect to the VMs. Make sure you have a Gigabit connection too.


text:
Q: How to use of present perfect or present simple in future time clause? I don't understand how difference is  between present simple and present perfect in future time clause?
For instance,

*

*I will go out when I finish my assignment.

*I will go out when I have finished my assignment.

A: To the average person on the street these two answers would have the same meaning regardless of their different verb structures.
However, I think there is a subtle difference which is more technical that practical.
The first  using the simple form might be given if the person was asked the following question:
John, when are you coming out?
John's answer uses the simple form because he is stating the fact that he will go out (for sure) but he possibly has some other things to do in the meantime like playing soccer, etc. BUT it (the assignment) will be finished.  He just doesn't know when.
John would probably answer using the present perfect form if the same question is asked while he is sitting at his desk working on his assignment with no intention to do anything else until he finishes it and then  he goes out.
He was working on the assignment before the point in time before he was asked the question and will no doubt continue up to the point where he will get up and go out.
Some help from Martin Parrots book:' Grammar for English Language Teachers


text:
Q: CUDA documentation does not mention compatibility requirements for Debian systems I often need to recall the compatibility between host and device compilers and refer to the documentation page
https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#system-requirements
The table in there does not mention the Debian distribution at all, though.
This seems odd to me, for Debian is a reputable and popular Linux distribution.

Is there a rational for this at least nominal absence, and how should one work around it?
In other words: given a CUDA version and a Debian system, how can I obtain the corresponding compatible versions of kernel, gcc version and so on?

A:
how can I obtain the corresponding compatible versions of kernel, gcc version and so on?

There aren't any.
CUDA isn't supported by NVIDIA for use on Debian as a development environment.  The support footprint as you've already pointed out is spelled out (for linux) in the linux install guide, in the table you excerpted, and absence from the table means that item (distro, kernel version, gcc version, etc.) is not officially supported.
The rationale for this is that each additional linux distro supported increases CUDA support costs.  One example of this is in QA costs.  Each CUDA release has a huge test matrix associated with it, and adding a new linux distro essentially increases the dimensionality of that test matrix.  These costs have to be considered against the benefit of supporting that particular distro.  As more distros are supported, there are decreasing returns on investment.
I won't be able to give a detailed answer on the specific business cost/benefit analysis as it pertains to Debian specifically, and that is not really a programming question anyway.
If you'd like to see a change in CUDA, whether it be functionality, documentation, support, etc., you're encouraged to file a bug to express your desires/concerns at http://developer.nvidia.com    The specific process to file a bug (not a programming question anyway) but it is easy to discover;  here is a current link to the process description.
We can generalize this answer to other similar questions of why a particular environment is not supported in CUDA. (For example, Linux Mint is not officially supported, neither is Scientific Linux.) The concepts discussed here are not unique to Debian, and similar comments could be made about a wide variety of compatibility scenarios.
I'm trying to address the question of why similar information for Debian is not present in the table excerpted in the question.  I'm not intending to answer the question "is there any way to use CUDA on Debian?" which I view as a separate question.  For that one, google is your friend, but there is no official statement of support or compatibility with Debian.


text:
Q: Darboux versus stochastic integral I don't know if my question is obscure. I'm astonished why there not mention the  Darboux sums in the definition of stochastic integral

A: Darboux sums are not mentioned because they are not useful in the definition of the stochastic integral. To see why, notice the difference between the Itō integral and the Stratonovich integral, in particular noting that the two give different answers.
Edited to add more detail: You can think of the Itō integral as defined using Riemann–Stieltjes sums with the integrand always evaluated at the left end of each subinterval, whereas the Stratonivich integral uses instead the average of values at the left and right ends of each subinterval. Darboux sums, in contrast, use the minimum and maximum values of the integrand on each subinterval. Therein lies a problem of its own, for Brownian motion is not monotone, and so $B(t_{i+1})-B(t_i)$ can have either sign. You might remedy that by defining the upper Darboux sum to use the maximum in intervals where $B(t_{i+1})-B(t_i)$ is positive, and the minimum where it is negative – and the opposite for the lower Darboux sum. In which case the Itō sum and Stratonivich sums will both lie between the upper and lower Darboux sums. Since the former two will in general converge to different values, so must the latter two, and hence you cannot define the Darboux integral in any meaningful sense. The problem, it seems, is that the integrands which interest us have too much local variation for the Darboux approach to work.


text:
Q: Covariance of 1-D random process is $n\times n$!!!! I'm reading a tutorial on stochastic processes. There is an example in the tutorial as follows:

General Moving Average random process given as $X[n]=\frac{(U[n]+U[n-1])}{2}$ where $E[U[n]]=\mu$ and $var(U[n]) = {σ^2}_U$ and the
  $U[n]$'s are uncorrelated.

As you see $X[n]$ is a 1-D random variable Then the example is solved in the following way:
$[C_X]_{ij}=E[(X[i]-E[X[i]])(X[j]-E[X[j]])]\qquad i=0,1,\dots,N-1;j=0,1,\dots,N-1.$
$\begin{align}
X[n]-E[X[n]]&=\frac{1}{2}(U[n]+U[n-1])-\frac{1}{2}(\mu+\mu)\\
&=\frac{1}{2}[(U[n]-\mu)+(U[n-1]-\mu)]\\
&=\frac{1}{2}[\overline U[n]+\overline U[n-1]]
\end{align}$
$\begin{align}
[C_X]_{ij}&=\frac{1}{4}E[(\overline U[i]+\overline U[i-1])(\overline U[j]+\overline U[j-1])]\\
&=\frac{1}{4}(E[\overline U[i]\overline U[j]]+E[\overline U[i]\overline U[j-1]]+E[\overline U[i-1]\overline U[j]]+E[\overline U[i-1]\overline U[j-1]])
\end{align}$
$[C_X]_{ij}=\frac{1}{4}(\sigma^2_U\delta[j-i]+\sigma^2_U\delta[j-i-1]+\sigma^2_U\delta[j-i+1]+\sigma^2_U\delta[j-i]).$
$C_X=\begin{bmatrix}\frac{\sigma^2_U}{2}&\frac{\sigma^2_U}{2}&0&0&\dots & 0&0&0\\
\frac{\sigma^2_U}{4}&\frac{\sigma^2_U}{2}&\frac{\sigma^2_U}{4}&0&\dots &0&0&0\\
\vdots &\vdots &\vdots& \vdots&\vdots &\vdots &\vdots& \vdots\\
0&0&0&0&\cdots &\frac{\sigma^2_U}{4}&\frac{\sigma^2_U}{2}&\frac{\sigma^2_U}{4}\\
0&0&0&0&\cdots &0&\frac{\sigma^2_U}{4}&\frac{\sigma^2_U}{2}\end{bmatrix}$
So why $C_X$ is $n\times n$ inspite of $X[n]$ being 1-dimensional?

A: First, your random process $X[n], n \in \mathbb{N}$ is collection of infinitely many random variables $X[1],X[2],\ldots$; if we take finitely many of them, say, $X[1],\ldots,X[n]$ and form random vector
$$X=(X[1],\ldots,X[n])$$
this random vector is sometimes called a finite-dimensional section of random process $X[n], n \in \mathbb{N}$.
With every random vector $Y=(Y_1,\ldots,Y_n)$ we can associate its covariance matrix $C_Y=\{c_{ij}\}_{i,j \in \{1,..,n\}}$ with entries
$$c_{ij}=Cov(Y_i,Y_j)=E[(Y_i-E[Y_i])(Y_j-E[Y_j])].$$
In your tutorial, $C_X$ is covariance matrix of finite-dimensional section $X$ of random process $X[n], n \in \mathbb{N}$ introduced in the previous paragraph.
When $Y$ is not a random vector, but a proper stochastic process, in place of covariance matrix we use auto-covariance function
$$C_Y(t_1,t_2)=Cov(Y_{t_1},Y_{t_2})=E[(Y_{t_1}-E[Y_{t_1}])(Y_{t_2}-E[Y_{t_2}])]$$
Of course, when process $Y$ is WSS, auto-covariance function $C_Y(t_1,t_2)$ depends on $(t_1,t_2)$ only through the lag $h=t_2-t_1$, and we can write auto-covariance function as
$$C_Y(h)=Cov(Y_0,Y_h).$$


text:
Q: Re-using login functionality in Selenium page object model tests I am exploring the use of Selenium 2 on a web application which requires authentication before a user can use any of the application. I am planning on either JUnit 4 or TestNG (Still investigating which one to use with Grid 2). I may plan to use jbehave as well.
Does anyone have any suggestions on how I can improve the following test so I can use  successful login functionality across all my tests? I want to avoid duplicating login in the tests itself.
public class LoginPageTest {

    private LoginPage page;

    @Before
    public void openTheBrowser() {
        page = PageFactory.initElements(new FirefoxDriver(), LoginPage.class);
        page.open("http://www.site.com/Login");
    }

    @After
    public void closeTheBrowser() {
        page.close();
    }

    @Test
    public void whenTheUserEntersValidCredentialsTheUserIsLoggedIn() {
        assertThat(page.getTitle(), containsString("Login") );
    }
}

The test is simplified but it will return a page object of a successful login.
thanks

A: check case study @ http://blog.infostretch.com/?p=806 for better idea. If you are at initial level of development i would suggest you to try using QAF (formerly ISFW).

A: Your best option might be to use the LoginPageTest class as a parent class and extend each of your test classes from LoginPageTest.
That way, each test can login to the system using the parent's setup and tear down methods and do its own additional testing as well.

A: Create Libraries and call the sequence of test cases to execute one test case/scenario.
Eg:
lib.login();
lib.whenTheUserEntersValidCredentialsTheUserIsLoggedIn();
lib.logout();

for doing this take care of object creations. solution for object is use of super eg: super.login()


text:
Q: Trying to modify a show/hide script so first div opens on page load (Django project) I'm working on a blog feed and have a script that currently opens up a div and displays it's (the div's) content onclick; however, I would like the first div in the feed to open when the page loads and right now I'm struggling to figure it out. I'm a serious django and javascript/jQuery noobie, so any help that can be offered with this is greatly appreciated.
Currently everything else works. The page loads the feed, all of the divs are closed and when selected they open up.
base.html
<article   id="entry-{{ object.pk }}" {% if continue_reading %} onclick="toggleArticleActive('entry-{{ object.pk }}', true);" {% endif %}>

...blog post content

</article>

tools.js
function toggleArticleActive(article_dom_id, is_active) {
  if (is_active) { // deactivate all that are active
    $('.article-active').each(function(index, value) {
      toggleArticleActive($(this).attr('id'), false);
    });
  }

  var a = $('#' + article_dom_id);
  a.attr("class", is_active ? "article-active" : "");

  if (is_active) {
    a.find(".show-when-article-active").show(); // can animate, e.g. show('slow')
    a.find(".show-when-article-not-active").hide();

    // Load questions about this entry in the main div
    $('#div_activity').load('/f/?entry=' + article_dom_id.replace('entry-','') );
  } else {
    a.find(".show-when-article-active").hide();
    a.find(".show-when-article-not-active").show();
  }
}

A: You should just be able to show the div automatically when the .ready() event is fired.
$( document ).ready(function() {
    $("#firstdiv").show();
});

Where "#firstdiv" is the id of your first div in the list. You can also select the first div using the ":first-child" selector of your containing element:
http://api.jquery.com/first-child-selector/


text:
Q: Does this manifold have a name? EDIT: In an attempt to not let the bounty go to waste, I will consider responses that give reasonable guesses of what the involved surfaces are, WITHOUT requiring parametrizations.
While using Mathematica to alter manifolds and numerically verify the Gauss-Bonnet Theorem, I generated the figure whose pictures I've attached in this post (multiple perspectives of the same shape are provided).
Does anyone know whether it is a known manifold with a name?
I generated this surface by using $h_{x}, h_{y}, h_{z}$ below, setting $t_{2}=t=1, M=0, \phi=\pi/2$ on the interval $0 \leq k_{x} \leq 2\pi$ and $0 \leq k_{x} \leq 2\pi$:

After much reading, my biggest guess is that this is a pseudosphere glued to a duplin cyclide - however, I am having trouble knowing this for sure. I do not even know how I would go about proving this.
Note that I plotted some of the normal vectors on its surface and it appears that normal vectors in the pseudosphere-like region point INTO the surface, whereas other normal vectors point out. Perhaps this could be useful information.
Since this is a question with a bounty on it now, I should know what this 2D surface is with certainty.
For your convenience, I have a link to MATLAB and Mathematica files that have manipulable figures here: https://1drv.ms/f/s!Ak6chxAgMs9Pg_tYixvFy6MfO9531A
Here are some animations that show sections of the surface (I change parameters in a fixed frame so that you get certain perspectives inside the surface as it leaves the fixed frame).

Here are some static images (essentially screenshots from the models in the link above):


text:
Q: Remove object from the image How to remove spider from "spider web"?

there is good example in documentation center

but how to make black marker of spider?

A: You should first generate the mask, then you can apply Inpaint. Following is a demo, it can be further enhanced.
flt = ColorNegate@MorphologicalBinarize[img, {0.4, 0.9}];
Inpaint[img, flt];

A: This is a fast and quite good way to create the mask of the spider:
i = Import["http://i.stack.imgur.com/2Lz0A.jpg"];
mask = Dilation[
  DeleteSmallComponents@ ColorNegate@ DeleteSmallComponents@
    MorphologicalBinarize[i, .25],
  DiskMatrix[2]]

Then, you can use Inpaint with the generated mask:
Inpaint[i, mask]

You will have to adjust the MorphologicalBinarize threshold value to achieve good results for other images.