text:
Q: Django Rest Framework List of Strings Serializer I have two models created in my Django app and am looking for a serialization approach so that the IPs are shown in JSON as a list of strings instead of a list of IPAddress objects.
Desired JSON
[
    {
        "hostname": "www.example.com",
        "ip_addresses": [ "1.1.1.1", "2.2.2.2" ]
    }
]

Current JSON
[
    {
        "hostname": "www.example.com",
        "ip_addresses": [
            {
                "id": 1,
                "ip_address": "1.1.1.1"
            },
            {
                "id": 2,
                "ip_address": "2.2.2.2"
            }
        ]
]

urls.py
class HostSerializer(serializers.ModelSerializer):
    hostname = serializers.CharField(source='name', read_only=True)

    class Meta:
        model = Host
        fields = ['hostname', 'ip_addresses']
        depth = 1

models.py
class IPAddress(models.Model):
    ip_address = models.GenericIPAddressField()

    def __str__(self):
        return str(self.ip_address)

class Host(models.Model):
    name = models.CharField(max_length=100)
    ip_addresses = models.ManyToManyField(IPAddress)

    def __str__(self):
        return self.name

A: Try out this !
class HostSerializer(serializers.Serializer):
    hostname = serializers.CharField(source='name', read_only=True)
    ip_addresses = serializers.SerializerMethodField(read_only=True)

    def get_ip_addresses(self, instance):
        return [item.ip_address for item in instance.ip_addresses.all()]

A: You can use serializers.SerializerMethodField() to achieve what you want:
class HostSerializer(serializers.ModelSerializer):
    hostname = serializers.CharField(source='name', read_only=True)
    ip_addresses: serializers.SerializerMethodField()

    class Meta:
        model = Host
        fields = ['hostname', 'ip_addresses']
        depth = 1

    def get_ip_addresses(self, instance):
        return [item.ip_address for item in instance.ip_addresses]


text:
Q: Jackson: Serialize an EER specialization I'm using spring boot with jackson to provide an API.
In my DB there is a generalization/specialization field. That means, I have two fields: a value and a field that defines the data type of the value.
So my entity looks like this:
public class Example{
    private String value;
    private String type;

    // getters and setters
}

For example with these three entries:
"1234";"Integer"
"example string";"String"
"true";"Boolean"

Jackson serialize this as follows:
[{
    "value": "1234",
    "type": "Integer"
},
{
    "value": "example string",
    "type": "String"
},
{
    "value": "true",
    "type": "Boolean"
}]

This is what I expteced, but, I need this:
[{
    "value": 1234,
    "type": "Integer"
},
{
    "value": "example string",
    "type": "String"
},
{
    "value": true,
    "type": "Boolean"
}]

So, the values should be serialized according to the value of the "type" field.
I know that I can attach a serializer to the "value" field, but I cannot access the "type" field there to know how to serialize the value.

A: One option is to change your Example class like this if you can :
public static class Example {
    private String value;
    private String type;

    @JsonIgnore
    public String getValue() {
        return value;
    }

    @JsonProperty("value")
    @JsonRawValue
    public Object getRawValue() {
        if("String" .equals(type)){
            return '"'+ value +'"';
        }
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

Or you could use deserializer on Example class
public static void main(String[] args) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Example.class, new MySerializer());
    mapper.registerModule(module);
    System.out.println(mapper.writeValueAsString(list));
}

private static class MySerializer extends JsonSerializer<Example> {
    @Override
    public void serialize(Example value, JsonGenerator gen, SerializerProvider serializers)
                                                                      throws IOException {
        gen.writeStartObject();

        gen.writeFieldName("value");

        if (value.getType().equals("String")) {
            gen.writeString( value.getValue());
        } else {
            gen.writeRawValue(value.getValue());
        }

        gen.writeStringField("type", value.getType());
        gen.writeEndObject();
    }
}

Result:
[{"value":1234,"type":"Integer"},{"value":"example string","type":"String"},{"value":true,"type":"Boolean"}]

Update
Here is one way how you could use custom deserializer and default one for every other field:
private static class MySerializer extends JsonSerializer<Example> {
    private static final ObjectMapper internalMapper = new ObjectMapper();

    @Override
    public void serialize(Example value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        ObjectNode node = internalMapper.valueToTree(value);

        if (value.getType().equals("String")) {
            node.put("value", value.getValue());
        } else {
            node.putRawValue("value", new RawValue(value.getValue()));
        }

        gen.writeObject(node);
    }
}

Will need to have @JsonIgnore in your public String getValue()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Modify Openbox key-bindings from commandline I am using the LXDE desktop environment, which is based on Openbox. I know how to change the key-bindings by editing my ~/.config/openbox/lxde-rc.xml, e.g.:
<keybind key="A-F11">
  <action name="ToggleFullscreen"/>
</keybind>

However, I need to make a non-persistent change, which will only be effective for the current session. And I need to make this change from the command line, without editing the XML file.
Is that possible?

A: here's a solution with bash, a fiddly language to write !
 #!/usr/bin/bash

 RCXML='rc.xml'

 find=$(cat $RCXML | grep -i -B 1 $1 | head -2)

 editkeys=$(cat $RCXML | grep -i -B 1 $1 | head -1)

 echo ''
 echo '  FOUND THE FOLLOWING SHORTCUT:'
 echo " ${find}"
 echo ''
 echo '  EDITING ABOVE KEYBIND TO:'
 echo "     <keybind key=\"$2\">"
 echo ''
 echo '  HIT ENTER TO CONFIRM.'
 read y

 if [ -z $y ]; then
     sed -i "s/$editkeys/\ \ \ \ <keybind key=\"$2\">/g" $RCXML
 fi

example of use:
 bash rcedit.sh ToggleShowD C-S-u

note: if you have the same keybinding for two different things, it uses the last one in the file. and this script edits the first one it finds by action name e.g. toggledesktop. but obviously you could edit it to find by keybinding, though keybindings are obviously less likely to be unique
the script needs to be in the same folder as the rc.xml unless you specify the full path in the RCXML variable, and note that globbing/tilda doesn't work in a variable
also, if you want to edit custom made shortcuts, which include the extra line:
 <action name="Execute">

you will have to adjust the bash script to include that extra line:
 find=$(cat $RCXML | grep -i -B 2 $1 | head -3)
 editkeys=$(cat $RCXML | grep -i -B 2 $1 | head -1)

if you want to edit mousekey shortcuts you'll have to do alot more editing
i tried for a little while to create something that appreciates the XML format more, with ruby, though the fact that the action name entry is nested inside the keybind key, is kind of the wrong way round to code an easy solution. also, the rc.xml file is packed with comment lines, which confused the two ruby XML modules i tried. but if you strip those out, you might be able to make something in ruby.
you could also append the following lines to .bashrc
 alias backuprcxml="~/.config/openbox/lxde-rc.xml > ~/.config/openbox/lxde-rc.xml.backup"
 alias restorercxml="~/.config/openbox/lxde-rc.xml.backup > ~/.config/openbox/lxde-rc.xml"

so then run this once to create a backup:
 backuprcxml

then add the following line to: ~/.config/openbox/autostart
 ~/.config/openbox/lxde-rc.xml.backup > ~/.config/openbox/lxde-rc.xml

A: When I used openbox a few years ago I found OBHotkey helpful. There's a command line interface and a tray icon as well.
I can't remember if I had to pair this with xdotool to get what I wanted out of it, but you should be able to make it work pretty easily.


text:
Q: concatenating multiple rows in 1 element separated by "," in R I have a data like this:
    date      id      product
29-01-16    1       a
29-01-16    1       b
29-01-16    1       c

I have created uniq_id as id_date. I want the output like
uniq_id       products
1_29-01-16    a,b,c


text:
Q: coding matrix of child elements in php Given values of variables $n, $m and $gap.
I want to display a matrix of equal red rectangles, having dimensions of $m rows and $n columns. Vertical and horizontal spaces between the rectangles will be $gap percent of the parent element's width and height respectively. Same size will have the margins of the matrix to the parent's edge.
For example for $n=2 and $m=3 this is the desired outcome:

Here is my code:
<?php
$n=2; //axis x
$m=3; //axis y
$gap=10% //percent of the parent's dimension

$childwidth=round((100-$gap*($n+1))/$n);
$childheight=round((100-$gap*($m+1))/$m);

?>

<!DOCTYPE html>

<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hey I am a title</title>

e

r

Could I please have an advice how to finish it? Thank you.
I work with percentages of the parent element. If it would be necessary to work with pixels instead, I have this code that enables to get window dimension into a php variable (window=parent in my case).

<?php
echo "inner: ";
echo $_COOKIE['window_width']."x";
echo $_COOKIE['window_height'];
?>

A: Seems to me that all you need is a fairly straightforward css grid (using display: grid and gap and the like).
Here's some examples on how to use it.


text:
Q: Simplest way to disable button on submission of a form? I've been trying to find the "right" way to prevent double submits of forms.  There are lots of related posts on SO but none of them hit the spot for me.  Two questions below.
Here is my form
<form method="POST">
    <input type="text" name="q"/>
    <button class="once-only">Send</button>
</form>

Here is my first attempt to disable double submits:
$(document).ready(function(){
    $(".once-only").click(function(){
        this.disabled = true;
        return true;
    });
});

This is the approach suggested here: Disable button after post using JS/Jquery. That post suggests the submitting element must be an input rather than a button, but testing both makes no difference.  You can try it yourself using this fiddle: http://jsfiddle.net/uT3hP/
As you can see, this disables the button, but also prevents submission of the form.  In cases where the submitting element is a button and an input element.
Question 1: why does this click handler stop submission of the form?
Searching around some more I find this solution (from Why doesn't my form post when I disable the submit button to prevent double clicking?)
if($.data(this, 'clicked')){
    return false;
} else{
    $.data(this, 'clicked', true);
    return true;
}

You can play with this using this fiddle: http://jsfiddle.net/uT3hP/1/
This does work, but...
Question 2:  Is this the best we can do?
I thought this would be an elementary thing.  Approach 1 does not work, approach 2 does, but I don't like it and sense there must be a simpler way.

A: Simple and effective solution is
<form ... onsubmit="myButton.disabled = true; return true;">
    ...
    <input type="submit" name="myButton" value="Submit">
</form>

Source: here

A: Similarly Ive seen a few examples, this one allows you to alter how long the button is disabled for, through timeout. It also only triggers on a form submit rather than on the buttons click event, which originally caused me a few issues.
    $('form').submit(function () {
        var button = $('#button');
        var oldValue = button.value;
        var isDisabled = true;

        button.attr('disabled', isDisabled);

        setTimeout(function () {
            button.value = oldValue;
            button.attr('disabled', !isDisabled);
        }, 3000)
    });

A: You can use jQuery's submit(). In this case, it should look something like this:
$('form').submit(function(){
    $(this).children('input[type=submit]').prop('disabled', true);
});

Here is a working jsFiddle (made by Mike) - http://jsfiddle.net/gKFLG/1/.
If your submit-button is not a direct child of the form-element you will need to replace children with find. Additionally, your submit-button may also be a button element instead of an input element. E.g. This is the case if you are using Bootstrap horizontal forms. Below is a different version of the snippet:
$('form').submit(function(){
    $(this).find('button[type=submit]').prop('disabled', true);
});

Demo jsFiddle - http://jsfiddle.net/devillers/fr7gmbcy/

A: You could try using the following code:
$(document).ready(function(){
   $(".once-only").click(function(){
      this.submit();
      this.disabled = true;
      return true;
   });
});

A: This should help:
<form class="form-once-only" method="POST">
    <input type="text" name="q"/>
    <button type="submit" class="once-only">Send</button>
</form>

Javascript:
$(document).ready(function(){
    $("form.form-once-only").submit(function () {
        $(this).find(':button').prop('disabled', true);
    });
}


text:
Q: Escape XML from database for output I'm trying to create a zend_form using XML, the passed XML includes all the tags so I can't use htmlspecialchars() because the tag < > would be encoded which I dont want.  Is there any easy way to encode just elements that are text values of the tags (the content between tags)?
$xml = sprintf('<?xml version="1.0" encoding="UTF-8"?><form><localhost><formmanager><formpage><elements>%s</elements></formpage></formmanager></localhost></form>',
                                $r['form_template']);
$config = new Zend_Config_Xml($xml, 'localhost');
$form = new Zend_Form($config->formmanager->$formName);

An extract of the xml saved on the DB :
<questionTechnicalServices>
<type>MultiCheckbox</type>
<options>
<class>rule2 standard basic2 starter business spotlight</class>
<label>Technical Services</label>
<multioptions>
<item-ContractLaboratoryandtestingServices>Contract Laboratory and testing Services</item-ContractLaboratoryandtestingServices>
<item-ContractRDDesignandEngineering>Contract R&D, Design and Engineering</item-ContractRDDesignandEngineering>
<item-ContractSterilization>Contract Sterilization</item-ContractSterilization>
<item-CoilingRespoolingWinding>Coiling/Respooling/Winding</item-CoilingRespoolingWinding>
<item-OthersTechnicalServices>Others</item-OthersTechnicalServices>
</multioptions>
</options>
</questionTechnicalServices>

The & from R&D, needs to be changed to & as would any > or < etc.
Regards,

A: The XML saved in the DB is invalid. The element values should be escaped before they are stored. Not doing that causes exactly the problem you have now.
However, you may be able to correct it by loading it into DOM as HTML and saving it back to a string. Although since it is already invalid, there is no guarantee that any parser will do what you want it to.


text:
Q: Set of limit points of continuous functions Let $x_0$ be an accumulation point of the set $D \subset \mathbb{R}$. We say that $y$ is a limit point of a function $f:D \rightarrow \mathbb{R}$ in $x_0$ iff there exists a sequence $(x_n)$, where $x_n \in D\setminus \{x_0\}$ for $n\in \mathbb{N}$ and $x_n \rightarrow x_0$, such that $y=\lim_{n\rightarrow \infty} f(x_n)$.
I don't know how to prove the following lemma:
If $f: (0,c) \rightarrow \mathbb{R}$ be continuous  then the set of all limits points of $f$ in $0$ is the interval                 $$[\liminf_{x\rightarrow 0}f(x), \limsup_{x\rightarrow 0}f(x)].$$

A: Note: I assume you require that $x_n\to x_0$ in your definition, otherwise this lemma is false.
Suppose $y$ is a limit point of $f$ in $0$, so we have a sequence $(x_n)$ in $(0,c)$ such that $x_n\to x$ and $f(x_n)\to y$. Then
$$\liminf\limits_{n\to\infty} f(x_n)=y=\limsup\limits_{n\to\infty} f(x_n)$$
so we have that
$$\liminf\limits_{x\to 0} f(x)\leq \liminf\limits_{n\to\infty} f(x_n)=y=\limsup\limits_{n\to\infty} f(x)\leq \limsup\limits_{x\to 0} f(x)$$
by definition. Thus $y\in [\liminf\limits_{x\to 0} f(x),\limsup\limits_{x\to 0} f(x)]$.
On the other hand, suppose $y\in [\liminf\limits_{x\to 0} f(x),\limsup\limits_{x\to 0} f(x)]$. Take sequence $(x_n)$ and $(x_n')$ in $(0,c)$ converging to $0$ such that $\lim\limits_{n\to\infty} f(x_n)=\liminf\limits_{x\to 0} f(x)$ and $\lim\limits_{n\to\infty} f(x_n')=\limsup\limits_{x\to 0} f(x)$. If $y$ is either $\liminf\limits_{x\to 0} f(x)$ or $\limsup\limits_{x\to 0} f(x)$ we are done. Otherwise, we have some $N$ such that
$$n\geq N\implies f(x)<y<f(x_n')$$
so by the Intermediate value theorem we have some $y_n$ between $x_n$ and $x_n'$ such that $f(y_n)=y$. Since $x_n\to 0$ and $x_n'\to 0$ it follows that $y_n\to 0$, and clearly $f(y_n)\to y$, thus $y$ is a limit point of $f$ in $0$.

A: The idea behind "why this lemma is morally true" is because it is trivial in the case where $f(x) \to C$ when $x \to 0$, and because if the limit $\lim_{x \to 0} f(x)$ doesn't exist, since the function is continuous, the function must be going back and forth between the sequence going towards the $\limsup$ and the other one going to the $\liminf$. So here's the idea :
I'll cover the (hard part of the) case where $\liminf < \limsup$. Choose $\liminf < \lambda < \limsup$. By assumption there exists $(y_n)$ such that $f(y_n) \to \liminf$ and $(z_n)$ such that $f(z_n) \to \limsup$. Now without loss of generality we can assume that $y_1 > z_1 > y_2 > z_2 > \dots > y_n > z_n > y_{n+1} > \dots$ since you can only take appropriate subsequences of your original sequences. Now if $N$ is large enough we know that for $n > N$ we have $f(y_n) < \liminf + \varepsilon$  and that $f(z_n) > \limsup - \varepsilon$.
Say we took $\varepsilon$ such that $\liminf + \varepsilon < \lambda < \limsup - \varepsilon$. By the mean value theorem this means there exists $z_n < c_n < y_n$ such that $f(c_n) = \lambda$. Letting $n \to \infty$ we obtain the appropriate sequence $c_n$.
Hope that helps,


text:
Q: In regex, what does [\w*] mean? What does this regex mean?
^[\w*]$

A: Quick answer: ^[\w*]$ will match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (_) or an asterisk (*).
Details:

*

*The "\w" means "any word character" which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_)

*The "^" "anchors" to the beginning of a string, and the "$" "anchors" To the end of a string, which means that, in this case, the match must start at the beginning of a string and end at the end of the string.

*The [] means a character class, which means "match any character contained in the character class".

It is also worth mentioning that normal quoting and escaping rules for strings make it very difficult to enter regular expressions (all the backslashes would need to be escaped with additional backslashes), so in Python there is a special notation which has its own special quoting rules that allow for all of the backslashes to be interpreted properly, and that is what the "r" at the beginning is for.
Note: Normally an asterisk (*) means "0 or more of the previous thing" but in the example above, it does not have that meaning, since the asterisk is inside of the character class, so it loses its "special-ness".
For more information on regular expressions in Python, the two official references are the re module, the Regular Expression HOWTO.

A: As exhuma said, \w is any word-class character (alphanumeric as Jonathan clarifies).
However because it is in square brackets it will match:

*

*a single alphanumeric character OR

*an asterisk (*)

So the whole regular expression matches:

*

*the beginning of a
line (^)

*followed by either a
single alphanumeric character or an
asterisk

*followed by the end of a
line ($)

so the following would match:
blah
z  <- matches this line
blah

or
blah
* <- matches this line
blah

A: \w refers to 0 or more alphanumeric characters and the underscore. the * in your case is also inside the character class, so [\w*] would match all of [a-zA-Z0-9_*] (the * is interpreted literally)
See http://www.regular-expressions.info/reference.html
To quote:

\d, \w and \s ---  Shorthand character classes matching digits, word characters, and whitespace. Can be used inside and outside character classes.

Edit corrected in response to comment

A: From the beginning of this line, "Any number of word characters (letter, number, underscore)" until the end of the line.
I am unsure as to why it's in square brackets, as circle brackets (e.g. "(" and ")") are correct if you want the matched text returned.

A: \w is equivalent to [a-zA-Z0-9_] I don't understand the * after it or the [] around it, because \w already is a class and * in class definitions makes no sense.

A: As said above \w means any word. so you could use this in the context of below
view.aspx?url=[\w]

which means you can have any word as the value of the "url=" parameter


text:
Q: How to remove lower margin from UI-Boostrap Angular Tab directive? The ui.bootstrap.tabs directive found here has an inherit margin before it displays it's content.

HTML:
<uib-tabset active="activeJustified" justified="false" id="tabSet" style="background-color: red">
    <uib-tab index="0" heading="Assessment" class="uib-tab">

TEST

    </uib-tab>
    <uib-tab index="1" headin[![enter image description here][2]][2]g="SJ" class="uib-tab"></uib-tab>
    <uib-tab index="2" heading="Long Justified" class="uib-tab"></uib-tab>
</uib-tabset>

The <uib-tabset> has background-color: red to show this margin.
My CSS won't stop it. (Perhaps it's a property I don't know of?)
.uib-tab {
margin: 0px;
padding: 0px;
}

.uib-tabset {
margin: 0px;
padding: 0px;
}

Any ideas to try? Thank you!

A: If the css you are trying to apply is on the correct element, I would suggest increasing the specificity of the selector such as "#tabSet .uib-tab", or use !important.

A: I think the problem is the style applied to the p element in the tab content.  The tab-content and tab-pane classes (which are applied to the elements wrapping the tab content) have no margin or padding styles.  This plunk demonstrates the effect you are seeing.  The code I used to prove this is:
<uib-tabset active="active" style="background-color: red;">
  <uib-tab index="0" heading="Tab 1">

Tab 1 content

  </uib-tab>
  <uib-tab index="1" heading="Tab 2">

Tab 2 content

  </uib-tab>
  <uib-tab index="3" heading="Tab 3">

Tab 3 content

  </uib-tab>
</uib-tabset>


text:
Q: Inequality within complex I step with a inequality and would like to know if it is truth...
$||(a_1-a_2)^2+i(b_1-b_2)^2||\leq ||a_1^2+ib_1^2||+||a_2^2+ib_2^2||,\quad \forall a_1,a_2\in\mathbb{R}$.
I tried to prove it but couldn't. Any help will be appreciated.

A: It's wrong.
Try $a_1=b_1=1$ and $a_2=b_2=-1$.


text:
Q: .sh file works in terminal but not in python script (rclone w/ Raspberry Pi) I'm having trouble running a .sh file in python.  When I type in the location of the .sh file (/home/pi/file/script.sh) the script runs perfectly.
I'm trying to run this script in my python2 script and I've done the following methods:
subprocess.Popen(['bash', 'location of .sh'])
subprocess.call(['location of .sh'])
os.popen(['location of .sh'])

When I run the python script, I get a prompt from rclone saying "Command sync needs 2 arguments maximum"
My .sh file just includes:
#!/bin/sh
sudo /usr/local/bin/rclone -v sync /home/pi/some_project_data remote:rclone --delete-before --include *.csv --include *.py

I'm not sure how running the .sh file on terminal works fine, but this error pops up when I'm trying to run the .sh file using Python.

A: Your script fails whenever you run it in a directory containing 2 or more .csv or .py files. This is true for terminals as well as via Python.
To avoid that, quote your patterns so the shell doesn't expand them:
#!/bin/sh
sudo /usr/local/bin/rclone -v sync /home/pi/some_project_data remote:rclone \
                           --delete-before --include "*.csv" --include "*.py"

A: Please try:
os.popen('bash locationof.sh')

ex:
os.popen('bash /home/script.sh')

That worked on my machine. If you place square brackets around the string then python assumes it is a list and popen doesnt accept a list, it accepts a single string.
If the script doesnt work, then this won't fix that, but it will at least run it. If it still doesnt work, try running the script with something like
touch z.txt

and see if z.txt appears in the file explorer. If it does, then your .sh file has a problem.


text:
Q: Python Script in WebApp won't run on Amazon Elastic Beanstalk So I recently deployed a NodeJS web app to Amazon Elastic Beanstalk. However, the python script that is supposed to run on deployment doesn't run? When I every I run my app locally the script runs, but for some reason this isn't the case on Bean Stalk. The logs also don't indicate any type of error on the Python Script. Below is the code I used to run my python script in my app.js file:
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["bitmexbot.py"]); // run python script

Any help would be appreciated.


text:
Q: How to deactivate kernel modules "firewire_ohci" and "firewire_core"? My computer currently uses the kernel modules firewire_ohci and firewire_core. I don't want them.
I blacklisted them, but they still load after any reboot. How can I deactivate them?

A: Did you rebuild:
sudo update-initramfs -k all -u && sudo reboot

If that doesn't work you should be able to disable them in GRUB.


text:
Q: Clearbox Radius attributes through SQL statement? I authenticate users through Radius, and I have the option to assign Radius attributes through SQL statements, but I can't for the life of me find any documentation on this. Anyone know the proper syntax?

A: Okay, I figured it out, and for anyone else who ends up having this problem:
Under the Authorization tab, in the Response List:
When adding an attribute from an SQL query, the first selected variable from the query is the attribute and the second is the value.
ex.
SELECT 'attribute', value FROM table WHERE username ='$u'
For a more specific example:
SELECT 'Ascend-Data-Rate', hsbrate.rate FROM hsbrate, customer WHERE  customer.id = hsbrate.id AND username='$u'
This statement will basically pass the following:
Ascend-Data-Rate=1024000
(assuming 1024000 is the rate value stored in the database)
NOTE: $u is an understood variable in Clearbox Radius that denotes the current-active user being authenticated.

A: kylex, try these links and see if they help. Specifically the first one
http://www.xperiencetech.com/forum/topic.asp?TOPIC_ID=97
http://www.xperiencetech.com/forum/topic.asp?TOPIC_ID=62


text:
Q: Alfresco Java backed webscript for creating folders does not create folders I am working on a Java backed webscript for Alfresco that needs to create a folder structure based on the path that is sent to it. Some of the folders that have been sent may already exist and some may not. This is the code I've got:
for( int i = 0; i < folderPathParts.length; i++){

    createdFolder = serviceRegistry.getFileFolderService().searchSimple(contextFolder, folderPathParts[i]);

    if( createdFolder == null){
        try{
            FileInfo subfolderInfo = serviceRegistry.getFileFolderService().create(contextFolder, folderPathParts[i], ContentModel.TYPE_FOLDER);
            contextFolder = subfolderInfo.getNodeRef();
        }catch(FileExistsException fee){
            contextFolder = serviceRegistry.getFileFolderService().searchSimple(contextFolder, folderPathParts[i]);
        }
    }
}

Debugging the script I can see that the new node refs are created, but there is nothing actually being created when I go to share.
I read that I might need to use transactions since this script will be accessed by multiple threads, and I have tried using the retrying transaction helper but I have the same result.


text:
Q: Different Equality[DenseVector] types for different numerical tolerances I've written a scalactic equality provider for DenseVectors that uses the breeze closeTo method to check if each double in the vector is close enough.
 implicit val vectorEquality: Equality[DenseVector[Double]] = new Equality[DenseVector[Double]] {
    def areEqual(a: DenseVector[Double], b: Any): Boolean = {
      b match {
        case b: DenseVector[Double] => (a.valuesIterator zip b.valuesIterator).forall(p =>
          closeTo(p._1, p._2))
        case _ => false
      }
    }

Is there any way to control the closeness of the closeTo when I use this equality in my test? Sometimes I would like "should be equal" in the test to mean equality to 2 decimal places, and other times I would like a more stringent requirement.

A: Yes, you can control the closeness since closeTo has a third parameter called tolerance defined in Implicits.
class RichDouble(x: Double) {
    def closeTo(y: Double, tol: Double=1E-5) = {
      (math.abs(x - y) / (math.abs(x) + math.abs(y) + 1e-10) < tol);
    }
    def isDangerous = x.isNaN || x.isInfinite
}

Example can be found in a test for Chi Squared distribution
def paramsClose(p: Double, b: Double) = breeze.numerics.closeTo(p, b, 5E-2)


text:
Q: Google map API2 addListener i have store all the markers in a makers array, and when i click on the marker i would like to retrieve the index from the array. however this doesn't return me with the correct index, instead it return the max index. Any suggestion?
for(var i = 0; i<options.length; i++){
marker[i] = new GMarker(new GLatLng(options[i].latitude, options[i].longitude), markerIcon);
//addListener(i, options[i].name);
GEvent.addListener(marker[i],"click", function(e) {
alert(i);
});
map.addOverlay(marker[i]);
}

A: The problem is that the variable i is not being captured in a closure, like you would expect. So, all listeners are capturing the same i (which is eventually incremented to options.length). You need to wrap the marker/listener creation in its own function.
var makeNewMarker = function(i) {
  var marker = new GMarker(
      new GLatLng(options[i].latitude, options[i].longitude),
      markerIcon);
  GEvent.addListener(marker[i],"click", function(e) {
    alert(i);
  });
};
for (var i = 0; i < options.length; ++i) {
  marker[i] = makeNewMarker(i);
  map.addOverlay(marker[i]);
}

You could make the makeNewMarker function an anonymous function inside the for-loop, but this way seems more readable.


text:
Q: Css show and hide working in all browsers but Safari. how can i fix this? I have a trigger toggle that shows or hides elements, its working well on chrome, but for some reason in safari, it wont work, any ideas?
   see more -->
   hide

      hidden divs

css
      .show:focus + .hide {display: inline; }
                .show:focus + .hide + .hidden-stuff {display: block;}

A: You can fix this by adding tabindex attribute.
see more -->

You can read more about this here.


text:
Q: call razor page from mvc controller I want to reuse my razor pages instead of having multiple similar views in mvc, I don't want to use a partial view. Thus I want to pass a parameter from a controller to razor page.
In the razor page my input will be something like below
public async Task OnGet(int? x,int?y)

How can i call this function/razor page from my mvc controller?

A: Controller
public class HomeController : Controller
 {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return RedirectToPage("/index", new { name = "Arun Kumar"});
        }
 }

Razor Page:
public class IndexModel : PageModel
 {
        public string FullName { get; set; }

        public void OnGet(string name)
        {
            FullName = name;
            ViewData["heading"] = "Welcome  to ASP.NET Core Razor Pages !!";

        }
 }

Razor Page View:
@page
@model RazorMVCMix.Pages.IndexModel

@ViewData["heading"]

@Model.FullName

Output here:

A: Controllers are just classes you can call action like methods from another controller.
https://softwareengineering.stackexchange.com/questions/264392/is-a-good-practice-to-call-a-controller-function-from-another-controller
How to call another controller Action From a controller in Mvc
https://forums.asp.net/t/1645726.aspx?how+to+call+a+controller+action+from+another+controller

A: In your controller action, use RedirectToPageResult:
return new RedirectToPageResult("/YourRazorPage", new {x = 1, y = 2});


text:
Q: Unable to make google login with express - nhandled rejection Error: passport.initialize() middleware not in use I'm receiving this error message when trying to use passport with google:
Unhandled rejection Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn

This is google function inside passport.js:
passport.use('google', new GoogleStrategy({
    clientID        : process.env.GOOGLE_CLIENTID,
    clientSecret    : process.env.GOOGLE_CLIENTSECRET,
    callbackURL     : process.env.GOOGLE_CALLBACKURL,
    passReqToCallback: true,
},
    function(req, token, refreshToken, profile, done) {

        process.nextTick(function() {

            console.log(profile);

            var values = {
                where: { google_id: profile.id },
                defaults: {google_id: profile.id, name: profile.displayName}
            };

            User.findOrCreate(values)
            .spread(function(user, created) {

                return done(null,user);
            });
        });
    }
));

This is the full error:
Unhandled rejection Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn
(/Users/filipeferminiano/MEGA/altcoin-site/node_modules/passport/lib/http/request.js:46:34)
    at Strategy.strategy.success (/Users/filipeferminiano/MEGA/altcoin-site/node_modules/passport/lib/middleware/authenticate.js:248:13)
    at verified (/Users/filipeferminiano/MEGA/altcoin-site/node_modules/passport-oauth2/lib/strategy.js:177:20)
    at /Users/filipeferminiano/MEGA/altcoin-site/config/passport.js:168:13
    at runCallback (timers.js:672:20)
    at tryOnImmediate (timers.js:645:5)
From previous event:
    at /Users/filipeferminiano/MEGA/altcoin-site/config/passport.js:166:6
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

How can I fix this?

A: app.js
var express=require('express');
var app=express();
var port=process.env.PORT || 3000;
var mongoose=require('mongoose');
var passport=require('passport');
var session = require('express-session');

mongoose.connect('mongodb://localhost:27017/myapp');
require('./config/passport')(passport);
var User = require('./models/user');

app.set('view engine', 'ejs');
app.use(session({ secret: '1234567' ,
       saveUninitialized: true,
       resave: true}));
app.use(passport.initialize());
app.use(passport.session());

  app.get('/', function(req, res) {
        res.render('index.ejs');
    });

app.get('/profile/:provider', isLoggedIn, function(req, res) {
console.log(req.user);
    res.render('profile.ejs', {
        provider:req.params.provider,
        user : req.user // get the user out of session and pass to template
    });
});

app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));

     app.get('/auth/google/callback',
                passport.authenticate('google', {
                        successRedirect : '/profile/google',
                        failureRedirect : '/'
                }));

   // route for logging out
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}

app.listen(port);

passport.js
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

var User       = require('../models/user');

module.exports = function(passport) {

    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

  passport.use(new GoogleStrategy({

        clientID        : 'clientID',
        clientSecret    : 'clientSecret',
        callbackURL     : 'http://localhost:3000/auth/google/callback',

    },
    function(token, refreshToken, profile, done) {
    process.nextTick(function() {
             User.findOne({ 'google.id' : profile.id }, function(err, user) {
                if (err)
                    return done(err);
                if (user) {
              return done(null, user);
                } else {
                    var newUser          = new User();
                    newUser.google.id    = profile.id;
                    newUser.google.token = token;
                    newUser.google.name  = profile.displayName;
                    newUser.google.email = profile.emails[0].value; // pull the first email

                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }
            });
        });

    }));

};


text:
Q: Rails/Ruby NoMethodError: undefined method `order' for # I want to execute the following:
case 1:
x = Group.all[0].people
x.class
=> Array
x.order

fine.
:)
case 2:
y = Person.all
y.class
=> Array
y.order
=> NoMethodError: undefined method `order' for #<Array:0x718c278>

:(
Both x and y contain the same type of item -  bunch of Person models.
Why can't ruby order the array?
Thanks in Advance

A: Because in the Rails 3 the method all(GitHub) returns an array. It can't be ordered with order method.
Although you may use the sort method do to the ordering.
The people returns an ActiveRecord::Relation object that can then be further scoped.
Fortunatelly the ActiveRecord::Relation have the to_a method that will return an array that you may sort.

A: OK, so Group.all.first.person does not return an Array. It looks like it does, but really it's part of ActiveRecord AREL that allows you to chain together relationships and scopes.
When you call #order on the Group.all.first.person you are really calling the "order" scope, telling the query to order person on nothing.
You will get the same error if you call
Group.all.first.person.all.order
  NoMethodError: undefined method `order' for #<Array:0x007fe7dd03ff08>

It's the "#all" that matters.
In ruby, there is no "order" method. There is a sort and sort_by


text:
Q: Could I have problems if I add elements to hashset from a parallel.Foreach? I have a POCO entity that has a hashset as navigation property. In some cases I need to add to this collection new elements, so I was thinking in something like that:
MyType myPocoEntity = new MyType();
Parallel.ForEach(myList,
    (iterator, state) =>
{
    myPocoEntity.MyCollection.Add(new MyType(){ Id = iterator.Id });
}

The idea is for each element in my list, create a new object that I have to add to the hashset of my POCO entity.
Just is an add operation, but I don't know if although it is only an add operation, if I could can problems, or if I should use first a concurrent collection and later pass the elements to the navigation property, but in this case I guess it would be better use a for loop and not parallel.
So I would like to know if it is a good idea to use a parallel foreach or not.
Thanks.

A: It's my assumption that switching thread contexts and synchronization is more expensive than HashSet<T>.Add() call even for large sets added from for loop. However, the fastest way to add new members to collections is always to use HashSet<T>.AddRange operation and due to that I would optimize code even further by creating new collection if it would be significantly smaller than target collection and than I would be adding it with single call to HashSet<T>.AddRange.


text:
Q: How to implement asynchronous inside d3 I want to change the color of the circles after a period of time. I tried to use setTimeout, but it doesn't work. Is there any way to solve the problem?
var circles = svg.selectAll("circle").data(data)
                .enter().append("circle")
                .attr("r", "10")
                .attr("fill","lightblue")

circles.attr('fill',function(){
            setTimeout(function(){return "red"},2000)
         })

A: Gerardo's comment explains why using setTimeout in the way that you did does not work and presents the alternative approach of using d3.transition.
StackSlave's comment explains how to correctly use setTimeout to solve the problem.
See the example below for approaches to solving your problem.
const data = [10, 15, 20, 30, 35];

const radius = 10; // px
const yPos = 35; // px

const svg = d3.select('svg');

const circles = svg.selectAll("circle").data(data)
  .enter().append("circle")
  .attr("r", radius)
  .attr("transform", function(d, i) {
     return `translate(${(i+1) * 3 * radius}, ${yPos})`;
   })
   .attr("fill", "lightblue");

// using setTimeout
setTimeout(function() {
  circles.attr("fill", "red");
}, 2000);

// using d3
circles
  .transition()
  .duration(2000)
  .ease(() => 0) // disable fading
  .style("fill", "red");

// using d3 - recommended (see Gerardo's comment below)
circles
  .transition()
  .duration(0)
  .delay(2000)
  .style("fill", "red");

Checkout the d3.transition docs to learn more.


text:
Q: How to skip a loop in kdb? I have the following
mydata:raze {[x]

L: select from ....

if[count[L] <= 20; continue]

} peach vals;

and I am trying to add an if-statement that would skip a particular entry in vals if the condition is not met. continueworks well in matlab, but, I am not sure of the corresponding syntax in kdb. Thank you.

A: You can use an explicit return (:) in the if statement to return an empty list for those cases. Something like:
mydata:raze {[x]

L: select from ....

if[count[L] <= 20; :()]

} peach vals;


text:
Q: WSH / JScript to start and stop services based on time? Just looking to see if my assessment is correct on the easiest way to do this.
Background: we have a software suite which we're running via services. The services need to be shut down between 10pm and 6am. We also need to check every 10 min to recover the services in case they've gone down when they were supposed to be up, and in case we restarted during a time when they'd need to be shut down.
Choices: I'm thinking a scheduled task that runs a WSH / JScript every 10 minutes. The pseduo code for the JScript would be something like:

*

*Get current time

*If the current time is after 10pm but before 6am

*

*call EnsureDowntime()

*Else

*

*call EnsureUptime()

*EnsureDownime():

*

*If the services are running, stop them

*EnsureUptime():

*

*If the services are not running, start them

Questions:

*

*Is Scheduled Task / WSH / JScript the best way to do this, or at least an acceptable way?

*is calling a new Date() and using .getHours() the best why to find the time?

*Does my pseudo-code look like the best way to approach this?

*how can I detect the state of a service (running / non-running)?

*

*or in this case, should I just start / stop the services regardless of state? If there are no errors and it won't re-start a service that's already started, I imagine I could just use "net start" and "net stop".

Thanks in advance for any help you can give!

A: Figured it out!
Solution Walkthrough

*

*Firstly, create a scheduled task and point it to a .bat file (pointing it directly to a .js will not work, I discovered).

*In the batch file point to your .js file to run it (for example, mine was located in "D:\BF_Ping.js"

BF_Ping.bat:
D:
cd\
BF_Ping.js

*

*Next, create your JavaScript file. My fully commented file is below for reference:

BF_Ping.js:
//*** Time Variables ***//
var UptimeBeginsAtHour = 6;     // Hour at which the services should be started
var UptimeEndsAtHour = 22;      // Hour at which the services should be ended

//*** Flags ***//
var KILL_FLAG = FindFile("C:\\BF_KILL.txt"); // If this flag is true, services will be shut down and not started.
var LAZY_FLAG = FindFile("C:\\BF_LAZY.txt"); // If this flag is true, nothing in the script will run.

if (KILL_FLAG == true)
{
    StopBizFlowServices();
}

if (KILL_FLAG == false && LAZY_FLAG == false)
{
    DetectTimeAndProcess(UptimeBeginsAtHour, UptimeEndsAtHour);
}

/***
 * DetectTimeAndProcess(startAtHour, stopAtHour):
 * Starts or stops BizFlow Services based on uptime variables.
 *
 * ---Arguments---
 * startAtHour  Hour after which services should be started (defined by variable in main code)
 * stopAtHour   Hour after which services should be started (defined by variable in main code)
 *
 * ---Returns---
 * None (void)
 *
 * ---Called By---
 * Main code.
 */

function DetectTimeAndProcess(startAtHour, stopAtHour)
{
    var currentTime = new Date();
    var hour = currentTime.getHours();      // Returns Hour in 24-hour format

    if (hour > startAtHour && hour < stopAtHour)
    {
        StartBizFlowServices();
    }
    else
    {
        StopBizFlowServices();
    }
}

/***
 * StartBizFlowServices():
 * Starts BizFlow Services using "net start" and the service name.
 *
 * --- Arguments ---
 * None.
 *
 * --- Returns ---
 * None (void)
 *
 * --- Called By---
 * DetectTimeAndProcess()
 */
function StartBizFlowServices()
{
    var objShell = WScript.CreateObject("WScript.Shell");

    objShell.Run("net start \"BizFlow Database Service\" ", 1, true);
    objShell.Run("net start \"BizFlow Main Service\"", 1, true);
    objShell.Run("net start \"BizFlow OLE-DB Service\"", 1, true);
    objShell.Run("net start \"BizFlow PKI Service\"", 1, true);
    objShell.Run("net start \"BizFlow Queue Service\"", 1, true);
    objShell.Run("net start \"BizFlow Scheduler Service\"", 1, true);
}

/***
 * StopBizFlowServices():
 * Stops BizFlow Services using "net stop" and the service name.
 *
 * --- Arguments ---
 * None.
 *
 * --- Returns ---
 * None (void)
 *
 * --- Called By---
 * DetectTimeAndProcess()
 */
function StopBizFlowServices()
{
    var objShell = WScript.CreateObject("WScript.Shell");

    objShell.Run("net stop \"BizFlow OLE-DB Service\"", 1, true);
    objShell.Run("net stop \"BizFlow PKI Service\"", 1, true);
    objShell.Run("net stop \"BizFlow Queue Service\"", 1, true);
    objShell.Run("net stop \"BizFlow Scheduler Service\"", 1, true);
    objShell.Run("net stop \"BizFlow Main Service\"", 1, true);
    objShell.Run("net stop \"BizFlow Database Service\"", 1, true);

}

/***
 *
 * FindFile (filePath):
 * Searches for the existence of a given file path.
 *
 * --- Arguments ---
 * filePath     Full Path of file (including file name)
 *
 * --- Returns ---
 * true     if file is found
 * false    if file is not found
 *
 * --- Called By---
 * Main Code (while setting flags)
 */

function FindFile(filePath)
{

    var fso;  //For FileSystemObject
    fso = new ActiveXObject("Scripting.FileSystemObject");

    if(fso.FileExists(filePath))
    {
        return true;
    }
    else
    {
        return false;
    }
}

I'm actually a little proud of this one -- it ran without error the first time :)
Some Notes:

*

*Times are given in 24 hour format.

*Set the scheduled task to run every 5-10 minutes to ensure that the check is performed often.

*The services I use here are BizFlow services, a product that a client is using. You can change the names of the functions accordingly, of course.

*Note the escape characters for the quotes when running "net start" or "net stop" for the service name.

*Use the full service name, as it appears in services.msc.

Please let me know if you have any questions or comments on how I might improve the code!
Thanks,
--
Sean

A: You mentioned that:

... (pointing it directly to a .js will not work, I discovered)

That was something I'd run into as well when trying to run a WSH JS file from Task Scheduler in Windows 2003.  I found in WIn7, you could run it directly with just a reference to the .js file, but it failed to pass parameters at least to the script if run the same way in the 2003 Scheduler.
I did find a workaround that seems to work to avoid needing the stub batch file that you mentioned though: if you just prefix the .js file with 'WScript' (or 'CScript') -- no full path should be needed because those are in %WINDIR%\system32, then it seems to work for me including the .js file getting any parameters passed.


text:
Q: Retrieve posts of users I dont follow LeftJoin Sql I have 3 tables: Users, Community & Posts.
I want to retrieve posts of users that Joe dont follow (id_user=1)
Users
    id_user  |  name
       1        Joe
       2        Doe
       3        Moe
       4        Roe
       5        Clin

Community
  id_follower | id_followed
       1            3
       1            5

Posts
    id_post   | id_user | post
      24            4       hi
      25            5       hello
      26            1       how are you
      27            3       come on
      28            4       let go
      29            2       get out

What I'm expecting to retrieve is
      24            4       hi - by Roe
      28            4       let go  - by Roe
      29            2       get out  - by Doe

I tried this but not working
SELECT p*
FROM community as c
LEFT JOIN users as u ON u.id_user=c.id_followed
LEFT JOIN posts as p ON p.id_user!=c.id_followed
WHERE c.id_follower=1 AND u.id_user!=1

A: This should work:
select * from Posts
where id_user not in
(select id_followed from Community where id_follower = 1)

A: No point just giving an answer, lets step through the logic.  There are other methods of doing this, but since you asked left join I will do as left join.  Start at posts...
from posts p

lets then left join to community
left join community c on c.id_followed = p.id_user and ID_follower = 1

This now gives you a list of all posts along with a community id_followed record...if the record from community is null, then it's from a user joe does not follow.  Since we only want the records joe does not follow
where c.id_followed is null

We will add a join to users to grab the poster name and put it all together
from posts p
left join community c on c.id_followed = p.id_user and ID_follower = 1
left join users u on u.id_user = p.id_user
where c.id_followed is null

and finally put together the select line to get the fields you want, using concat to get the post by name format you want
select p.id_post, p.id_user,  concat(p.post  , ' by ', u.name)

put it together and run!

A: you  could use a inner join on a not in
select p.*
from  Posts p
inner join (
  select id_user form community
  where id_user  not in (
   select id_followed
   from community
   where id_follower =1
  )
) t  on p.id_user = t.id_user and p.id_user <>1


text:
Q: What is the meaning of "Rapidly improving rap sheet."? It's the drama dialogue and background is the police office.
The detective said like this about the suspect.

Name. Klaus Goedecke. Size twelve wide. Rapidly improving rap sheet. Recently made a sizable cash deposit

In this sentence, what is the meaning of "Rapidly improving"? I know rap sheet means criminal report.

A: You need to look at No. 2 definition of intransitive verb:

to make useful additions or amendments

A crime can't be a useful addition unless it is used in a sarcastic or ironic sense as TRomano commented.
"Improving" in the sentence could be replaced by "growing" or "increasing", but it won't have such a sarcastic or ironic sense.

A: The mention of "Rapidly improving" in a positive reference could mean:
Pardoned/ Exonerated/ Expungment of a crime from the rap sheet.


text:
Q: Fluid DIVS on HTML / CSS Layout This is the first time i'm trying to create a custom html page from scratch and I'm having some trouble :
This is what i want basically:

I want the site to automatically resize according to the window size - the first div bg should be full width and its inside should be fixed width (centered)
I first tried creating each divs manually - seems ok so far except the inside div inside the header i want to center
I'm really noob in css/html , so if there is any way to improve my code - please let me know
I tried several ways but keep getting stuck .
Tried:

*

*MaxDesign Article

*LayZilla

*CSS-Tricks Fluid
I was using the above as examples , but i kept getting stuck so i decided to start from zero
CSS
#body_wrapper {
    width:100%;
    background:white;
}
#header {
    width:100%;
    height:200px;
    background:red;
}
#header_inside {
    width:500px;
    height:180px;
    background:green;
}
#content {
    width:100%;
    height:600px;
    background:blue;
}
#footer {
    width:100%;
    height:200px;
    background:yellow;
}

HTML

A: To center a div, use: margin:auto;. So;
#header_inside {
   margin: auto;
   [ ... ]
}

A: Change  the css for header like this:
#header {
box-sizing: border-box;
padding: 10px 0;
width: 100%;
height: 200px;
background: red;
}
#header_inside {
margin: 0px auto;
width: 500px;
height: 180px;
background: green;
}

A: If responsive and resizing is your priorty try Twitter Bootstrap Css .
It works great for responsive features with the help of predefined classes itself.

A: I hope this is what you want ::
http://jsfiddle.net/rahulrulez/b4gWx/
Just add following properties to inner divs.. I have followed HTML5 convention and I recommend you to do so.
width:500px;
margin:0 auto;

After getting familiar with HTML and CSS enough.. I recommend you to kick start development with frameworks like Twitter Bootstrap or Zurb Foundation

A: The margin: auto solution should work.
You can also use text-align:
.outerDiv {
    width: 100%;
    text-align: center;
}

.innerDiv {
    width: 500px;
    text-align: left;
}

A: HTML

CSS
* {
    margin:0px;
    padding:0px;
}
#wrapper {
    width:100%;
    border:1px solid black;
    height:1000px;
}
body {
    width:100%;
    border:1px solid black;
    height:1000px
}
#header {
    width:100%;
    height:100px;
    border:1px solid red;
    display:block;
}
#logo {
    width:50%;
    margin:5px auto;
    border:1px solid red;
    height:50px;
    display:block;
}
#menu {
    width:100%;
    height:30px;
    border:1px solid blue;
    display:block;
}
#menuitems {
    width:50%;
    margin:5px auto;
    border:1px solid blue;
    height:15px;
    display:block;
}

#content {
    width:100%;
    height:800px;
    border:1px solid green;
    display:block;
}
#contents {
    width:50%;
    margin:15px auto;
    border:1px solid green;
    height:650px;
    display:block;
}

#footer {
    width:100%;
    height:60px;
    border:1px solid orange;
    display:block;
}
#footers {
    width:50%;
    margin:5px auto;
    border:1px solid orange;
    height:40px;
    display:block;
}

 Fiddle

A: Html

        <u1>

list items

your content follows here


text:
Q: Running a loop to check for multiple congruences I have the code for a loop to run. Right now it can check if a number is a square and at the same time check if it is congruent 0 mod 47. My questions is, how can I alter the code to see if it is congruent for more than one prime. SO for instance I would like it to check that a number is congruent, 0 mod 5, 0 mod 13 and 0 mod 17 all at once and only keep or print the numbers which are. I would try something like:
'Select[Range[10^7]^2, Divisible[7 # + 4, 5], Divisible[7 # + 4, 13], Divisible[7 # + 4, 17] &]'
but it just prints numbers most of which I am assuming do not satisfy the desired effect

A: To find solutions, for example, the code:
FindInstance[{n == a^2, 7 n + 4 == m, m == 5 b}, {n, m, a, b}, Integers]

returns {} to indicate no solutions. The alternative code
Reduce[{n == a^2, 7 n + 4 == m, m == 5 b}, {m}, Integers]

returns False similarly. Try variations of these codes depending on your needs.
However, both Reduce[] and FindInstance[] are not good with exponential equations.
For that, you can use some code
Select[2^Range[0, 20] - 1, Divisible[#, 5] && Divisible[#, 13] &]

which returns {0, 4095} and you can try variations of this.

A: For the question, expressed in a comment by argamon, of finding numbers of the form (4^n)-1 congruent to 0 mod 5, 0 mod 13, and 0 mod 17, please consider the function ChineseRemainder.
Block[{c},
   Flatten[Table[
      c = ChineseRemainder[{0, 0, 0}, {5, 13, 17}, m];
      If[c == m, m, {}],
      {m, Table[4^k - 1, {k, 1, 50}]}]]
]

{16777215, 281474976710655, 4722366482869645213695,
  79228162514264337593543950335}


text:
Q: Background image fixed to container edge Is it possible to have a body background image aligned to the edge of a container element?
Using boostrap 3, I want a background to the page that is fixed to a container edge, so when resizing, the background moves with the container (ie, in the example below, the background image centered over the container edge):

(source: nfx.nz)
Is this possible with a background image, or would I have to add a new absolutely positioned layer / or javascript...?

A: There are several solutions to your question, and it really depends on if you require dynamic sizing of the background. The example I have shown will animate the container dynamically, so you can see how it works.
Approach No. 1: Offset background position with known value
One is if you know the exact dimensions of the image, then you can simply position it negatively along the x-axis (i.e. moving it to the left) by half the width of the image. This is assuming that you are not dynamically sizing your background image:

* {
  margin: 0;
  padding: 0;
}
div {
  background-color: steelblue;
  background-image: url('http://placehold.it/400x200');
  background-repeat: no-repeat;
  background-position: -200px 0;
  width: 50%;
  margin: 0 auto;
  height: 500px;
  animation-name: pulse;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}
@keyframes pulse {
  0% {
    width: 50%;
  }
  50% {
    width: 100%;
  }
  100% {
    width: 50%;
  }
}

Background image dimension: 400x200

Approach No. 2: Use pseudo/dummy element
If your background size is dynamic (i.e. changes with the size of the container), you are better off using an absolutely positioned pseudo-element or a dummy element:

* {
  margin: 0;
  padding: 0;
}
div {
  background-color: steelblue;
  width: 50%;
  margin: 0 auto;
  height: 500px;
  animation-name: pulse;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  position: relative;
  overflow: hidden;
}
div::before {
  background-image: url('http://placehold.it/400x200');
  background-repeat: no-repeat;
  background-size: 100%;
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: -50%;
  right: 50%;
}
div > * {
  position: relative;
  }
@keyframes pulse {
  0% {
    width: 50%;
  }
  50% {
    width: 100%;
  }
  100% {
    width: 50%;
  }
}

Background image dimension: 400x200


text:
Q: How do I stop loading images in Junk mail folder in Mail.app 6.6 with Gmail I have setup Mail.app to use my Gmail account. Gmail has a spam filter that works excellent for me. But I sometimes check the Junk mailbox in Mail to see if something got there by accident.
When I go through the messages the images in those messages get loaded anyway as the message is placed by Gmail in the Spam folder (which is linked to the Junk mailbox) but Mail.app does not mark it as Junk and therefore loads the images.
If I manually mark the message as Junk, Mail stops loading the images.
How do I make Mail to mark the messages in Gmail's Spam folder to be marked as Junk, forcing it to not load the images?

A: You have to "map" the Gmail folders to match what happens in Mail.app.

*

*Open Preferences in Mail.app

*Go to Accounts and select your Gmail account

*Click the "Advanced" tab

*Enter [Gmail] (yes, with the brackets) into the 'IMAP Path Prefix' field

*Close the window and Save changes to the Account.


text:
Q: What are the rules regarding casing of values for environment variable USERNAME in Windows? One of my customers says that in his AD usernames have mixed case sometimes and besides that, that people are able to successfully login using another casing of usernames. So there might be an ExampleUser in the AD and Windows allows them to login with exampleUSER etc. as well.
But what is the impact on the environment variable USERNAME?
I have tested a bit myself without an AD and in all of my tests USERNAME had the value of the username as it has been created. So in case of ExampleUser created in Windows, using the login EXAMPLEuser provided ExampleUser as USERNAME. That happened for RDP where users are free to input usernames as well as using runas.
My customer said that this is not the case for him at least sometimes, but instead if ExampleUser in the AD logs in using exampleUSER, USERNAME really contains the value of the current login, exampleUSER. I've found another question describing that as well:

For some users in this office, %USERNAME% is always in the case they type it when logging in.
For other users, %USERNAME has until recently always been in the canonical case (for a user logging in as elenasimpson it returns ElenaSimpson), but last week mysteriously started only doing this sometimes and the rest of the time returning it as typed. Rebooting often toggles to the other behaviour.

What I did not found is any official docs from MS of what is the value of USERNAME under which setups and inputs of users. Are there any rules one can rely on?
Thanks!

A: Active Directory is case aware, but not case sensitive. I can't seem to find a Microsoft document directly on it, but that is the case. What that means, is the first time a user logs into a computer and they use EXAMPLEuser, it will create the user folder with that case. If you use ExampleUser, it will also use that case for that new computer.
I might double check to see if the customer is comparing apples to apples. Does he have a domain or a work group? Is he using an app that is case aware? Can he log into the same computer with the two "different" accounts? If it's on a domain, compare the two accounts Common Name, pre-Windows 2000 logon, and userPrincipalName.


text:
Q: Using Prolog ODBC Interface I am just learning prolog. I have a task ahead. I have to insert some data in to a database like mysql or MSSQL using Prolog ODBC INterface. I know there are some example predicates(SWI-PROLOG) like
open_wordnet :-
    odbc_connect('WordNet', _,
                 [ user(jan),
                   password(xxx),
                   alias(wordnet),
                   open(once)
                 ]).

I do not know how to exactly use these predicates and show a working example. Can anyone please tell me how do I exactly use these to insert data into a database like MySSQL or MSSQL from prolog. Can anyone please tell me the exact requirements to achieve the same through ProLOG?
Any help or information would be greatly appreciated.
Thank you.

A: Thank you for you responses @ThomasH and @StarWind Software. I could figure out the solutions using the code sames that you pointed out. Well here is a complete picture. I am sure there are so many people out there who need a clear picture of connection from Prolog to a Database.
Notes:

*

*You can connect to any database from within swi-prolog. I used Oracle 10g and MySQL 5.

*First of all download the 'SWI-Prolog' ODBC Interface from here.

*There are two main 'dll' files in the package 'ODBCProlog.dll' and 'OracleProlog.dll'
Next, this is the sample code which is same as above one. I Will explain the sections
MYSQL CONNECTION IN PROLOG

:- use_module(oracle).
go :-
    db_open('mysql5', 'root', 'admin'),
    db_import('EMP'('EMPID', 'EMPNAME'), emp),
    %%db_flag(show_query, _, off),

    db_query(emp(EMPID, EMPNAME), emp(EMPID, EMPNAME)),
    %% Run the query.
    get_result,
    %% Modify the database.
    %%emp_ins(109, 1, 221),
    %%test_del(109, 1, 221),
    %% Commit changes.
    db_transaction(commit),
    db_close.

%% Retrieve all records over backtracking.
get_result:-
    emp(EMPID, EMPNAME),
    write_ln([EMPID, EMPNAME]),
    fail.
get_result.

Now the explanation part:

db_open('mysql5', 'root', 'admin'),

the first part 'mysql5' the dsn name for mysql. If you do nmot have it installed in your system, you can download it from the MySQL website. The next one is username and password.

db_flag(show_query, _, off),

prints the SQL statements in the output. commenting it will prevent it from outputting the SQL query.

db_import('EMP'('EMPID', 'EMPNAME'), emp),

Here 'EMP' is the actual table name in the database and 'emp' is its alias.
It is important to create this way otherwise it will not work.

db_query(emp(EMPID, EMPNAME), emp(EMPID, EMPNAME)),

next for quering the database the above call 'db_query' will take 2 arguments. You can either query two tables using this like a JOIN statement. If you are using just quering one table then it is necessary to give the same query twice as this call expects two arguments.
Is you need to insert anything in the database uncomment

emp_ins(109, 1, 221),

This convention is nothing but you are adding _ins to the alias name which is understood by the prolog that it is an insert call to database.
similarly

emp_del(109, 1, 221),

I guess the rest is self explanatory.
Now, the next part is if you need to connect to Oracle database then the only statement that changes is :

:- use_module(odbc).

The rest is pretty same. One thing you have to remember is that you need to use the oracle INSTANCE name while specifying the database.
Usually in Oracle 10g the instance name is 'orcl' and for Oracle Express edition the convention is :
'your full computer name:port/XE','username','password'
You WILL be able to connect to database and display the results with this block of code,
Hope this helps.

A: There is an older example embedded in this mailing list conversation (look for 'test_1'). I haven't worked with it but I guess that se_greenslades is the ODBC data base instance name; you have to look up yours in your local setup. After that, I guess you use normal SQL statments (in odbc_prepare?!) to do inserts and updates. Check the SWI docs you already linked to, and search the internet for basic ODBC usage (I think the SWI interface is pretty standard).
What do you mean with "ProLOG"?

A: What about this example:
:- use_module(oracle).

go :-
    db_open('Your Database Name', 'scott', 'tiger'),
    db_import('DEPT'('DEPTNO', 'DNAME', 'LOC'), dept),
    db_import('EMP'('EMPNO', 'ENAME', 'JOB', 'MGR', 'HIREDATE', 'SAL', 'COMM', 'DEPTNO'), emp),
    %% Uncomment it, if you do not want to see SQL statements.
    %% db_flag(show_query, _, off),
    db_query(empinfo(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, DNAME, LOC),
        (   emp(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO),
            dept(DEPTNO, DNAME, LOC)
        )
    ),
    get_result,
    db_close.

get_result:-
    empinfo(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, DNAME, LOC),
    write_ln([EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, DNAME, LOC]),
    fail.
get_result.

Taken from here: http://www.geocities.com/SiliconValley/Bit/1116/PrologSQLex01.html


text:
Q: Failed to install *.apk on device 'emulator-5554': No space left on device I've seen the questions posted about this issue. I understand it takes several minutes for the emulator to configure itself and launch. But if I'm getting the specific error:
I recently deploy the project to emulator finding this problem
At the same time,I use genymotion simulator,but I don't find it on DDMS
thanks
thanks everyone!!!


text:
Q: Reagarding stdController.getRecord(); I am not getting any value when I use Quote q = (Quote)stdController.getRecord();
q is empty. Can any one suggest what would be the reason for this?

A: If you want any fields value then you need add the field api name in standard controller
public ctrl(ApexPages.StandardController stdController)
{
     stdController.addFields(new List<String>{'Name', 'PriceBook2Id', 'CurrencyIsoCode'});
}

So basically when we use getRecord()

getRecord()
Returns the record that is currently in context, based on the value of
  the id query string parameter in the Visualforce page URL.

Use addFields(fieldNames) method

When a Visualforce page is loaded, the fields accessible to the page
  are based on the fields referenced in the Visualforce markup. This
  method adds a reference to each field specified in fieldNames so that
  the controller can explicitly access those fields as well.

If q is empty means you are not adding id in url
example
/apex/VFPAGE?id=quoteId here

If we debug
Quote q = (Quote)stdController.getRecord();
system.debug('======'+q);

If output is like below means id is not passed in above page url

|======Quote :{}

If you output like below then id in url

DEBUG|======Quote :{Id=0Q09000000K8YjGAAV}


text:
Q: How to switch records in one table by Sql Command? I have such question for database developers.
I have a table which has two columns, first one is ID, Second one is Year(2002,2003,2004...it is string). I want to update them by switching the records.
In the beginning it is like this.
ID    Year
1     2002
2     2003
3     2004

I want to switch them and make like this.
ID    Year
1     2003
2     2002
3     2004

Please pay attention that My Year Column is unique.
So I tried something like this but did not work for me.
SqlCeCommand sss = new SqlCeCommand("Update Year Set Year='" + Year1 + "' Where Year='" + Year2 + "'", MainWindow._Conn);

A: Consider setting id to the number of years that are smaller or equal:
update   YourTable
set      id =
         (
         select  count(*)
         from    YourTable yt2
         where   yt2.Year <= YourTable.year
         )

Live example at SQL Fiddle.


text:
Q: Close text on close button in jquery dialog What is causing my jquery dialog to show both the Close text and the icon?
How can i remove the Close text?
I am using:

<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.10.3/themes/cupertino/jquery-ui.css" />

A: I guess you are missing some required CSS files. But anyway, you can over-ride by using:

*

*Negative text indent.

*Overflow hidden.

Give this CSS:
.close {
  text-indent: -99em;
  overflow: hidden;
}

A: Source : https://jqueryui.com/dialog/

Close button :

<button type="button" class="ui-button ui-corner-all ui-widget ui-button-icon-only ui-dialog-titlebar-close" title="Close">

    Close
</button>

A: I also have this issue.
I have a shell page with included Jquery library and Jquery UI library.
After a 3rd party application is loaded into my shell page, their bundled javascript library (which includes different version Jquery, Jquery UI and Bootstrap) conficts with the shell page.
Then the popup dialog defined in my shell page has exact same issue as shown in your question -- the overlapped close text and X sign.
Fixing the conflict is too complicated for my case, the simplest solution seems just hiding that default close button and creating a customized button to do closing.
Here is the CSS to hide the close button
    .ui-dialog-titlebar-close {
    visibility: hidden;
    }


text:
Q: Signalr invode not return output xml, angularjs For SPA have to use angularjs, signalr. Signalr call require xml as a input parameter based on input xml, output xml will return which I have to parse and get essential data.
Parse data contain captions/labels which to be used on HTML page to be set through  controller.
When called through invoke method it is not returned output xml in data.
Here is the code.
function ServerTimeController($scope, signalRHubProxy) {

            var serverHubProxy = signalRHubProxy(
                signalRHubProxy.defaultServer, 'serverTimeHub');

            $scope.getServerData = function () {
                serverHubProxy.invoke('getBnoData', '
    <?xml version="1.0" encoding="utf-8"?>
    <ENVELOPE NAME="PV.ENVELOPE" VERSION="1.00" CREATE="">
      <ENVELOPE_DATA>
        <TOKEN />
        <IPADDRESS />
        <USERAGENT />
        <LANGUAGE>LANGUAGE:ENGLISH</LANGUAGE>
        <ORIGINATOR>PV.TC.WEB.UI</ORIGINATOR>
      </ENVELOPE_DATA>
      <APPLICATION_REQUEST VERSION="1.00" LANGUAGE="EN">
        <BNO_REQUEST VERSION="1.00">
          <BNO_PRODUCTION_MODE>TRUE</BNO_PRODUCTION_MODE>
          <BNO_GROUP>LOGIN</BNO_GROUP>
          <BNO_INTERACTION_NAME>GET_T_PRE_APP_INIT</BNO_INTERACTION_NAME>
          <BNO_INTERACTION_VERSION>1.00</BNO_INTERACTION_VERSION>
          <BNO_INTERACTION_MODE>INTERACTION_MODE:VIEW</BNO_INTERACTION_MODE>
          <BNO_PARAMETERS>
            <BNO_PARAM NAME="LINGO">
              <VALUE>EN</VALUE>
            </BNO_PARAM>
          </BNO_PARAMETERS>
        </BNO_REQUEST>
      </APPLICATION_REQUEST>
    </ENVELOPE>
    ', function (data) {
                    $scope.currentServerTimeManually = data;
                    console.log(data);
                });
            };
        };

Factory code
app1.factory('signalRHubProxy', ['$rootScope', 'signalRServer',
    function ($rootScope, signalRServer) {
        function signalRHubProxyFactory(serverUrl, hubName, startOptions) {
            var connection = $.hubConnection(signalRServer);
            var proxy = connection.createHubProxy("pvhub");
            connection.start(startOptions).done(function () { });

            return {
                on: function (eventName, callback) {
                    proxy.on(eventName, function (result) {
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback(result);
                            }
                        });
                    });
                },
                off: function (eventName, callback) {
                    proxy.off(eventName, function (result) {
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback(result);
                            }
                        });
                    });
                },
                invoke: function (methodName, input, callback) {
                    proxy.invoke(methodName, input)
                        .done(function (result) {
                            $rootScope.$apply(function () {
                                if (callback) {
                                    callback(result);
                                }
                            });
                        });
                },
                connection: connection
            };
        };

        return signalRHubProxyFactory;
}]);

However when used  srv.client.receiveData it gives output xml but I need to integrate this in angularjs.
Hub code is here:
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Web;
using System.Xml;

using IDF.FACADE;

namespace PV.COM.WEB
{
    public class PvHub : Hub
    {
        ///
<summary> /// Function to be called from client siede
  /// </summary>
///
<param name="piAppRequest">
</param>
public void GetBnoData(string piAppRequest)
        {

...deleted code here

             /// call BackendAPI (Facade) to retrieve XML with content.
                    callFacade = new Facade("PV.GLOBAL.APPCONFIG.XML");
                    answer = callFacade.ExecuteAppRequest(piAppRequest);

...deleted code here

            /// call function on JS client side to send XML data with content filled by Facade
             Clients.Caller.receiveData(answer);
        }

...deleted code here

    }
}

A: I think there are a few things that do not look right, but the most clear to me is the fact that you are sending your data to the caller invoking receiveData on it, however you did not define any receiveData handler in your client code.
UPDATE
As I said, you have no receiveData callback defined on the client, but adding that would have an impact on your current client code organization. It's not a difficult thing to do, but you'd have to change some stuff. Instead, if you just change your Hub code from:
public void GetBnoData(string piAppRequest)
{
    //getting answer...

    Clients.Caller.receiveData(answer);
}

to
public dynamic GetBnoData(string piAppRequest)  //from void to dynamic
{
    //getting answer...

    return answer;
}

then you current client code (based on .done(...)) will just work.


text:
Q: problem recived the earthquake JSON result This Is the Error:-
E/QueryUtils: problem recived the earthquake JSON result
    java.net.ProtocolException: Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was Get
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.setRequestMethod(HttpURLConnectionImpl.java:606)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.setRequestMethod(DelegatingHttpsURLConnection.java:113)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java)
        at com.example.quakereport.QueryUtils.makeHttpRequest(QueryUtils.java:92)
        at com.example.quakereport.QueryUtils.featchEarthquakeDate(QueryUtils.java:52)
        at com.example.quakereport.MainActivity$EarthquakeAsyncTask.doInBackground(MainActivity.java:64)
        at com.example.quakereport.MainActivity$EarthquakeAsyncTask.doInBackground(MainActivity.java:56)
        at android.os.AsyncTask$2.call(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:760)

MainActivity.java
public class MainActivity extends AppCompatActivity {

    private EarthquakeAdapter mAdapter;

    //URL for earthquake data from the USGS dataset
    private static final String USGS_REQUEST_URL ="https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Find a refrence to the {@link ListView} in the layout*/
        ListView eathquakeListView = (ListView) findViewById(R.id.list);

        /** Create a new {@link ArrayAdapter} of earthquakes*/
       mAdapter = new EarthquakeAdapter(this,new ArrayList<Earthquake>());
        eathquakeListView.setAdapter(mAdapter);

        /** Start the AsyncTask to fetch the earthquake data*/
        EarthquakeAsyncTask task = new EarthquakeAsyncTask();
        task.execute(USGS_REQUEST_URL);

        eathquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                // Find the current earthquake that was clicked on
                Earthquake currentEarthquake = mAdapter.getItem(position);
                //convert the String URL int a URI object(to pass into the intent constructor)
                Uri eathquakeuri = Uri.parse(currentEarthquake.getmUrl());
                //Create a new intent to view the earthquake URI
                Intent websiteIntent = new Intent(Intent.ACTION_SEND, eathquakeuri);

                // Send the intent to launch a new activity
                startActivity(websiteIntent);
            }
        });

    }

    private class EarthquakeAsyncTask extends AsyncTask<String, Void, List<Earthquake>>{

        protected List<Earthquake> doInBackground(String... urls) {
            /** If there is a valid list of {@link Earthquake}, then add them to the adapter's data set. This will trigger the
             * Listview to update*/
            if(urls.length<1 || urls[0] == null){
                return null;
            }
            List<Earthquake> result = QueryUtils.featchEarthquakeDate(urls[0]);
            return result;
        }

        @Override
        protected void onPostExecute(List<Earthquake> data) {
        /** Clear the adapter of previous earthquake data*/
        mAdapter.clear();

        /** If there is a valid list of {@link Earthquake}s, then add them to the adapter's dataset. THis will trigger
         * the ListVIew to update*/

        if (data != null && !data.isEmpty()){
            mAdapter.addAll(data);
        }
        }
    }

}

QueryUtils.java
public final class QueryUtils {

    /**
     * Sample JSON response for a USGS query
     */

    /**
     * Create a private constructor because no one should ever create a {@link QueryUtils} object.
     * This class is only meant to hold static variables and methods, which can be accessed
     * directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
     */
    private static final String LOG_TAG = QueryUtils.class.getSimpleName();
    private QueryUtils() {
    }

    /**
     * Query the USGS dataset and return a list of{@link Earthquake} objects.
     */
    public static List<Earthquake> featchEarthquakeDate(String requestUrl)
    {
        // Create URL Object
        URL url = createurl(requestUrl);

        // Perform HTTP request to the URL and recive a JSON response back
        String JSONResponse = null;
        try{
            JSONResponse = makeHttpRequest(url);
        }catch (IOException e)
        {
            Log.e(LOG_TAG,"Problem Making http equest", e);
        }
        // Extract relevent fields fom the JSON response and create a list of {@link Earthquake}s
        List<Earthquake> earthquakes = extractFeatureFromJson(JSONResponse);

        //Return the list of {@link Earthquake}s
        return earthquakes;
    }
    /**
     * Return new URL from object from the given string URL
     */

    private static URL createurl(String stringURL){
        URL url = null;
        try {
            url = new URL(stringURL);
        }catch (MalformedURLException e){
            Log.e(LOG_TAG,"problem building the url", e);
        }
        return url;
    }

    /**
     * Make an HTTP request to the given URL and return a string as the response.
     * */
    private static String makeHttpRequest(URL url)throws IOException{
        String jsonResponse = "";
        // If the URL is null, then return early.
        if (url == null){
            return jsonResponse;
        }
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try{
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000/* millisecond*/);
            urlConnection.setConnectTimeout(15000 /*milisecond*/);
            urlConnection.setRequestMethod("Get");
            urlConnection.connect();

            //If the request was successful (response code 200), then read the Input Stream and parse the Response.
            if (urlConnection.getResponseCode() == 200){
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            }else {
                Log.e(LOG_TAG,"Error Response code" + urlConnection.getResponseCode());
            }

        }catch (IOException e){
            Log.e(LOG_TAG,"problem recived the earthquake JSON result",e);
        }finally {
            if (urlConnection!=null)
            {
                urlConnection.disconnect();
            }
            if (inputStream!=null){
                /*
                  Closing the input Stream could throw an IOException, which is why the makeHttpRequest(URL url) method
                  signature specific than an IOException could be thrown.
                 */
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    private static String readFromStream(InputStream inputStream) throws IOException{
        StringBuilder output = new StringBuilder();
        if (inputStream != null){
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null){
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

    /**
     * Return a list of {@link Earthquake} objects that has been built up from
     * parsing a JSON response.
     */
    private static List<Earthquake> extractFeatureFromJson(String eartheuakeJSON) {

        // If the JSON string is empity or null, then return early.
        if (TextUtils.isEmpty(eartheuakeJSON))
        {
            return null;
        }

        // Create an empty ArrayList that we can start adding earthquakes to
        List<Earthquake> earthquakes = new ArrayList<Earthquake>();

        // Try to parse the JSON response string. If there's a problem with the way the JSON
        // is formatted, a JSONException exception object will be thrown.
        // Catch the exception so the app doesn't crash, and print the error message to the logs.
        try {

           // create a JSONObject from the JSON response string
            JSONObject baseJsonResponse = new JSONObject(eartheuakeJSON);

            // Extract the JSONArray associated with the key called "features", which represent a list of features(or earthquakes).
            JSONArray earthquakeArray = baseJsonResponse.getJSONArray("features");

            // For each earthquake in the earthquakeArray, create an {@link Earthquake} object
            for (int i = 0; i < earthquakeArray.length(); i++) {
                JSONObject currentEarthquake = earthquakeArray.getJSONObject(i);

                // For a given earthquake, extract the JSONObject associated with the key called "properties", which represent a
                // list of all properties for the earthquake.
                JSONObject properties = currentEarthquake.getJSONObject("properties");
                // Extract the value for the key called "mag"
                Double magnitude = properties.getDouble("mag");
                // Extract the value for the key called "place"
                String location = properties.getString("place");
                // Extract the value for the key called "time"
                long time = properties.getLong("time");
                // Extract the value for the key called "url"
                String url = properties.getString("url");

                // Create a new {@link Earthquake} object with the magnitude,locaton,time, and url
                // from the JSON response
                Earthquake earthquake = new Earthquake(magnitude, location, time,url);
                // Add the new {@link Earthquake} to the list of earthquakes.
                earthquakes.add(earthquake);
            }

        } catch (JSONException e) {
            // If an error is thrown when executing any of the above statements in the "try" block,
            // catch the exception here, so the app doesn't crash. Print a log message
            // with the message from the exception.
            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }
        // Return the list of earthquakes
        return earthquakes;
    }

}

Earthquake.java
package com.example.quakereport;

import android.content.Context;

public class Earthquake {

    private Double mMagnitude;
    private String mLocation;
    private String mDate;
    private long mTimeInMillisecond;
    private String mUrl;

    public Earthquake(Double Magnitude, String Location, long TimeInMIllisecond, String Url) {
        mMagnitude = Magnitude;
        mLocation = Location;
        mTimeInMillisecond = TimeInMIllisecond;
        mUrl = Url;
    }

    public Double getmMagnitude() {
        return mMagnitude;
    }

    public String getmLocation() {
        return mLocation;
    }

    public String getmUrl() {
        return mUrl;
    }

    public long getmTimeInMillisecond() {
        return mTimeInMillisecond;
    }
}

EartquakeAdapter.java
public class EarthquakeAdapter extends ArrayAdapter<Earthquake> {
    private static  final String LOCATION_SEPARATOR = "of";
    public EarthquakeAdapter (Context context, List<Earthquake> place)
    {
        super(context,0,place);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View listItemView = convertView;
        if (listItemView == null)
        {
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.earthquake_list_item,parent,false);

        }

        Earthquake currentEarthQuake = getItem(position);

        TextView magnitude = (TextView) listItemView.findViewById(R.id.magnitude);
        // Formate The Magnitude to show 1 decimal place
        String formattedMaginitude = formatedMagnitude(currentEarthQuake.getmMagnitude());
        magnitude.setText(formattedMaginitude);

        //Set the prope background color on the magnitude circle.
        // Fetch the background fom the Textview, which is a GadientDrawable.

        GradientDrawable maginitudeCircle = (GradientDrawable) magnitude.getBackground();
        // Get the appropriate background color based on the current earthquake magnitude

        int magnitudeColor = getMagnitudeColor(currentEarthQuake.getmMagnitude());
        // Set the color on the magnitude cicle

        maginitudeCircle.setColor(magnitudeColor);

        String originallocation = currentEarthQuake.getmLocation();
        String primaryLocation;
        String locationOffset;

        if(originallocation.contains(LOCATION_SEPARATOR))
        {
            String[] parts = originallocation.split(LOCATION_SEPARATOR);
            locationOffset = parts[0] + LOCATION_SEPARATOR;
            primaryLocation = parts[1];
        }else {
            locationOffset= getContext().getString(R.string.near_the);
            primaryLocation = originallocation;
        }

        TextView primarrylocation = (TextView) listItemView.findViewById(R.id.location_primarry);
        primarrylocation.setText(primaryLocation);

        TextView locationOffsetView = (TextView) listItemView.findViewById(R.id.location_offset);
        locationOffsetView .setText(locationOffset);

//        TextView locationView = (TextView) listItemView.findViewById(R.id.location_primarry);
//        locationView.setText(currentEarthQuake.getmLocation());

        Date dateObject = new Date(currentEarthQuake.getmTimeInMillisecond());

        TextView dateView = (TextView) listItemView.findViewById(R.id.date);
        // Fomate the date string (ex "Mar 3, 1995")
        String formattedDate = formatDate(dateObject);
        dateView.setText(formattedDate);

        TextView timeView = (TextView) listItemView.findViewById(R.id.time);
        String formattedtime = formatTime(dateObject);
        timeView.setText(formattedtime);

        return listItemView;
    }

    private int getMagnitudeColor(double magnitude)
    {
        int mgnitudeColorResourceId;
        int magnitudeFloor = (int) Math.floor(magnitude);

        switch (magnitudeFloor)
        {
            case 0:
            case 1:
                mgnitudeColorResourceId = R.color.magnitude1;
                break;
            case 2:
                mgnitudeColorResourceId = R.color.magnitude2;
                break;
            case 3:
                mgnitudeColorResourceId = R.color.magnitude3;
                break;
            case 4:
                mgnitudeColorResourceId = R.color.magnitude4;
                break;
            case 5:
                mgnitudeColorResourceId = R.color.magnitude5;
                break;
            case 6:
                mgnitudeColorResourceId = R.color.magnitude6;
                break;
            case 7:
                mgnitudeColorResourceId = R.color.magnitude7;
                break;
            case 8:
                mgnitudeColorResourceId = R.color.magnitude8;
                break;
            case 9:
                mgnitudeColorResourceId = R.color.magnitude9;
                break;
            default:
                mgnitudeColorResourceId = R.color.magnitude10plus;
                break;

        }
        return ContextCompat.getColor(getContext(),mgnitudeColorResourceId);
    }

    private String formatDate(Date dateObject){
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
        return dateFormat.format(dateObject);
    }

    private  String formatTime (Date dateObject){
        SimpleDateFormat timeFormate = new SimpleDateFormat("h:mm a");
        return timeFormate.format(dateObject);
    }
    private  String formatedMagnitude(double magnitude){
        DecimalFormat magnitudeFormate = new DecimalFormat("0.0");
        return  magnitudeFormate.format(magnitude);
    }
}

A: In File: QueryUtils.java
You need to change this line of code
urlConnection.setRequestMethod("Get");

To this one
urlConnection.setRequestMethod("GET");

The error message explains it:
This Is the Error:- E/QueryUtils: problem recived the earthquake JSON result java.net.ProtocolException: Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was Get at
It expected GET but it was Get


text:
Q: List of categories and cms pages in single widget instance need a bit of advice with widget instance's.
I need to great a widget instance which lists both cms pages and categories which the client can change easily. here is what it needs to look like:

Now any of these links can be CMS or category pages, whichever the client decides they want, hence why i would ideally be a widget instance
What would be the best way to accomplish this?
A widget within a widget? If so how would i do that?
I have build custom widgets so i pretty much understand that process, so any advice is welcome
Thanks


text:
Q: PHP line break with file_put_contents() I can't seem to figure out why the following code doesn't produce a new line in my text file - neither does using \n etc either - any ideas what could be wrong?
    $data = $name . ' | ' . $_POST['comment'] . PHP_EOL;

    //write to file
    $f = file_put_contents('posts.txt', $data, FILE_APPEND);

A: Are you viewing the text file in an internet browser by any chance?
If you are, the browser will get rid of the newline characters (unless you're using PRE tags).

A: Try double quotes: $data = $name . ' | ' . $_POST['comment'] . "\n";
Or: $data = "$name | {$_POST['comment']}\n";

A: Have you tried \r or \n\r ? Just an idea.


text:
Q: JSONB query in Rails for a key that contains an array of hashes I have a Rails 5 project with a Page model that has a JSONB column content.  So the structure looks like this (reduced to the bare minimum for the question):
#<Page id: 46, content: {..., "media" => [{ "resource_id" => 143, "other_key" => "value", ...}, ...], ...}>

How would I write a query to find all pages that have a resource_id of some desired number under the media key of the content JSONB column?  This was an attempt that I made which doesn't work (I think because there are other key/value pairs in each item of the array):
Page.where("content -> 'media' @> ?", {resource_id: '143'}.to_json)
EDIT: This works, but will only check the first hash in the media array: Page.where("content -> 'media' -> 0 ->> 'resource_id' = ?", '143')

A: Using sql, this should give you all pages which have resource id 143:
select * from pages p where '{"resource_id": 143}' <@ ANY ( ARRAY(select jsonb_array_elements ( content -> 'media' ) from pages where id=p.id ) );

Postgresql has a function called ANY (postgres docs) which uses the form expression operator ANY (array). The left-hand expression is evaluated and compared to each element of the array using the given operator.
Since the right hand side parameter to ANY has to be an array (not a json array), we use the jsonb_array_elements method to convert the content->media json array into a set of rows which are then converted into an array by using ARRAY().
The <@ operator checks if the expression on the right contains the expression on the left side. Ex: '{"a": 1}'::jsonb <@ '{"b": 2, "a": 1}'::jsonb will return true.


text:
Q: Can't set delegate between ViewController and SKScene I want to set delegate between my GameViewController and SKScene file but facing error. My goal is to call method from SKScene file.
Error is : Value of type 'GameScene' has no member 'gameViewControllerDelegate'
What am i doing wrong ?
Thanks in advance
MainSC.swift
import UIKit
import SpriteKit
import Firebase
import StoreKit
import GoogleMobileAds

class MainVC: UIViewController, GameViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

     if let view = self.view as! SKView? {

            if let scene = SKScene(fileNamed: "GameScene") {
                let gameScene = scene as! GameScene

                //THIS GUY THROWING ERROR
                 gameScene.gameViewControllerDelegate = self

                gameScene.scaleMode = .aspectFill
                gameScene.size.width = 414
                gameScene.size.height = 736
                view.presentScene(gameScene)

            }

            view.ignoresSiblingOrder = true

            view.showsFPS = true
            view.showsNodeCount = true
            view.showsPhysics = true

        }
    }
func callMethod(inputProperty:String) {
        print("inputProperty is: ",inputProperty)
    }
}

MainSC.swift
import UIKit
import SpriteKit
import GameplayKit
import Firebase
import GoogleMobileAds

protocol GameViewControllerDelegate : class {
    func callMethod(inputProperty:String)
}

class MainSC: SKScene {

    weak var gameViewControllerDelegate : GameViewControllerDelegate?

override func didMove(to view: SKView) {

       ...

       gameViewControllerDelegate?.callMethod(inputProperty: "call game view controller method")

    }

}

A: You didn't  set the gameViewControllerDelegate delegate as self in  MainVC  so how is it possible to call the delegate of that SKscene . So set as self in MainVC