Q:

php - email form

rough day and I'm sure I'm missing something obvious, but could someone glance over this and explain why I'm getting a blank email?  I've broken this down as much as possible but can't seem to find the reason why its blank
<?php
$to = 'blah@blah.com';
$name = $_POST['name'] ;
$subject = "Message from: $name";
$message = $_POST['comment'] ;
$robotest = $_REQUEST['robotest'];
$body = "From: $name \r\nMessage: $message";

/*
if (preg_match($match, $from) ||
preg_match($match, $subject) ||
preg_match($match, $body)) {
die("Header injection detected.");
}
*/

if ($sent == '0') {
mail($to, $subject, $body) or die("Error Bro!!!");
$sent = 1;
}

if ($robotest) {
$error = print("You are a gutless robot.");
}

 if ($name == ' '){
print("You have not entered a name, please go back and try again");
 } else {
$send = mail($to, $subject, $body);
print("Thank you for contacting us. We will be in touch with you very soon.");
 }
 ?>

html:
            <form style="margin-left: 10%;" method="post" action="coming-soon/email.php" enctype="text/plain">

                <input id="fName" name="name" type="text"  placeholder="Name (required)">

                    If you're human leave this blank:
                    <input name="robotest" type="text" id="robotest" class="robotest" />

                <textarea id="fComment" name="comment" style="height: inherit; margin: 0 40% 1% 0;" rows="10" cols="50" placeholder="Place your Message here...."></textarea>
                <input type="submit" value="Send">
                <input type="reset" value="Reset">
            </form>

A:

Remove and it should work.  Have a look here as well method="post" enctype="text/plain" are not compatible?
 enctype="text/plain"


Q:

How to use stored procedure in Linq-to-Entities

I am working with Entity Framework
I want to know how I can use stored procedures in Linq-to-Entities. My stored procedure is called SelectEmployee and table name is Employee
For this I added code like this
 databaseentity entities = new databaseentity();
 var selectdata = entities.ExecuteStoreQuery<Employee>("SelectEmployee").ToList();

but it is not supported ExecuteStoreQuery
So please guide me how can I use stored procedures in Linq-to-Entities

A:

In simple steps:

Add your stored procedure to the edmx.
You will find that sp in Model Browser
Right click on stored procedure and say Add Function Import
use it by entities.SelectEmployee()


Q:

Can individual feature properties be retrieved from the CartoDB.js API?

I'm building an application that uses CartoDB to show users how a proposed redistricting plan would affect them. The user enters an address and that fires a ST_Intersects query to CartoDB, the result of which is always two polygons: one is the old ward, one is the proposed ward. Type "40 Bradley Street, Burlington, VT" into the search box to see how this works.

I'd like to push answers to the indicated questions (e.g. "Where will my polling place be?") as well. However, this requires the ability to retrieve individual attribute values from the query results, and I can't figure out how to do this. Here is the structure I'm trying to use after running cartodb.createLayer();
var 1990ward = cartodbproperty.ward[1];
    var 2010ward = cartodbproperty.ward[0];

    if (1990ward == 2010ward) {
        $('#wardchange').text("No. You will remain in ward " + 2010ward + " under the proposed plan.");
    }
    else {
        $('#wardchange').text("Yes. You are currently in ward " + 1990ward + ", but you would be in ward " + 2010ward + " under the proposed plan.");
    }

    $('#distchange').text("The " + cartodbproperty.district + " District");
    $('#pollchange').text(cartodbproperty.pollingplace);

The "cartodbproperty" variables are dummies because I can't figure out how I would use the cartodb.js API to select the "ward" attribute value of the query-result feature where "year" = 2010.
I believe I could pull this off with a parallel call to the SQL API - which could then be parsed as JSON - but that seems horribly inefficient. How can I get this data from the CartoDB.js API?
Thanks as always for the great toolset!

A:

If I understand your question correctly, I think you are missing a few important bits. Right now you are doing,
cartodb.createLayer(map, {
  user_name: 'geosprocket',
  type: 'cartodb',
  sublayers: [{
    sql: "somesql",
    cartocss: "somestyle"
  }]
})

but you also need to tell it you want interaction,
cartodb.createLayer(map, {
  user_name: 'geosprocket',
  type: 'cartodb',
  sublayers: [{
    sql: "somesql",
    cartocss: "somestyle",
    interactivity: 'cartodb_id, column_2, column_3'
  }]
})

Then, in your function, you can get at that data with the feature events. You can wire them up after adding your layers to the map, e.g.
.done(function(layer){
  var sublayer = layer.getSubLayer(0);
  sublayer.bind('featureOver', function(e, latlon, pxPos, data, layer) {
     console.log(data.cartodb_id);
  });
});


Q:

Access to localhost from other machine - Angular

Background
Most of developers often use two or more desktops and laptops when they working on the project. Same as me, and now I'm working on Angular project.
GOAL
I wanna access to the localhost:4200 from another computer that I'm using, so that I can check the UI updates without switching windows on one computer.
I took some research and tried with below angular-cli command.
ng serve --host=MyLocalIP
ng serve --host 0.0.0.0

But no luck until yet. Is there a better way to achieve this one?

A:

Using ng serve --host 0.0.0.0 command has solved my problem.
Type 192.168.x.x:4200 to get access the app from another machine.

A:

Two options are there
ng serve --host 0.0.0.0

To check, if this is not working, 1st try to hit from same computer where you rung ng serve, to get to know if you can access through firewall
ng serve --host 192.168.X.X

192.168.X.X is the ip address of my pc(you can use ipconfig(windows), ifconfig(linux) to see your ip)
After that you can access 192.1668.X.X:4200 instead of localhost:4200
Nothing related :- Even if you change some code and server refresh to show updated code, it will refresh in other machine too
If you can not able to access 192.168.X.X:4200. You may be in a network where firewall protection is blocking. SO, connect to your personal network and check


Q:

AWS: Security Group to allow access internet-facing Load balancer to be accessed from private instances

My question is an extended version of this.

In my case the security group has to restrict the access to Load Balancer 1. It has to have some white listed IPs. So, which IPs can I put here that can allow access of Load Balancer 1 from Auto Scaling Group 2 private instances?
I have tried putting the Elastic IP of NAT Gateway as a whitelisted IP and it works. I want to understand why it is absolutely necessary to put this IP in Security Group to access the internet-facing ALB from the private subnet instance of the same VPC.

A:

I have tried putting the Elastic IP of NAT Gateway as a whitelisted IP
  and it works. I want to understand why it is absolutely necessary to
  put this IP in Security Group to access the internet-facing ALB from
  the private subnet instance of the same VPC.

Because the instances in the private subnet look up the DNS of the public load balancer, resolve it to its public internet IP, and then attempt to connect to that IP, which gets routed through the NAT gateway.
As far as I know there is no way to have a public Elastic Load Balancer that can also be resolved to a private IP inside your VPC. So you will have to go through the NAT gateway to access the public load balancer from inside your private IP.
An alternative setup would be to create a third load balancer, that is private, that also points to the instances in Auto-Scale Group #1, and have your private subnet instances communicate with that load balancer.
If you go with the third load balancer approach, you would create a new target group, assign that group as to your existing auto-scaling group, and point the new load balancer to the new target group. The key point is that a target group can only be used by one Application Load Balancer, but instances can belong to multiple target groups and auto-scaling groups can have multiple target groups.


Q:

Express in terms of $r$, $\theta$ the following equations

Book: Introduction to Complex Analysis, H. A. Priestley
This may be stupid question, but this exercise doesnt make much sense to me
Exercise 1.3.(i)-(v): Express in terms of $r$, $\theta$ the following equations, where $z=re^{i\theta}$:
(i) $|z^2| = 4$
(ii) $|z^2 - 1| = 1$
(iii) $ arg(2z) = \frac{2\pi}{3} $
Now, my attempt doesnt make sense anyway, $\theta$ or $r$ vanishes or.... what even are the solutions? Help <3

A:

For the first one, your method seems unnecessarily complicated. Much simpler to go $|z^2| = 4 \implies |z|^2 = 4 \implies r^2 = 4 \implies r = 2$. Note that the magnitude is non-negative, so you should not have the negative root.
For the second one, you omitted a couple steps. Let's look at the manipulation of the LHS: $|z^2 - 1| = \sqrt{|(z^2 - 1)\overline{(z^2-1)}|} = \sqrt{|(z^2 - 1)(\overline{z^2}-1)|}$ (justified by $\overline{w - x} = \overline w - \overline x$), following which you squared both LHS and RHS to get your equation.
You can simplify your final answer to $r = \sqrt 2 |\cos 2\theta|$ (that's an absolute value sign on the RHS), but it's OK as you left it.
The last one is very easy. The argument of a complex number is not affected by a real multiplier, so $arg(2z) = arg(z)$. You can immediately conclude $\theta = \frac{2\pi}{3}$. $r$ doesn't enter into the expression at all.
(Please note the correction in the final one, I made a major error initially).


Q:

C- Run-length encoding doesn't work on large file, worked on smaller file

I have a problem, when I use this on a 41 kb file it compressed (Although because it uses run-length encoding it always seems to double the size of the file) and decompresses properly. However when I tried to use it on a 16,173 kb file and I decompressed it, it didn't open and the file size was 16,171 kb....so it decompressed it but it didn't return back to it's original form....something screwed up....Has me baffled, I just can't seem to figure out what I am doing wrong....
The method used is run-length encoding, it replaces every byte with a count followed by the byte.
Before:
46 6F 6F 20 62 61 72 21 21 21 20 20 20 20 20
After:
01 46 02 6F 01 20 01 62 01 61 01 72 03 21 05 20
Here is my code:
    void compress_file(FILE *fp_in, FILE *fp_out)
    {
        int count, ch, ch2;

        ch = getc(fp_in);
        for (count = 0; ch2 != EOF; count = 0) {
            // if next byte is the same increase count and test again
            do {
                count++;           // set binary count
                ch2 = getc(fp_in); // set next variable for comparison
            } while (ch2 != EOF && ch2 == ch);
            // write bytes into new file
            putc(count, fp_out);
            putc(ch, fp_out);
            ch = ch2;
        }
        fclose(fp_in);
        fclose(fp_out);
        fprintf(stderr, "File Compressed\n");
    }

    void uncompress_file(FILE *fp_in, FILE *fp_out)
    {
        int count, ch, ch2;

        for (count = 0; ch2 != EOF; count = 0) {
            ch = getc(fp_in);   // grab first byte
            ch2 = getc(fp_in);  // grab second byte
            // write the bytes
            do {
                putc(ch2, fp_out);
                count++;
            } while (count < ch);
        }
        fclose(fp_in);
        fclose(fp_out);
        fprintf(stderr, "File Decompressed\n");
    }

A:

You miss to check your run length count for char overflow, so this will go wrong if you have more than 255 identical characters in your file in sequence.

A:

Here is the working source code:
    // Chapter 22 Programming Project #7

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>

    void compress_file(FILE *fp_in, FILE *fp_out);
    void uncompress_file(FILE *fp_in, FILE *fp_out);

    int main(void)
    {
        FILE *fp_in, *fp_out;
        char nm_in[FILENAME_MAX], nm_out[FILENAME_MAX];
        int chk;

        for (;;) {
            printf(" ----------------------------------------- \n");
            printf("|             1 - Compress                |\n");
            printf("|             2 - Decompress              |\n");
            printf("|             3 - Exit                    |\n");
            printf(" ----------------------------------------- \n");
            do {
                printf("Enter a command: ");
                scanf(" %d", &chk);
            } while (isalpha(chk));

            if (chk == 3)
                exit(EXIT_SUCCESS);

            printf("Enter input file name: ");
            scanf(" %s", nm_in);
            printf("Enter output file name: ");
            scanf(" %s", nm_out);
            // Open file to read from
            while ((fp_in = fopen(nm_in, "rb")) == NULL) {
                fprintf(stderr, "Can't open \"%s\"\n", nm_in);
                printf("Enter input file name: ");
                scanf(" %s", nm_in);
            }
            // Open file to write to
            while ((fp_out = fopen(nm_out, "wb")) == NULL) {
                fprintf(stderr, "Can't create \"%s\"\n", nm_out);
                printf("Enter output file name: ");
                scanf(" %s", nm_out);
            }
            switch(chk) {
                case 1: compress_file(fp_in, fp_out); break;
                case 2: uncompress_file(fp_in, fp_out); break;
            }
            putchar('\n');
        }

        return 0;
    }

    void compress_file(FILE *fp_in, FILE *fp_out)
    {
        int count, ch, ch2, chk;

        ch = getc(fp_in);
        ch2 = ch;
        while (ch2 != EOF) {
            // if next byte is the same increase count and test
            for (count = 0; ch2 == ch && count < 255; count++) {
                ch2 = getc(fp_in); // set next variable for comparison
            }
            // write bytes into new file
            putc(count, fp_out);
            putc(ch, fp_out);
            ch = ch2;
        }
        fclose(fp_in);
        fclose(fp_out);
        fprintf(stderr, "File Compressed\n");
    }

    void uncompress_file(FILE *fp_in, FILE *fp_out)
    {
        int count, ch, ch2;

        for (count = 0; ch2 != EOF; count = 0) {
            ch = getc(fp_in);   // grab first byte
            ch2 = getc(fp_in);  // grab second byte
            // write the bytes
            do {
                putc(ch2, fp_out);
                count++;
            } while (count < ch);
        }
        fclose(fp_in);
        fclose(fp_out);
        fprintf(stderr, "File Decompressed\n");
    }


Q:

Accessing method parameters from asynchronously running lambda

What I know: only final or effectively final local variables are accessible from inside a lambda. static variables are also accessible and can be modified as well.
What I do not know: why this code does not throw an exception?
public static String sampleFunction(String param1, int param2) {
    new Thread(() -> {
        try { Thread.sleep(100000); } catch (InterruptedException e) { }
        // accessing method parameter here...
        String _param1 = param1;
        System.out.println(_param1);
    }).start();

   return "";
}

public static void Main(String[] arguments) {
    sampleFunction("to print", 9);
    System.out.println("function returned");
}

So having that in mind the parameters are released on return
which happens before trying to access them from inside the asynchronously running lambda expression, why does not it throw Exception? I tested the code, compiled and interestingly the "returned" message was printed earlier than "to print".
Which means that I could access the method parameters after the method returned.

A:

The code would not throw an Exception as param1 is effectively final. Java Lambdas are similar to closures.


Q:

Why is $O_K\otimes \mathbb{Z}_p\cong \oplus_{\mathfrak{p}|p}O_{K,\mathfrak{p}}$?

In my old number theory notebook this is stated as a fact. However, I ran into problems when I tried to prove it. First let me state the (supposed) theorem accurately:
Theorem (?)
Let $K$ be a number field with ring of integers $O_K$. Let $p$ be a prime of $\mathbb{Z}$. Then $O_K\otimes \mathbb{Z}_p\cong \oplus_{\mathfrak{p}|p}O_{K,\mathfrak{p}}$, where $\mathfrak{p}$ runs over those primes of $O_K$ that lie over $p$, and where $O_{K,\mathfrak{p}}$ is the formal local ring of $O_K$ at $\mathfrak{p}$ (i.e., $\varprojlim O_K/\mathfrak{p}^n$).
Attempt
The way I was thinking of proving this is through the Chinese Remainder Theorem. The following is true for every natural number $n$:
$$O_K\otimes \mathbb{Z}/p^n\mathbb{Z}\cong O_K/p^nO_K\cong O_K/\mathfrak{p}_1^{ne_1}\cdots \mathfrak{p}_m^{ne_m}\cong O_K/\mathfrak{p}_1^{ne_1}\oplus...\oplus O_K/\mathfrak{p}_m^{ne_m}.$$
where $pO_K=\mathfrak{p}_1^{e_1}\cdots \mathfrak{p}_m^{e_m}$.
The next natural step is to take inverse limits of both sides with respect to n. As inverse limits commute with direct sums (as both are limits), $\varprojlim O_K/\mathfrak{p}_1^{ne_1}\oplus...\oplus O_K/\mathfrak{p}_m^{ne_m}\cong O_{K,\mathfrak{p}_1}\oplus...\oplus O_{K,\mathfrak{p}_m}$.
This is where the wheels come off the argument: inverse limits don't generally commute with tensor products. This is because inverse limits are categorical limits, whereas tensor products are categorical colimits (indeed they are the coproduct of the category of $\mathbb{Z}$-algebras). So there is no reason, a priori, that $\varprojlim O_K\otimes \mathbb{Z}/p^n\mathbb{Z}$ would be isomorphic to $O_K\otimes \mathbb{Z}_p$.
So this leads me to the
Question
Why is the theorem true? (if it even is.)

A:

As noticed wxu in the comments, $O_K$ is finite free over $\mathbb Z$. Write $O_K=\oplus_{1\le i\le d} e_i\mathbb Z$. Then we have
$$ O_K\otimes_\mathbb Z \mathbb Z/p^n \mathbb Z =\oplus_{1\le i\le d} e_i(\mathbb Z/p^n\mathbb Z).$$
Passing to the inverse limit, we get
$$\varprojlim_n O_K\otimes \mathbb Z/p^n \mathbb Z =\oplus_{1\le i\le d} e_i\mathbb Z_p=O_K\otimes_\mathbb Z \mathbb Z_p.$$

A:

Your problem can be solved under more general conditions.
Let $A$ be a Noetherian commutative ring.
Let $I$ be an ideal of $A$.
Let $M$ be a finitely generated $A$-module.
Let $A_I$ = $\varprojlim A/I^n$.
Then $M\otimes A_I$ $\cong$ $\varprojlim M\otimes (A/I^n)$.
The proof can be found, for example, in Matsumura's "Commutative ring theory", Theorem 8.7 in page 60.


Q:

How can i use jsx instead of js extension in react boilerplate?

I just want to add jsx Page in the https://github.com/react-boilerplate/react-boilerplate/
Below is what i want to add Password forgot page jsx file content.
import React from 'react';
import { connect } from 'react-redux';
import {Link, Route} from 'react-router-dom';

class PwdForgotPage extends React.Component {
  render() {
    return (

        Password forgot.
        <button className="btn btn-link">Back</button>

    );
  }
}

function mapStateToProps(state) {
  const { registering } = state.registration;
  return {
    registering,
  };
}

const connectedPwdForgotPage = connect(mapStateToProps)(PwdForgotPage);
export { connectedPwdForgotPage as PwdForgotPage };

But if i use jsx extension, failed to run as below.
Module parse failed: C:\.....\frontend\app\containers\PwdForgotPage\PwdForgotPage.jsx Unexpected token (8:6)
You may need an appropriate loader to handle this file type.
|   render() {
|     return (
|

|         Password forgot.
|         <button className="btn btn-link">Back</button>

If i use js extension, it works.
How do i change the config in the boilerplate for jsx extension support?

A:

You need to add jsx extension to the rule  in webpack config that enables babel babel-loader.
{
    test: /\.jsx?$/, // notice optional x?
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      options: options.babelQuery,
    },
  },

https://github.com/react-boilerplate/react-boilerplate/blob/master/internals/webpack/webpack.base.babel.js#L23
Or subjectively more readable /\.(js|jsx)$/


Q:

escoger valor random de un array

tengo un array con 807 valores y deseo poder escoger uno de ellos al azar el problema es que solo puedo escoger 10 con el método de random(), de que otra manera lo puedo hacer?

let arrayNumeros = []

function numbers1() {
    for (let i = 1; i <= 807; i++) {
        arrayNumeros.push(i)
    }
}
numbers1()

A:

Puedes generar un numero aleatorio con un mínimo de 0 y máximo el tamaño de tu array para nunca estar fuera de rango. Una vez tengamos el numero random, lo utilizaremos como indice para acceder al array con todos los valores.
var numbers = []

function llenar() {
    for (let i = 1; i <= 807; i++) {
        numbers.push(i)
    }
}
llenar()

function random() {
 let number = Math.floor(Math.random()*numbers.length);
 return number
}

let position = random()
let number = numbers[position]
console.log(`Numero random: ${position}, elemento correspondiente: ${number}`)

Recuerda que cuando trabajamos con un array, los indices comienzan en 0

A:

Lo que necesitas es un número random entre 0 y 806 (los indices de los arrays comienzan con 0 y no con  1), a partir de un número (pseudo) random entre 0 y 1 pero sin incluír el 1 [0,1) que nos provee Math.random().
Entonces, lo mejor que se puede hacer es multiplicar ambos números, ya que como el random es menor que 1, el resultado será siempre menor a 806 e igual o mayor a 0. Ahora bien, el 806 nunca saldrá porque nunca se dará el caso 1*806, entonces al límite superior hay que sumarle uno. Dicho esto, la forma sería entonces:
Math.random()*807
como eso da un número decimal, se le puede hacer Math.floor que nos dá el menor número entero, lo que nos permite incluír el 0 entre los resultados, además de interpretar el 806.999999 como 806, y no como 807. Entonces, si quieres encontrar un número entre 0 y 806 (807 elementos) la forma sería:
Math.floor(Math.random()*807)


Q:

Android change google map tile with custom tiles

Is it possible to change google map API v3 standart map to my own custom map coming from url? I know that OSMdroid provide it but i want work with google map API. Is it possible?

A:

it is indeed possible by using WMS services (if you don't know what they are, please google it).
Here is some code you can use:
The WMSTile provider is used by GoogleMapsAPI to set the map provider:
public abstract class WMSTileProvider extends UrlTileProvider {

// Web Mercator n/w corner of the map.
private static final double[] TILE_ORIGIN = { -20037508.34789244, 20037508.34789244 };
// array indexes for that data
private static final int ORIG_X = 0;
private static final int ORIG_Y = 1; // "

// Size of square world map in meters, using WebMerc projection.
private static final double MAP_SIZE = 20037508.34789244 * 2;

// array indexes for array to hold bounding boxes.
protected static final int MINX = 0;
protected static final int MAXX = 1;
protected static final int MINY = 2;
protected static final int MAXY = 3;

// cql filters
private String cqlString = "";

// Construct with tile size in pixels, normally 256, see parent class.
public WMSTileProvider(int x, int y) {
    super(x, y);
}

@SuppressWarnings("deprecation")
protected String getCql() {
    try {
        return URLEncoder.encode(cqlString, Charset.defaultCharset().name());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return URLEncoder.encode(cqlString);
    }
}

public void setCql(String c) {
    cqlString = c;
}

// Return a web Mercator bounding box given tile x/y indexes and a zoom
// level.
protected double[] getBoundingBox(int x, int y, int zoom) {
    double tileSize = MAP_SIZE / Math.pow(2, zoom);
    double minx = TILE_ORIGIN[ORIG_X] + x * tileSize;
    double maxx = TILE_ORIGIN[ORIG_X] + (x + 1) * tileSize;
    double miny = TILE_ORIGIN[ORIG_Y] - (y + 1) * tileSize;
    double maxy = TILE_ORIGIN[ORIG_Y] - y * tileSize;

    double[] bbox = new double[4];
    bbox[MINX] = minx;
    bbox[MINY] = miny;
    bbox[MAXX] = maxx;
    bbox[MAXY] = maxy;

    return bbox;
}
}

And you can instantiate a custom one from your URL in such a way:
public static WMSTileProvider getWMSTileProviderByName(String layerName) {
        final String OSGEO_WMS = "http://YOURWMSSERVERURL?"
                + "LAYERS=" + layerName
                + "&FORMAT=image/png8&"
                + "PROJECTION=EPSG:3857&"
                + "TILEORIGIN=lon=-20037508.34,lat=-20037508.34&"
                + "TILESIZE=w=256,h=256"
                + "&MAXEXTENT=-20037508.34,-20037508.34,20037508.34,20037508.34&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG:3857"
                + "&BBOX=%f,%f,%f,%f&WIDTH=256&HEIGHT=256";

        return new WMSTileProvider(256, 256) {

            @Override
            public synchronized URL getTileUrl(int x, int y, int zoom) {
                final double[] bbox = getBoundingBox(x, y, zoom);
                String s = String.format(Locale.US, OSGEO_WMS, bbox[MINX], bbox[MINY], bbox[MAXX], bbox[MAXY]);
                try {
                    return new URL(s);
                } catch (MalformedURLException e) {
                    throw new AssertionError(e);
                }
            }
        };
    }

Add to your map:
TileProvider tileProvider = getWMSTileProviderByName("MYLAYERNAME");
TileOverlay tileOverlay = myMap.addTileOverlay(new TileOverlayOptions()
    .tileProvider(tileProvider));

You should also set the map type to MAP_NONE when using a custom tile provider (if it is not transparent), so you avoid to load gmaps tiles that are hidden behind your custom map.


Q:

Alkaline cells vs. LED flashlight

I have (had, actually) an El Cheapo pocket LED flashlight powered by 3 AAA cells. It was shipped with very low quality "salt" cells (regular, low weight - someone please suggest a proper English name for them). I tried to beef-up this flashlight by installing powerful Varta alkaline cells but flashlight blinked couple of times and gone dead. Now I have slight memories about what I read somewhere what LED drivers does not allow alkaline (higher current) feeding. Are my memories correct? Can I actually install alkaline cells to LED lighting devices? (Yes, No or Sometimes depending on driver)

A:

by installing powerful Varta alkaline cells but flashlight blinked
  couple of times and gone dead.

Yep. You definitely fried it there. I once had a cheap keychain flashlight that I didn't want so I hooked it up to 5V and it had exactly those symptoms. When I hooked it up again, it didn't work. No big deal, I just wanted to see what would happen, and I didn't really have a use for it.
However, if the person who designed that flashlight has greater than 0 electronic knowledge, they would add a resistor to limit the current. The only reason a resistor wouldn't limit the current correctly is if you had more voltage, which both more voltage and current allowed is a huge problem. Current is supplied on demand, but the LED sucks up as much as it can, but the resistor should limit it no matter the amount of current that can be supplied, unless the voltage is increased.

Edit: One thing I forgot: Quote from jippie's comment:

Alkaline batteries probably have much lower internal impedance than
  the original ones. The designer used the battery's internal impedance
  as series resistor. Done quite a lot in el Cheapo stuff.

Batteries have a internal resistance, and that's why the designer used the original ones to save on money. It's a smart trick, but you should have put a resistor in. How you would know this before, I don't know. But, if you have another one, you would just need to add a quick one from the store. At my RadioShack, I can get a five pack of 1/8W, 1/4W, or 1/2W for $1.49. (Yes they are all the same price... I have been wondering why anybody would want the more flimsy wires and a smaller piece that has less capacity but is the same price as the others.) But... you don't know how much current the LED can handle, unless you measured the current with the old batteries and used Ohm's Law.
If you have another and a multimeter, you can fix it on the other, but this one is toast. Gone. Bad. Broken. Fried.

A:

Your LED flashlight depended on the internal resistance of the batteries to limit current through the LEDs. With the original batteries, the internal impedance was high enough to limit LED current to safe levels.
This is common practice in many low price, non critical electronic devices. The saving is not just in the cost of the resistor, but also in incremental cost of assembly, however small. Anyone familiar with the so-called design of cheap consumer electronics will know how common this practice is.
Alkaline batteries typically have lower internal resistance i.e. can support much higher current than the cheaper zinc-carbon batteries. Without any other form of current limiting, the ”improved” capability of alkaline batteries has caused the death of the LED.


Q:

Oracle11g error: table or view does not exist when using INSERT INTO

After creating a table I would like to insert data but I've encountered an error.
Creating the table:
CREATE TABLE "Buildings"(
  "idBuilding" Integer NOT NULL,
  "buildingName" Varchar2(30 ) NOT NULL,
  "city" Varchar2(30 ) NOT NULL,
  "street" Varchar2(30 ) NOT NULL,
)

and then
INSERT INTO Buildings VALUES(1, 'Empire State', 'New York', 'West');

and the error is
SQL Error: 00942. 00000 -  "table or view does not exist"

I know that there are a lot of similar questions here but I couldn't find any solution. I've tried using GRANT and it didn't help. I'm using Oracle SQL Developer.

A:

Since you created the table with quotes and some lowercase letter, you have to use quotes in your insert statement as well. "Buildings" instead of Buildungs.
Identifiers are case sensitive in Oracle, but identifiers without quotes are automatically turned to uppercase. Therefore, "ABC"=ABC=Abc=abc


Q:

using both column and row name in apply

I'm having something like this:
#data.table
#      a b
#aland 1 2
#bland 3 4

freq_all = read.table(file='data.table', header=T,stringsAsFactors = FALSE)
country_names = rownames(freq_all)
blood_types = colnames(freq_all)

func <- function(country,type) {paste(country, type)}

newfr <- freq_all
for (country in country_names){
    for (type in blood_types){
        newfr[country, type] <- func(country, type)
    }
}

And I'm wondering if I can use the apply() function or something similar here.

A:

We can use outer
freq1 <- freq_all
freq1[] <- outer(rownames(freq_all), colnames(freq_all), FUN= paste)
freq1
#           a       b
#aland aland a aland b
#bland bland a bland b

identical(freq1, newfr)
#[1] TRUE

data
freq_all <- structure(list(a = c(1L, 3L), b = c(2L, 4L)), .Names = c("a",
  "b"), class = "data.frame", row.names = c("aland", "bland"))


Q:

What town is in the Samsung Galaxy S default wallpaper?

This is the default wallpaper of Samsung Galaxy S smartphone, does anyone know where this place is?

A:

It is Annecy in France.
And you can see on the picture le Palais de l'Isle.

A:

Yes it's Annecy and its Old Town. This building is "Le Palais de l'Ile". It used to be a jail and now it's a place for exhibitions.
See more : http://goo.gl/hUoCJm


Q:

How to set alignment for UIScrollView in ios

i am creating an application, where i am using UIScrollView for displaying the number of available colors of each product. I am getting number of available colors at run time, so i have used for loop and displaying on my scroll view. Its working fine, but the problem if i am getting only one available color then my output is coming as below screen :

But the output should be as below screen :

It seems like i need to do kind of center alignment for my UIScrollView, so every available color will suppose to display from center. here is my code :
UIScrollView *availableColorScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
availableColorScrollView.backgroundColor = [UIColor clearColor];
availableColorScrollView.showsHorizontalScrollIndicator = YES;
availableColorScrollView.showsVerticalScrollIndicator=NO;
availableColorScrollView.pagingEnabled = YES;

for (int i = 0; i < arrayAvlbleColors.count; i++) {
    CGRect frame;
    frame.origin.x = 23 * i;
    frame.origin.y = 0;
    frame.size = availableColorScrollView.frame.size;
    UIView *subview = [[UIView alloc] initWithFrame:frame];

    UILabel *label = [[UILabel alloc] init];
    [label setFrame:CGRectMake(15, 14, 16, 16)];
    [label.layer setCornerRadius:8];

    NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
    strColorCode = [strColorCode substringFromIndex:1];
    [label setBackgroundColor:[self colorWithHexString:strColorCode]];
    [subview addSubview:label];
    [availableColorScrollView addSubview:subview];
}

 [self.view addSubview:availableColorScrollView];

availableColorScrollView.contentSize = CGSizeMake(24 * arrayAvlbleColors.count, availableColorScrollView.frame.size.height);

Please suggest me to achieve my output, Thanks!

A:

this is the simple answer but working fine if u taken any Mainview or subview or else,
set the frame size/2 for height and width it automatically set it into center of the  subview.
here i used static color , customize urself
just change your line this
 NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
strColorCode = [strColorCode substringFromIndex:1];
[label setBackgroundColor:[self colorWithHexString:strColorCode]];
[subview addSubview:label];
[availableColorScrollView addSubview:subview];

into
    NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
     strColorCode = [strColorCode substringFromIndex:1];
    [label setBackgroundColor:[self colorWithHexString:strColorCode]];

    //use any one

    //option no 1:

    //[label setCenter:subview.center];

     //option no 2:

    [ label setCenter:CGPointMake(subview.frame.size.width / 2, subview.frame.size.height / 2)];

    [subview addSubview:label];
    [availableColorScrollView addSubview:subview];

final out put is


Q:

Asp.net: Can a delegate ("Action") be serialized into control state?

I am implementing a user control that has a method that takes an Action delegate as a parm.
Attempting to store the delegate in Control State yields a serialization error. Is it even possible to serialize a delegate into Control State?
BP

A:

Not easily - and it could open the door for potential problems.
It is theoretically possible to use reflection to determine which method of an object the delegate is invoking, and write a custom serialization process for it. Upon deserialization you would once again need to write logic to convert the information into a delegate reference.
The problem is that in the general case, discovering the object at runtime that you need to re-generate the delegate for is not always possible. If the delegate refers to a lambda or anonymous method that complicates things even more because their may be closures involved.
You are probably better off either:

Not preserving the Action delegate between requests and having the ASP.NET code re-attach the delegate on postback. This is the least risky option IMHO.
Storing the delegate reference in session state and reattach it to the deserialized object on postback. This option is risky for two reasons:
a) holding on to object references indefinitely in memory if the end user never posts back, or you forget to clear the object from server state.
b) if the delegate references page elements (controls, etc) you may run
into subtle bugs because the delegate will operate against the objects from the previous request, and not the new request.


Q:

Корректно ли считать shell языком по умолчанию для меток [linux], [unix]?

Множество вопросов и ответов по linux, unix и прочим *nix-системам включают в себя фрагменты скриптов на shell и производных от него языках. Но соответствующая метка ставится не всегда.
Стоит ли выставить lang-sh как язык по умолчанию для меток *nix-ОС? Плюс в том, что мы получим более адекватную подсветку синтаксиса в вопросах. Потенциальный минус — неверная подсветка, когда используются метки с разными языками. Хотя пример вопроса по c & linux показывает, что используется язык от более популярной метки и подстветка синтаксиса адекватна.
Картинка кликабельна.

A:

Я прошвырнулся по вопросам, и у меня впечатление, что у вопросов, которые касаются Linux, но не касаются shell-языков, содержат в блоках кода скорее фрагменты логов и конфиги, которые в подобной подсветке не нуждаются.
Если уж в вопросе речь о шелл-скриптах, лучше добавить к нему метку shell, bash, sh, или что там подходит лучше. Правильные метки у вопросов это важно.


Q:

TSQL for XML Path maxOccurs

I having issues trying to create results as shown below.
Any help would be greatly appreciated.
Required XML output
<Wartung>
 <Wartungsseite>
  <Wartungsdetails>
   <Vertragsnummer>111111</Vertragsnummer>
   <Kunde>bla1</Kunde>
   <Betrag>123.00</Betrag>
  </Wartungsdetails>
  <Wartungsdetails>
   <Vertragsnummer>222222</Vertragsnummer>
   <Kunde>bla2</Kunde>
   <Betrag>60.00</Betrag>
  </Wartungsdetails>
  <Wartungsdetails>
   <Vertragsnummer>3333333</Vertragsnummer>
   <Kunde>bla3</Kunde>
   <Betrag>14.00</Betrag>
  </Wartungsdetails>
</Wartungsseite>
<Wartungsseite>
  <Wartungsdetails>
   <Vertragsnummer>4444</Vertragsnummer>
   <Kunde>bla4</Kunde>
   <Betrag>123.00</Betrag>
</Wartungsdetails>
  <Wartungsdetails>
   <Vertragsnummer>5555</Vertragsnummer>
   <Kunde>bla5</Kunde>
   <Betrag>60.00</Betrag>
  </Wartungsdetails>
  <Wartungsdetails>
   <Vertragsnummer>66666</Vertragsnummer>
   <Kunde>bla6</Kunde>
   <Betrag>14.00</Betrag>
  </Wartungsdetails>
 </Wartungsseite>
</Wartung>

Actual XML output from my SQL
 <Wartung>
<Wartungsseite>
 <Wartungsdetails>
  <Vertragsnummer>3333</Vertragsnummer>
  <Kunde>bla3</Kunde>
  <Betrag>123.00</Betrag>
</Wartungsdetails>
<Wartungsdetails>
  <Vertragsnummer>111</Vertragsnummer>
  <Kunde>bla1</Kunde>
  <Betrag>60.00</Betrag>
</Wartungsdetails>
<Wartungsdetails>
  <Vertragsnummer>2222</Vertragsnummer>
  <Kunde>bla2</Kunde>
  <Betrag>14.00</Betrag>
 </Wartungsdetails>
</Wartungsseite>
  </Wartung>

The SQL generating this is
SELECT
(
    SELECT
        gutschrift.VertragNr                                    AS Vertragsnummer,
        gutschrift.PartnerName1 + ' ' + gutschrift.PartnerName2 AS Kunde,
        gutschrift.NettoBetrag                                  AS Betrag
    FROM
        Transfer.TB_LE148                    AS gutschrift
        LEFT JOIN
            MmvFibu.TB_Rechnungsausgangsbuch AS rbuch
                ON rbuch.FK_KaeuferKontakt = gutschrift.WartHaendler_PK_ID
    WHERE
        rbuch.PK_ID = 1054401
    FOR XML PATH('Wartungsdetails'), ROOT('Wartungsseite'), TYPE
)
 FOR XML PATH('Wartung'), TYPE;

Problem
The maximum number of child items in the "Wartungsseite" is 3. Are there any more items available for "Wartungsdetails". Then create a new item "Wartungsseite".

A:

Try it like this:
DECLARE @mockTable TABLE(ID INT IDENTITY, SomeValue VARCHAR(100));
INSERT INTO @mockTable VALUES('val1'),('val2'),('val3'),('val4'),('val5'),('val6'),('val7');

WITH GroupOfThree AS
(
    SELECT (ROW_NUMBER() OVER(ORDER BY ID)-1) / 3 AS GroupCode
          ,*
    FROM @mockTable
)
SELECT (
        SELECT ID, SomeValue
        FROM GroupOfThree As innerSource
        WHERE outerSource.GroupCode=innerSource.GroupCode
        ORDER BY innerSource.ID
        FOR XML PATH('Wartungsdetails'),TYPE
       )
FROM GroupOfThree AS outerSource
GROUP BY outerSource.GroupCode
FOR XML PATH('Wartungsseite'), ROOT ('Wartung');

The result
<Wartung>
  <Wartungsseite>
    <Wartungsdetails>
      <ID>1</ID>
      <SomeValue>val1</SomeValue>
    </Wartungsdetails>
    <Wartungsdetails>
      <ID>2</ID>
      <SomeValue>val2</SomeValue>
    </Wartungsdetails>
    <Wartungsdetails>
      <ID>3</ID>
      <SomeValue>val3</SomeValue>
    </Wartungsdetails>
  </Wartungsseite>
  <Wartungsseite>
    <Wartungsdetails>
      <ID>4</ID>
      <SomeValue>val4</SomeValue>
    </Wartungsdetails>
    <Wartungsdetails>
      <ID>5</ID>
      <SomeValue>val5</SomeValue>
    </Wartungsdetails>
    <Wartungsdetails>
      <ID>6</ID>
      <SomeValue>val6</SomeValue>
    </Wartungsdetails>
  </Wartungsseite>
  <Wartungsseite>
    <Wartungsdetails>
      <ID>7</ID>
      <SomeValue>val7</SomeValue>
    </Wartungsdetails>
  </Wartungsseite>
</Wartung>

The trick is to use ROW_NUMBER() together with the integer division (down-rounding to the lower integer).


Q:

What are the best ways to monitor performance and maintain performance statistics of python code?

I'm working on a python multithreaded daemon that will be processing data through a variety of APIs.
The setup I have is:
the master daemon:
Manages the threads, sends messages to the thread queues.
the API threads:
one thread per API. This allows me to start Task #2 on API #1, while Task #1 is finishing up with the final API. There are 4 or 5 APIs (maybe 6?). Some of these APIs are web-based, some are java applications that I execute from the thread.
So, with this in place, I'd like to also setup something to monitor the cpu/memory usage of the daemon and its threads while this is running in production, and I'd like to save this information somewhere (flatfile? off site database?)
What are the best approaches to this?

A:

You can use  psutil to retrieve information of running processes, and store wanted results using the logging module.


Q:

Recommendation on building a browser app for visualizing data in a database for within the company?

I'm looking for a solution for this intended application.
I maintain a database of performance of a list of companies in our investment portfolio. The database is a collection of the company's daily performance, going back a few months. The format of the table is as follows (simplified version):
ID, Date, Investment_Name, Market_Share, %_change
1, 1/1/2000, SPX, 0.1, 0.05
2, 1/1/2000, INDU, 0.2, -0.01
...
101, 1/2/2000, SPX, 0.1, 0.03
102, 1/2/2000, INDU, 0.2, 0.03
...

The data is maintained in Access currently and I have queries setup for myself to see things like daily return for the whole portfolio, get historical series for selected securities, etc. Basically anything I can think of that I can make a query for.
..
Now I'm trying to create something for other people to access this data. I want it to be an application (hosted on our local network), that gives people an idea for our company's current performance. The simplest thing I could think of is to make a browser app that queries the database and gives visualization of the data. The user can have the freedom to select things they want to look at, in both table and graph form. Maybe make a few modules that displays "top 5" "bottom 5" in each asset class. More advanced feature would be making "what if" scenarios, changing security composition and things like that.
My experience in development is quite limited. I know python to a workable extent, have used things like pandas and matplotlib for local graphing. I'm wondering if there's a lightweight way to set up a system like this using some other python modules? Or is there a web framework already available for this type of task? I'm sure this is a common task in many organization and I'd love to know what's the easiest way to accomplish this.
Thanks a lot for your time.

A:

There are various opensource BI tools, the major players are:

http://www.pentaho.com/
http://www.actuate.com/products/open-source-bi/
http://community.jaspersoft.com/

It's not just about a tool though, do you want to keep the data in Access or do you want to put it in something like mysql or postgresql, how will you automate the ETL (see also http://www.talend.com), document the definitions etc.
Building it yourself is cooler, but also not that easy. You could build a RESTful api on pandas (running on UWSGI/Flask for instance) and then put a html5 library like d3.js (http://d3js.org) on top of it. But that's a really large effort, especially for a one man team. I would look at pentaho if i were you ;)


Q:

Form Validation using JavaScript and html

i want to validate my form.I have a form validation javascript code in my code igniter view but it is not working and still sending values to next page without any validation.Could you tell me where I am making mistake and why this is happening?
Code:
<form method="get" action="/calculator/stage_two" name="calculate" id="calculate" onsubmit="return validateForm();">

        <input type="text" name="property_number" placeholder="No/Name" id = "property_number" class="stage_one_box" />
        <input type="text"  name="postcode" placeholder="Postcode" id = "postcode" class="stage_one_box" />

    <input type = "image" name = "submit_calculator" id = "submit_calculator" value="Go" src = "/images/next_button.png" />
</form>

Javascript function:

A:

You are missing an end bracket. Any error in the validation code will return a non-false value and allow the submission
Here is a canonical way using forms access:
<form method="get" action="/calculator/stage_two" name="calculate"
  id="calculate"  onsubmit="return validateForm(this);">

    <input type="text" name="property_number" placeholder="No/Name" id = "property_number" class="stage_one_box" />
    <input type="text"  name="postcode" placeholder="Postcode"
      id = "postcode" class="stage_one_box" />

    <input type = "image" name = "submit_calculator" id="submit_calculator" src="/images/next_button.png" />
</form>

A:

It seems like you are missing the closing braces "}" at the end of the function.


Q:

create primary and foreign key relationship

I am trying to create a table name accounts. I have created a visual diagram in mysql workbench. I copied sql command from diagram try to create real table from my command line but  command line is showing
ERROR 1215 (HY000): Cannot add foreign key constraint

Here is the query
CREATE TABLE accounts(
    account_id INT NOT NULL AUTO_INCREMENT,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    PRIMARY KEY ( account_id ),
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;

A:

The customers table could look like the below. It needs to have a common data type and index for the column in Parent table (customers). The FK will fail on child table create if column types / index are wrong.
And for an ALTER TABLE add constraint command with pre-existing data in child, it will fail if data is not valid.
By the way, the INT(4) is just a display width. It is still an int.
create table customers(
    customer_id int auto_increment primary key,
    customerName varchar(100) not null
    -- other columns
);

CREATE TABLE accounts(
    account_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;


Q:

How can I set the correct position of the text in CSS?

I have the following css code:
#content{
  position: fixed;
  bottom: 21px;
  text-align: right;
}

#content h1{
  font-size: 1.5vw;
  text-align: right;
}

and html:

content

here's jsfiddle. I cannot make the text to be displayed on the right side, it's only on the left side... How can I fix it? Thanks.

A:

Set container's (#content) width css property to 100%.
JSFiddle


Q:

Chrome.socket listener in browser

So I've searched very thoroughly and tried a lot of things to create a TCP or UDP listener for the Chrome.socket API in the browser in JavaScript. I am very confused now. So far I have tried using:

WebSockets
WebTCP sockets
WebRTC
PeerJS
Node net module in chrome extension

And several more small options. So far these 'options' all don't seem to work properly. The closest I got was getting a readyState of zero in the browser. The server accepts the connection, but the readyState of the socket in the browser just stays zero (means still connecting).
I have two questions.
Is it possible?
Is it even possible to listen to incoming TCP/UDP connections made from a Chrome extension on a sperate website with only client-side JavaScript?
How?
If so, how would I be able to create this?

A:

For security reasons, you will never be able to create raw sockets in pure client-side code.
Protocols like WebSockets or WebRTC require that the server explicitly acknowledge the protocol and allow you to connect.


Q:

How to store OAuth data

We have several oauth2 providers people can authorize through (twitter, facebook, etc). Now we store data in database via "provider/id". The problem is: we want a possibility to use several oauth2 providers for one user, i.e. user can authorize through facebook, then through twitter and it would be one user in our database.
We thought about related table, like oauth_users_info, or something like that, where we will store fields like facebook_id, twitter_id etc, and use it after authorization.
Is that a good practice or u can propose something better? I'm afraid of pitfalls that can cause some problems afterwards.

A:

Actually, you may want to create Identity model, associated to User model. User can have many Identities like facebook, twitter, etc. Your Identity model will be like,
Identity(id: integer, uid: string, provider: string, user_id: reference)


Q:

SAS token is expiring while Blob download

I have a SAS token which will expire within 2 minutes.
SAS = AzureClient.GetCloudContainer().GetSharedAccessSignature(new SharedAccessPolicy()
{
    SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromMinutes(1)
}, "readonly");
var sasCreds = new StorageCredentialsSharedAccessSignature(SAS);
CloudStorageAccount _storageAccount = AzureClient.GetCloudStorageAccount();
CloudBlobClient sasBlobClient = new CloudBlobClient(_storageAccount.BlobEndpoint, sasCreds);

CloudBlob sasBlob = sasBlobClient.GetBlobReference("blobname");

Where readonly is the policy name.
Now I am doing the following operation:
using (BlobStream stream = sasBlob.OpenRead())
{
    using (FileStream fileStream = File.OpenWrite(@"Smething.txt"))
    {
        BlobStreamReader(stream,fileStream);
    }
}

private void BlobStreamReader(BlobStream blob,Stream OutputStream)
{
    int buffersize = 4194304; // 4MB
    byte[] data = new byte[buffersize];
    do
    {
        int bytesRead = blob.Read(data,0,buffersize);
        if (bytesRead == 0) break;
        OutputStream.Write(data,0,bytesRead);
    }
    while (true);
}

The problem is that download is failing when the SAS is expired. I had an understanding that the SAS token is needed only for authentication and if download is started with its expiry time then download will continue even if the SAS is expired.

A:

It is correct that the SAS token is needed only for authentication. However, in your case, BlobStream will issue a new request whenever it needs more data from the server. Because each request needs to be authenticated separately and your SAS token expires before the entire download is finished, it is expected to fail.
If you want to download the entire blob, DownloadToStream is actually a better alternative, because it will only issue a single request to the server and then download the entire blob.


Q:

Problem for gradient and extremum points.

I try to compute extremum points for this funciton:
$$
f(x,y) = x^{4} - y^{4} - 4xy^{2}-2x^{2}
$$
The first step compute gradient:
$$
\nabla f(x,y) = [4 x^3-4 x-4 y^2, -8 x y-4 y^3]
$$
Next step
$$
\nabla f(x,y) = 0
$$ and its fail. It's not easy compute explicitly roots.
Do you have any ideas?

A:

Your system is$$\left\{\begin{array}{l}x^3-x-y^2=0\\2xy+y^3=0.\end{array}\right.$$If $y=0$, then the second equation becomes $0=0$, whereas the first one becomes $x^3-x=0$. So, the solutions for which $y=0$ are $(\pm1,0)$ and $(0,0)$.
If $y\ne 0$, then the second equation is equivalent to $2x+y^2=0$, that is, $y^2=-2x$. But then the first equation becomes $x^3-x+2x=0$, or $x^3+x=0$. Can you take it from here?


Q:

Java 8: Reflection Field.get() try-catch error

Issue
I am receiving an error in Eclipse stating that I have an unhandled exception with my call to Field.get(Object). When I wrap the code in the recommended try-catch, the error persists. I assume that I have to wrap the parameter, in the get() method, with a try-catch. Is this possible?
Error

Unhandled exception type IllegalAccessException

Line in question:
return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());

Code
Main.java
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Entity> entities = Arrays.asList(
                new Item(0, "Apple"),
                new Item(1, "Banana"),
                new Item(2, "Grape"),
                new Item(3, "Orange")
                );

        List<Long> ids = null;
        try {
            ids = pluck("id", Long.class, entities, Entity.class, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(ids);
    }

    public static <E extends Entity> List<Long> pluckIds(List<E> list) {
        return list.stream().map(e -> e.getId()).collect(Collectors.toList());
    }

    public static <T,F> List<F> pluck(String fieldName, Class<F> fieldType,
            List<T> list, Class<T> listType, boolean useLambda)
            throws NoSuchFieldException, IllegalAccessException,
            IllegalArgumentException {
        Field f = listType.getDeclaredField(fieldName);
        f.setAccessible(true);

        if (useLambda) {
            return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());
        } else {
            List<F> result = new ArrayList<F>();
            for (T element : list) {
                result.add(fieldType.cast(f.get(element)));
            }
            return result;
        }
    }
}

Item.java
public class Item extends Entity {
    private String name;

    public Item(long id, String name) {
        super(id);
        this.setName(name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Entity.java
public abstract class Entity {
    private long id;

    public Entity(long id) {
        this.id = id;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}

A:

Eclipse is kind of stupid right now (there's probably a bug open).
You have a lambda expression in here
return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());

Field#get(Object) is declared as throwing a checked exception. But Function#apply(Object), which is the functional interface method you're implementing, does not. Eclipse is stupid in that it recommends that you wrap the statement in a try block, but it adds the try block around the whole thing
try {
    return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());
} catch (Exception e) {
}

when in reality it should be adding it to the body of the lambda
return list.stream().map(e -> {
    try {
        return fieldType.cast(f.get(e));
    } catch (Exception e) {
        return /* something else */ null; // or throw an unchecked exception
    }
}).collect(Collectors.toList());

This seems to happen when your lambda body is a simple expression rather than a block.


Q:

Javascript references aren't working ASP.NET Development Server?

I'm not sure what's going on here. I've reformed the links in every way I can think of to try and reference my Script libraries, but nothing seems to work.
When I upload it to my web host it works fine, locally it doesn't work at all.
The weirdest part is, it references my CSS files fine and nothing else seems to have any issues.
//Works
<link href="@Url.Content("~/Content/main.css")" rel="stylesheet" type="text/css" />
//Doesn't work
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>

I'm not sure what could be going on here or really even where to debug from here. I've tried removing the @Url.Content(...) and pointing directly to the directory, but that doesn't do anything at all. Hopefully someone else has run into this issue and has figured out a solution.
Using: ASP.NET MVC3 Razor, Visual Studio 2010 Professional

A:

If you're using the default directory setup then your Scripts folder is a sub-directory of the Content folder; in which case:
<script src="@Url.Content("~/Content/Scripts/jquery-1.5.1.min.js")"></script>


Q:

Is it possible to have two triangles with equal sides but with different angles?

Can there be two triangles, for example $ \triangle ABC $ and $ \triangle DEF$ so that the measure of their sides is the same but their angles are different? Thanks.

A:

Yes, if the triangles aren't necessarily both Euclidean. This may not be what you meant, and the other answers may answer your question more appropriately, but this seems a good opportunity to point out some more exotic scenarios that can exist.
One thing we could do is take triangles from different geometries. For instance, the sum of the angles of a triangle drawn on a sphere will always be greater than $180$ degrees. So you could draw one triangle on a flat plane, another on a sphere, make the side lengths match, and you will get different sized angles.
Be aware though that it isn't sufficient to just scale the metric on a Euclidean space. That is, if I define two different planes where distance is greater in one but they are both flat, and I draw two triangles with matching side length, the angles will still be the same. The important thing about the example of the previous paragraph is that we changed the curvature of the space.
Maybe it's cheating to allow the two triangles to come from different geometries. Well it is in fact possible to draw two triangles with matching side lengths and different angles, in the same geometry. You can do this in the hyperbolic plane by allowing vertices on the boundary of the plane.
The boundary of the hyperbolic plane is like a circle that is infinitely far away from any point in the space. If you put two vertices on this boundary, then pick whatever point you want within the space for your third vertex, each side of the triangle will have infinite length. So the lengths of the sides would be unaffected by where you choose to put your third vertex. Also, the two angles at the vertices on the boundary would actually be $0$ degrees, and the third one could be any number up to and including $180$ degrees, depending on where you put it! This wouldn't work in Euclidean space. You can also talk about a circle boundary of $\mathbb{R}^2$ infinitely far away, but there, you can't draw a straight line connecting arbitrary boundary points and passing through the plane.
There's lots of Google-able info out there (and in Wikipedia too) about the hyperbolic plane, if this concept interests you and you want to know more!

A:

No: given three sides of a triangle, the cosine rule determines the angles unambiguously:
$$ c^2 = a^2+b^2 - 2ab\cos{\gamma}, $$
so
$$ \cos{\gamma} = \frac{a^2+b^2-c^2}{2ab}, $$
where $\gamma$ is one of the angles, $c$ is the side opposite $\gamma$, and $a,b$ the other two sides. Cosine is one-to-one from the angles between $0$ and $\pi$ to the real interval $(-1,1)$, and one can check that the right-hand side lies strictly between $-1$ and $1$ when $a,b,c$ form a triangle, so one has
$$ \gamma = \arccos{\left( \frac{a^2+b^2-c^2}{2ab} \right)}. $$

A:

No, this is not possible in normal Euclidean geometry. Two triangles are congruent if all the corresponding sides are pairwise equal, so their angles will be equal too.


Q:

How do I send an ARP packet through python on windows without needing winpcap?

Is there any way to send ARP packet on Windows without the use of another library such as winpcap?
I have heard that Windows XP SP2 blocks raw ethernet sockets, but I have also heard that raw sockets are only blocked for administrators. Any clarification here?

A:

There is no way to do that in the general case without the use of an external library.
If there are no requirements on what the packet should contain (i.e., if any ARP packet will do) then you can obviously send an ARP request if you're on an Ethernet network simply by trying to send something to any IP on your own subnet (ensuring beforehand that the destination IP is not in the ARP cache by running an external arp -d tar.get.ip.address command), but this will probably not be what you want.
For more information about raw socket support see the TCP/IP Raw Sockets Docs page, specifically the Limitations on Raw Sockets section.


Q:

MouseAdapter methods - why `mouseDragged`, `mouseMoved` and `mouseWheelMoved` included?

My goal was to simplify this code (all works fine):
package test;

import java.awt.Window;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JWindow;

public class A extends JWindow implements MouseListener, MouseMotionListener {

    public A() {
        addMouseListener(A.this);
        addMouseMotionListener(A.this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    }
}

But if I decide to use MouseAdapter like this:
addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        transferFocusBackward();
        //This method is being used, working fine
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, not working anymore
    }
});

mouseDragged receiving no events. But if I add MouseMotionListener like this:
addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }
});

addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }
});

Then everything backs to normal. So my question is - what is the purpose of mouseDragged, mouseMoved and mouseWheelMoved methods in MouseAdapter class if they do not work?

A:

OK, I think I understand now: in MouseAdapter class documentation it is said that "Create a listener object using the extended class and then register it with a component using the component's addMouseListener, addMouseMotionListener, addMouseWheelListener methods". So now it looks like:
private class MouseListeners extends MouseAdapter {

    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }
}

and then:
MouseListeners listeners = new MouseListeners();
addMouseListener(listeners);
addMouseMotionListener(listeners);

Now everything is OK.


Q:

Is it possible to iterate through a array in lambda expressions? (java)

I need to make a new ForkJoinTask for every division, and don't know how to get to the next position in the array. Can someone help me?
protected static double parManyTaskArraySum(final double[] input, final int numTasks) {

        double sum = 0;
        // ToDo: Start Calculation with help of ForkJoinPool
        ForkJoinPool fjp = new ForkJoinPool(numTasks);
        fjp.execute(() -> {

            sum+=( 1 / input[???] ); //the problem is here
        });

        return sum;
    }

Exception: local variables referenced from a lambda expression must be final or effectively final

A:

You are feeding a Runnable lambda to your ForkJoinPool.
As such, you cannot parametrize it with the desired array chunk.
You should actually define a class extending RecursiveTask<Double> whose constructor takes the array chunk as parameter, and decides whether to operate on the whole of it or fork if it's too large.
Then use the invoke method of your ForkJoinPool to get the result of the final calculation, by passing it a new instance of that RecursiveTask<Double> taking the whole array (the task will the decide based on your criteria whether to do everything in one go, or to fork, say, half of the array's elements to another task and join later).
Note as there is some confusion here.
If in fact, you don't need to leverage the fork/join framework and only want to perform your operation asynchronously, there are many ways to do so without a ForkJoinPool.
For instance:
Callable<Double> call  = () -> {return Arrays.stream(input).sum();};
Future<Double> future =  Executors.newSingleThreadExecutor().submit(call);
// when you're ready
Double sum = future.get();


Q:

How does last authorize.net changes refer to CiviCRM

Lately I have received email stating that a few things are changing in Authorize.net payment. Among a few items (changing urls, longer ids, tls 1.1 force etc) one is:

RC4 Cipher Disablement
  In an effort to ensure that all of your server-to-server communications with the Authorize.Net platform (both
  transactional and otherwise) maintain the highest levels of security,
  we will be disabling the RC4 cipher suite during the first half of
  2016. A follow-up notification will be sent out once specific dates for the disablement are ready for the sandbox and production
  environments.
For now, if you have a solution that relies on RC4 to communicate with
  our servers, please update it to a current, high-security cipher as
  soon as possible. Please review our API best practices blog post for
  more information.

I haven't been able to find anything mentioning rc4 in civicrm authorize.net payment processor. Does anyone know if this relates to CiviCRM?

A:

From my understanding, this has a lot more to do with your web server and the cypher suites that are configured than it does with CiviCRM directly.  SSLLabs has a great page on getting all of that set up.
https://www.ssllabs.com/index.html


Q:

how do i check the data in an array with indexOf in java

i'm fairly new to java and i'm trying to use indexOf to check if a persons name ends with the letters in the array and output a word it rhymes with. Where am i going wrong? e.g. Dean ends in "ean" so it rhymes with green. Thanks guys
    String [] first = new String [3];
    first [0] = "eem";
    first [1] = "een";
    first [2] = "ean";

    for (int i = 0; i < first.length; i++) {

        if (first[i].indexOf(first.length) != -1){
            System.out.println("That rhymes with green");
        }
    }

A:

You should use endsWith instead of indexOf. indexOf will return the index where the passed string exactly matches the current string and, as the name suggests, endsWith will check if the current string ends with the passed string.
Take a look at the following code:
String personName = "Dean";
String[] suffix = {"eem", "een", "ean"};
String[] names = {"greem", "green", "grean"};

for(int i = 0; i < suffix.length; i++) {
    if (personName.endsWith(suffix[i])){
        System.out.println("That rhymes with " + names[i]);
    }
}

Also, ideally, you would want to keep a map of suffix -> name for maintainability, but for simplicity/exploring this should be fine.


Q:

Create a function called addGrade

I need to Create a function called addGrade with the following params: index, grade
that gets a student's index in the array and adds him a new grade.
I have array with all the object student and now I need to add grade to all the student by their id.

var studentArray = [];
var grade = [];

function createStudent(id, age, firstName, lastName){
  this.id = id;
  this.age = age;
  this.firstName = firstName;
  this.lastName = lastName;

}

var student1 = new createStudent(111, 36, "A", "A");
var student2 = new createStudent(222, 46, "B", "B");
var student3 = new createStudent(333, 56, "C", "C");
var student4 = new createStudent(444, 66, "D", "D");

studentArray.push(student1, student2, student3, student4);

function addGrade(id, grade){

}

console.log(studentArray);

How can I do this? I really feel lost!
Thanks!

A:

Since a grade belongs to a student it would be better to add grade as a property to the Student object instead of a separate grade array. Then as indicated in my comment all you need to do is loop through the array, check if student.id matches the given parameter id and if so assign the grade given to the students grade student.grade = grade.

var studentArray = [];

function createStudent(id, age, firstName, lastName){
  this.id = id;
  this.age = age;
  this.firstName = firstName;
  this.lastName = lastName;
  this.grade = null;
}

var student1 = new createStudent(111, 36, "A", "A");
var student2 = new createStudent(222, 46, "B", "B");
var student3 = new createStudent(333, 56, "C", "C");
var student4 = new createStudent(444, 66, "D", "D");

studentArray.push(student1, student2, student3, student4);

addGrade(111, "A"); // Give student 111 a A
addGrade(222, "C"); // Give student 222 a C
addGrade(444, "B"); // Give student 444 a B
                    // Student 333 will have the default null value

function addGrade(id, grade){
    studentArray.forEach(function(student){ // For each student in the studentArray
      if(student.id == id)                  // If that student id matches the given id
        student.grade = grade;              // Assign the given grade to that student
    });
}

console.log(studentArray);


Q:

andorid daydream service webview (context requires the flag_activity_new_task flag)

I have implemented the android daydream service in which I have played a video from asserts ,
I have put a button there and onclick listener I want to open a webview with a link, every things goes right but I can't able to deal with the webview as when I clicks the button this message appear
Unfortunatley App has stopped
and the error message that appears in log is

AndroidRuntime(827): FATAL EXCEPTION:
  android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  con text requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I have created the webview in the xml file
my code for calling webview is:
final WebView webView = (WebView)this.findViewById(R.id.webView1);

   button.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
           // Perform action on click
           vv.stopPlayback();
           vv.setVisibility(View.GONE);//for media player

           webView.setVisibility(View.VISIBLE);
           webView.loadUrl("http://www.google.com");
       }
   });

A:

After a lot of search i found answer of my question here is the link that helps me most
link
basically i just put this class code in my android dreamservice
    private class LinkLauncher extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        return true;
    }

and uses the webview as follow
           WebView webview = (WebView) findViewById(R.id.webView1);
           webview.setVisibility(View.VISIBLE);
           webview.setWebViewClient(new LinkLauncher());

           WebSettings webSettings = webview.getSettings();
           webSettings.setJavaScriptEnabled(true);

           webview.loadUrl("http://www.google.com");

i write answer that might help anyone else.
thanks


Q:

Outputting HTML In Twig From Database

I have a database that stores some text as well as some HTML inside of a varchar column. It looks something like this:
Click here to go to the site: http://www.google.com.

However when I output this to the HTML page it appears as plain text and is not a clickable link.
How do I make it output as a valid HTML tag and create a clickable href?
I fetch the data using a Slim route:
$app->get('/projects/:id', function($id) use ($app) {
    // Open Dataabse Connection
    $con = connect_db();
    // Query for all Projects with specific Id
    $project = $con->query("SELECT * FROM Projects WHERE projectId=".$id."")->fetch(PDO::FETCH_OBJ);
    // Get Documents associated with Project Id
    $documents = $con->query("SELECT * FROM ProjectDocuments WHERE projectId=".$id."")->fetchAll(PDO::FETCH_OBJ);
    // Get Student Updates by Project Id
    $updates = $con->query("SELECT * FROM StudentUpdates LEFT JOIN ASAPers ON ASAPers.userId = StudentUpdates.userId
        WHERE projectId=".$id." ORDER BY StudentUpdates.date DESC LIMIT 5")->fetchAll(PDO::FETCH_OBJ);

    $projectArray = array();

    foreach ($project as $key => $value) {
        $project->{$key} = htmlspecialchars_decode($value);
        array_push($projectArray, $project->{$key});
    }

    print_r($projectArray);

    // Render Single Project page
    $app->render('single.project.twig', array('project'=>$projectArray, 'updates'=>$updates, 'documents'=>$documents));
});

Inside single.project.twig

{{ project[1] }}

{{ project[2] }}

If I print the array out in PHP it appears as a HTML link! However, as soon as I print out my variable using Twig it appears as plain text again!

A:

Just figured this out. For anybody who sees this here is the answer.

{{ project[1] | raw }}

{{ project[2] | raw }}

Adding | raw will output the HTML as HTML.


Q:

I accidentally set my default terminal command to "killall Terminal"

It wasn't just killall Terminal. It was some command;killall Terminal because all I wanted to do was run an sshfs command and then exit the terminal, and previously using some command;exit had yielded un-satisfactory results, with me forgetting to quit Terminal and such. But now, the command is exiting with an error and I can't open the preferences or open my default terminal window because it automatically exits every time. Is there any way to restore Terminal to it's original settings? I feel really stuptid now.

A:

I found that going to ~/Library/Preferences/com.apple.Terminal.plist and using a 3rd party editor called pref setter to edit the startup key to take the command away.


Q:

Rails: Check uniqueness of decrypted data

I have a users table with an encrypted_mobile_number field. How can I check the uniqueness of the decrypted mobile_number without looping on all the mobile numbers?  I am using MessageEncrptor for the Encryption and Decryption of data. api.rubyonrails.org/classes/ActiveSupport/MessageEncryptor.html

A:

Option 1: Override the reader
validates encrypted_mobile_number, uniqueness: true

def encrypted_mobile_number
  # ...
  crypt.decrypt_and_verify(@encrypted_mobile_number)
end

Option 2: Create unique index
add_index :users, :encrypted_mobile_number, unique: true


Q:

Replace all div tags of each row of a table

I am trying to replace a div tag that is the same on each row of a dynamically created table. I'm not sure how to go about it. Right now I can get the function to work but it only replaces the first row of div tags. Here is my code:


Q:

Control how linux deletes files

What exactly happens when an application deletes a file?
Is there any way to control this behavior? Basically I want to shred instead of rm in all cases, but of course applications do not make calls to rm, I am guessing they interact directly with the kernel?? Would I have to modify the kernel to implement this feature?

A:

Rather than trying to intercept all filesystem calls, what about encrypting the filesystem your data is stored upon?  Then, all of your data gains the benefit of being securely encrypted, including that which was deleted.


Q:

All com.android.support libraries must use the exact same version specification for 26.+ (android version 2.3.3)

I am new in Android development, I am making Firebase chatting app, But suddenly I am facing the issue of transitive dependency. I followed this link
Do not use + for a library version . But failed to resolve the problem. Here is my code build.gradle(Module),
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "kiran.example.com.firebasechattingapp21_11"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-core:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:26.0.0-alpha1'
    compile 'com.firebaseui:firebase-ui:1.1.1'
}

apply plugin: 'com.google.gms.google-services'

I am facing the following error,

All com.android.support libraries must use the exact same version
  specification (mixing versions can lead to runtime crashes). Found
  versions 26.0.0-alpha1, 25.1.0. Examples include
  com.android.support:animated-vector-drawable:26.0.0-alpha1 and
  com.android.support:cardview-v7:25.1.0

Following is the code of build.gradle (Project)
 // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

If anyone is having the solution please help.

A:

Yes after searching I Solved this issue by the following way
I added the following lines in build.gradle app level
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-core:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:26.0.0-alpha1'
    compile 'com.firebaseui:firebase-ui:1.1.1'
    **//add the following for transitive dependency**
    compile 'com.android.support:animated-vector-drawable:26.0.0-alpha1'
    compile 'com.android.support:cardview-v7:26.0.0-alpha1'
    compile 'com.android.support:customtabs:26.0.0-alpha1'
    compile 'com.android.support:palette-v7:26.0.0-alpha1'
}

after that I solved the problem which I have posted here, But one new problem occured i.e.

Error:Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : Attribute application@supportsRtl value=(true) from AndroidManifest.xml:12:9-35    is also present at
    [com.firebaseui:firebase-ui-auth:1.1.1] AndroidManifest.xml:14:18-45
    value=(false).    Suggestion: add 'tools:replace="android:supportsRtl"'
    to  element at AndroidManifest.xml:7:5-22:19 to override.

By taking the reference from this I solved above new issue. Thanks for your comments. :-)


Q:

Reloading Cufon after Ajax load, please assist

I have been trying every possible combination of cufon.replace - Cufon.refresh and Cufon.reload but i just cant seem to get this working. when original page loads cufon does its job, but when Ajax loads new content the cufon is missing. here is my java hope this makes sense to anyone, Cufon fires first, followed by Ajax,
    jQuery.noConflict();

/*
  * TYPOGRAPHY
*/

Cufon.set('fontFamily', 'ColaborateLight');
Cufon.replace('h2, #main h3, h4, h5, h6, #slogan, .label', {
    hover: true
});

Cufon.set('fontFamily', 'Colaborate-Medium');
Cufon.replace('#main_home h3', {
    hover: true
});

jQuery(document).ready(function() {

    var hash = window.location.hash.substr(1);
    var href = jQuery('#nav2 li a').each(function(){
        var href = jQuery(this).attr('href');
        if(hash==href.substr(0,href.length-5)){
            var toLoad = hash+'.html #content';
            jQuery('#content').load(toLoad)
        }
    });

    jQuery('#nav2 li a').click(function(){
    jQuery("#nav2 li a").addClass("current").not(this).removeClass("current");

        var toLoad = jQuery(this).attr('href')+' #content';
        jQuery('#content').hide('fast',loadContent);
        jQuery('#load').remove();
        jQuery('#wrapper').append('LOADING...');
        jQuery('#load').fadeIn('normal');
        window.location.hash = jQuery(this).attr('href').substr(0,jQuery(this).attr('href').length-5);
        function loadContent() {
            jQuery('#content').load(toLoad,'',showNewContent())
        }
        function showNewContent() {
            jQuery('#content').show('normal',hideLoader());
        }
        function hideLoader() {
            jQuery('#load').fadeOut('normal');
        }
        return false;

    });

});

and this is the pages in question that im having trouble with.
Climate Page
You will see the Ajax loader at the bottom of the page with a secondary menu list.
I'm desperate guys, please help...

A:

I had the same issue, couldn't get this to work:
$("#my_div").load('some-ajax-file.php', Cufon.refresh);

But, wrapping Cufon.refresh in a function did the trick:
$("#my_div").load('some-ajax-file.php', function() { Cufon.refresh(); });

A:

this worked for me...
$(document).ajaxSuccess(function() {
    Cufon.refresh();
});


Q:

How to print ordered submodel in template?

I have models:
class Model_1(models.Model):
    name = models.CharField(...
    pos = models.IntegerField(...

class Model_2(models.Model):
    ...
    m1 = models.ManyToManyField(Model_1,...

and I print this in template:
{% for m2 in model2 %}
    {% for m1 in m2.m1.all %}
        {{ m1.name }}
    {% endfor %}
{% endfor %}

but I want to print m1.names ordered by 'pos' field. How to do it?

A:

in the model you can specify ordering of the objects. More here
class M1():
   ...
   class Meta:
      ordering = ['pos']


Q:

Dynamic linking with smalltalk objects

I plan about implementing a dynamic linking into my smalltalk dialect. The problem is about getting message passing to work with dynamic linking.
Message passing itself is as simple as this: message with a selector is sent to the object, the object picks up a method matching with the selector from it's protocol, it then process the data bundled with the message and returns a result.
In image-based implementations, one can implement message passing in very straightforward manner - Your message selectors can be just integers translated from the global symbol table, your protocols can be just hash tables with integers and addresses in them. Assuming it's all compiled into an one big image with that global symbol table.
In dynamic linking, you can't assume a symbol table pointing to a correct selector. You can turn around the problem with using strings as your selectors, but you doom the language being slower.
There's one way, and it involves copying the protocols and a table of selectors for the process to relocate them properly. But it's sounds like a quite lot of work.
Is there better ways to solve this problem? Also, is the dynamic linking worth it? How could I implement the relocation for the selectors and protocols?

A:

Sure you can assume a global symbol table, you just have to update it and ensure at link time that the codes only uses symbol instances from that table. Did you have a look at Squeak? The loading code is image-level (not VM) so it's easy to browse from any Squeak image.


Q:

Cauchy sequence Convergence on real numbers

Suppose $\{a_n\}$ and $\{b_n\}$ are Cauchy sequences of $\mathbb{R}$. Show that $\{a_n+b_n\}$ is also Cauchy sequences.
My proof is like this. Since this is a Cauchy sequences of $\mathbb{R}$, $\{a_n\}$ and $\{b_n\}$ converges. Thus, $\{a_n+b_n\}$ converges. Since every convergent sequences is Cauchy sequences,  $\{a_n+b_n\}$ is Cauchy sequence.
Is it okay to prove like this instead of using definition of Cauchy sequence to prove it?

A:

Whether or not it is 'okay' really depends on who you're doing this work for.  Nobody here can answer that for you.
I will say, though, that you've used a really heavy piece of machinery (that any Cauchy sequence in $\mathbb{R}$ converges) when it is completely unnecessary for the problem at hand.
It is very straight-forward to prove this fact directly.  Take an $\epsilon>0$, and use the fact that $(a_n)$ and $(b_n)$ are Cauchy to show that both $\lvert a_n-a_m\rvert$ and $\lvert b_n-b_m\rvert$ can be made small for all $n,m\geq N$, for some $N\in\mathbb{N}$. Then use the triangle inequality to consider $\lvert (a_n+b_n)-(a_m+b_m)\rvert$ when $n,m$ exceed that same $N$.


Q:

Error on ALTER TYPE in postgres relation does not exist

Using the following:
CREATE TYPE user_types AS ENUM ('it', 'accounting', 'processes');

CREATE TABLE my_users
(
    my_user_id integer NOT NULL,
    my_user_name text NOT NULL,
    my_user_type user_types
)

I want to change one of the user types:
ALTER TYPE user_types RENAME ATTRIBUTE it TO softwaredev CASCADE;

I get a error:
ERROR: relation "user_types" does not exist
SQL state: 42P01

I tried adding quotes and backticks but that didn't help. The example I wrote down here is not the exact code, my type has 31 characters, but I don't think the length of my type is the issue.
I'm using postgres version 9.6.2

A:

ALTER TYPE ... RENAME ATTRIBUTE only works for composite types, not for ENUM types.
While there is a way to add new entries to such a type (ALTER TYPE ... ADD VALUE 'new_value'), there is no supported way to remove or rename an enumeration entry.
If you are not afraid to mess with the catalogs, you can try as superuser:
UPDATE pg_enum
SET enumlabel = 'softwaredev'
WHERE enumtypid = 'user_types'::regtype
  AND enumlabel = 'it';

From PostgreSQL v10 on, you can use
ALTER TYPE ... RENAME VALUE ... TO ...


Q:

How bad is kickboxing for your brain?

I'm not asking for medical advice, I'm just asking this out of sheer curiosity:
To me it seems that kickboxing is the best kind of workout I could get, nothing else gets me in shape quite as quickly and as well. But as a noncompetitive kickboxer, I've always wondered what doctors would say about the potential for braindamage with kickboxing.
I mean, is it something that always occurs, or is it incidental? Sometimes when I'm hit well (about 2 - 3 times every training), I see stars and feel a little lightheaded. I've always wondered what's actually going on in my body when that happens. I mean, most sports tend to damage you a little, but in the long run the gains are worth it and you heal from the damage. Or is the damage you do to yourself with kickboxing beyond healing (and if so, is there a point of no return)?

A:

I don't think the science is settled to a degree where we can give a solid answer, or make too many specific conclusions. Disclaimer: I'm not a kickboxer, and I haven't studied the subject deeply.
Dementia pugilistica
Getting hit in the head is not good for your brain. Getting hit a lot in the head is very bad for your brain. That's true regardless of dosage, but large, repeated doses of getting hit in the head over long periods of time are particularly problematic.
Medicine has known about the brain damage from boxing and kickboxing for a long time. We have a name for it:

Dementia pugilistica...[is a] variant of chronic traumatic encephalopathy... Symptoms and signs of [dementia pugilistica] develop progressively over a long latent period sometimes amounting to decades, with the average time of onset being about 12 to 16 years after the start of a career in boxing. The condition is thought to affect around 15% to 20% of professional boxers.

I would argue that there are probably a lot of people with minor brain damage that doesn't rise to the level of dementia pugilistica. That damage might be insignificant, but it exists. This is backed up by more recent studies, as reported in the LA Times:

A yearlong study of boxers' and mixed martial-arts fighters' brain activity has found those who fight for more than six years begin to experience damage and those who fight longer than 12 years expose themselves to an even greater decline each time they return to the ring.

Mitigation
The degree of brain damage depends greatly on how you train. Competing seriously is definitely a different animal from training hard, and training hard is different again from training casually. Getting your bell rung is a minor concussion, make no mistake, and those are no good. But in terms of serious damage, I bet a lot of people get a handful of minor concussions spread out over a few years of training and don't suffer any major brain damage. Taking three or four ring fights a year, and the training that requires, would probably mean a greater degree of brain damage. (Not debilitating in every case by any means, but it's certainly present.) Doing this for several years would in most cases cause noticeable problems.
Reading up on the signs of concussions is extremely informative. Staying out of hard training after a serious or moderate concussion is definitely a good idea. It would be a good idea for boxing and kickboxing coaches (in addition to grappling and field sports coaches) to adopt a concussion-recognition protocol. The King-Devick test has been shown to work well for boxing and MMA:

The King-Devick (K-D) test is based on measurement of the speed of rapid number naming (reading aloud single-digit numbers from 3 test cards), and captures impairment of eye movements, attention, language, and other correlates of suboptimal brain function. We investigated the K-D test as a potential rapid sideline screening for concussion in a cohort of boxers and mixed martial arts fighters.

In particular, getting knocked out or losing the match were predictors of damage:

Those with loss of consciousness showed the greatest worsening from prefight to postfight. Worse postfight K-D scores and greater worsening of scores correlated well with postfight MACE scores.

So work on your slipping and defense!
It is also probably a good idea to get regular MRIs or other brain tests done, if you continue to train over several years. As noted in the LA Times article, this is already enforced by boxing commissions.
But in the end, hard training is not knitting class. The risks of learning to hit and get hit can be mitigated through careful control in sparring and diligent use of equipment (and recognizing the limitations thereof), but at some point you're going to get concussed.

A:

The biggest risk with concussions is getting a second one shortly after the first. For competetive boxers and kickboxers, this means the 10 count and standing 8 count are sentencing them to long term brain damage. If you're training casually, wearing very good headgear (Winning FG-2900 if you can afford it, Rival d3o would seem to be a good second choice) and a very good mouthguard (custom made for boxing) will help. Also, if you get hit once and see stars - call your sparring off right away, and don't finish the round. You'd want to not do any further sparring for at least 2 weeks.

A:

What is a concussion?
In the last few years we've gotten a lot more info on them, and literally, they are brain damage.  What makes them especially dangerous is that concussions can be extremely unpredictable in terms of cause to effect - sure, getting hit harder in the head is worse, but sometimes lighter hits can cause severe concussions or heavier hits not one at all.
Concussions build up over your lifetime.  Earlier concussions make later ones worse and more damaging.  Receiving a second concussion while still under the effects of a first one can literally kill you.  (High school football deaths are mostly from this.)
The only way to avoid concussions is don't hit your head at all.
That said, you can do a few things if you're going to be in an activity where these happen.

Wear headgear, use gloves.  Preferably, go light.  Really preferably, don't hit each other in the head and train well to take falls.  Obviously, this runs counter to a lot of self defense training and sports, so you have to figure out where on the scale you want to be and how many head shots and how hard is going to be necessary for you to develop and keep your skills and conditioning.
Strengthen your neck muscles.  The stronger your neck, the better you can take those shots because you'll have better stabilizer muscles.  You can still roll with punches, you just don't want the whiplash effect happening.  Stats show sports you wouldn't necessarily think of as being that brutal to the head having high rates of concussions (soccer, volleyball), primarily because they don't do a lot of strength training for the neck and supporting muscles.
Learn what the signs of a concussion are.  Don't ignore them.  Don't try to tough it out.

When do you have a concussion?
The old way of recognizing a concussion was to ask people things like - "How many fingers am I holding up?"  "Who is the President?"  "What is your name?"  These are valid in the loosest sense - if you lose the ability to visually focus, if you cannot remember things (including short term memory loss - "What were you doing 2 minutes ago?"), you have a concussion.
Do you have a headache?  Do you feel nauseous?  Do you feel dizzy?  Does light seem too bright?  Do you slur your speech or mix up your words? You also have a concussion.
If someone's eyes look in different directions, or the pupils do not match in size, there is a concussion.  If you shine a light in their eyes and they don't react, there's a concussion.
Sports teams now have a computerized word test they run people through while they're healthy and after they take a hit, run them through again - if they drop below a certain performance level, this indicates a concussion as well.
What do you do if you have a concussion?
If you have a headache that seems to be getting worse?  Go to the hospital RIGHT AWAY.   The worst case scenario is internal brain swelling/bleeding.  People who die from concussions typically die 30 minutes to a few hours after taking the hit, as their brain slowly swells and crushes itself inside their skull.
If not, the answer is it's time for you to stop training.  Take a rest.  Go home.
Now comes the other unfun part of recovering from a concussion.  You're looking at 3-10 days of recovery IF you rest.  Rest means:

Don't take any other head hits
Try to engage your brain as little as possible - no reading, no studying, no figuring out the tough problem at work...

Non-rest can increase your concussion recovery time to months.
The concussion has damaged the neural connections in your brain, and you basically are stuck letting your brain connect things around again, starting from the most basic autonomic processes.  Things like "pupils focus like this",  "We control our tongue and mouth using these neural connections", etc.   Trying to read or intake heavy information ends up causing the brain to prioritize high level processes and leaves the low level ones unrepaired.
Wow that sounds totally unreasonable!
Yep! The brain is not well designed to take hits.  It helps if you remember that for most of human evolution we weren't designed to last quite as long as we do these days, nor did we need to do much more than organize hunting food or gathering it as a social group.
It's up to you to decide for your own health how much risks you want to take with head shots and how you want to train around that.
You can see a lot of traditional martial arts where sparring only involves body and leg shots.  That's an adaptation, but not necessarily as good for self defense.  You can also see arts where people do controlled drills most of the time, and only once in a while break out the head gear and go with any force.   That's more useful.   It really depends on what risks you plan on taking for you.
Just be aware - muscle heals easiest, bone heals ok, joints heal hard, the brain barely heals.