text:
Q: Acessing javaScript array of objects like a matrix Is it possible to make access to a property of an object into an array of objects like a matrix?
I mean something like this:
jSon generated object:
[
    {
        "Nome": "1",
        "Departamento": "1",
        "Cargo": "1"
    },
    {
        "Nome": "5",
        "Departamento": "5",
        "Cargo": "5"
    },
    {
        "Nome": "2",
        "Departamento": "2",
        "Cargo": "2"
    },
    {
        "Nome": "3",
        "Departamento": "33",
        "Cargo": "33"
    },
    {
        "Nome": "4",
        "Departamento": "4",
        "Cargo": "4"
    }
]

How I'm trying access the object properties:
object[0][1] = value;

What I already do:
object[0]["Nome"] = value;

I've searched a lot, but I can't find a solution for this problem.

A: No.
Objects and Arrays are two very different types in JavaScript. In an Array order is very important but order is not retained for Object keys. Keep in mind you can still iterate over the keys of an Object.
for (var prop in myObj) {
  console.log("myObj.prop -> ", myObj[prop]);
}

A: As already stated, Arrays and Objects are different. I don't really follow your reasoning for converting from one structure to the other, and you should probably consider working in a different way, which is totally possible from your question and comment descriptions. But, if you really must convert then you will need to perform some kind of mapping, to and from, to be sure that things are ordered correctly. You could do something like this.
Javascript
function toMapped (array) {
    var mapping = {
            "Nome": 0,
            "Departamento": 1,
            "Cargo": 2
        },
        mapped = [],
        length = array.length,
        i = 0,
        element,
        j;

    while (i < length ) {
        element = [];

        for (j in mapping) {
            if (mapping.hasOwnProperty(j) && array[i].hasOwnProperty(j)) {
                element[mapping[j]] = array[i][j];
            }
        }

        mapped.push(element);
        i += 1;
    }

    return mapped;
}

function fromMapped (array) {
    var mapping = {
            0: "Nome",
            1: "Departamento",
            2: "Cargo"
        },
        mapped = [],
        length = array.length,
        i = 0,
        object,
        j;

    while (i < length ) {
        object = {};
        for (j in mapping) {
            if (mapping.hasOwnProperty(j) && array[i].hasOwnProperty(j)) {
                object[mapping[j]] = array[i][j];
            }
        }

        mapped.push(object);
        i += 1;
    }

    return mapped;
}

var test = [{
    "Nome": "1",
    "Departamento": "1",
    "Cargo": "1"
}, {
    "Nome": "5",
    "Departamento": "5",
    "Cargo": "5"
}, {
    "Nome": "2",
    "Departamento": "2",
    "Cargo": "2"
}, {
    "Nome": "3",
    "Departamento": "33",
    "Cargo": "33"
}, {
    "Nome": "4",
    "Departamento": "4",
    "Cargo": "4"
}];

var mapped = toMapped(test);
var unmapped = fromMapped(mapped);

console.log(test);
console.log(mapped);
console.log(unmapped);

On jsfiddle
Using ECMA5 Array.prototype.map
Javascript
function toMapped(array) {
    var mapping = {
        "Nome": 0,
        "Departamento": 1,
        "Cargo": 2
    };

    return array.map(function (object) {
        var element = [],
            i;

        for (i in mapping) {
            if (mapping.hasOwnProperty(i) && object.hasOwnProperty(i)) {
                element[mapping[i]] = object[i];
            }
        }

        return element;
    });
}

function fromMapped(array) {
    var mapping = {
        0: "Nome",
        1: "Departamento",
        2: "Cargo"
    };

    return array.map(function (element) {
        var object = {},
            i;

        for (i in mapping) {
            if (mapping.hasOwnProperty(i) && element.hasOwnProperty(i)) {
                object[mapping[i]] = element[i];
            }
        }

        return object;
    });
}

var test = [{
    "Nome": "1",
        "Departamento": "1",
        "Cargo": "1"
}, {
    "Nome": "5",
        "Departamento": "5",
        "Cargo": "5"
}, {
    "Nome": "2",
        "Departamento": "2",
        "Cargo": "2"
}, {
    "Nome": "3",
        "Departamento": "33",
        "Cargo": "33"
}, {
    "Nome": "4",
        "Departamento": "4",
        "Cargo": "4"
}];

var mapped = toMapped(test);
var unmapped = fromMapped(mapped);

console.log(test);
console.log(mapped);
console.log(unmapped);

On jsfiddle


text:
Q: how to compare values on different screen in robotframework I want to get value of ref_no from page1 by locating it using name=ref_no. Now i clicked submit and another page opened which again show ref_no.
I want to compare these.
note: these are in 2 different "User Keyword"
In 1st user keyword, i am using:
${tmp}  Get Text    name=ref_no
Set Global Variable ${ref_no}   ${tmp}

In 2nd user keyword, i am using:
${ref_no_again} Get Text    name=ref_no
Should Be Equal As Strings  ${ref_no}   ${ref_no_again}

This is giving error. How to do this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Не работает Style в ListView Есть вот такой вот ListView:
<ListView x:Name="listView1"
              Width="300"
              HorizontalAlignment="Left"
              Background="White"
              BorderThickness ="0, 0, 2, 0"
              BorderBrush="#FFD3D7D8"
              DataContext="{Binding DataContext, ElementName=Window}"
              Foreground="Black"
              ItemsSource="{Binding ListViewAdapter}"
              MouseDoubleClick="listView1_MouseDoubleClick"
              SelectedIndex="0"
              SelectedItem="{Binding CurrentItem}"
              SelectionMode="Single"
              SelectionChanged="listView1_SelectionChanged"
                  Padding="0" Style="{DynamicResource ListViewStyle1}">
            <ListBox.ItemContainerStyle> // Вот от сюда
                <Style TargetType="{x:Type ListBoxItem}">
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="BorderThickness" Value="0, 1, 0, 1"/>
                            <Setter Property="BorderBrush" Value="Yellow"/>
                            <Setter Property="Background" Value="White"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ListBox.ItemContainerStyle> // До сюда

            <ListView.ItemTemplate>
                <DataTemplate>
                    <WrapPanel>
                        <Image Width="40"
                           Height="40"
                           Source="{Binding Image}" />
                        <Border Height="45" BorderBrush="{x:Null}">
                            <TextBlock Margin="2,0"
                                   VerticalAlignment="Center"
                                   FontFamily="Tahoma"
                                   Text="{Binding Text1}" FontSize="14" />
                        </Border>
                        <Border Height="45" BorderBrush="{x:Null}">
                            <TextBlock Margin="2,0"
                                   VerticalAlignment="Center"
                                   FontFamily="Tahoma"
                                   Foreground="#FF63676A"
                                   Text="{Binding Text2}" FontSize="14" />
                        </Border>
                    </WrapPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Начиная с 16 по 26 строчки пытаюсь изменить фон итема при его выделении на форме, но он остается таким же синим(показано на изображении ниже). Что не так и почему не работает?
Прошу помощи знатоков!
Заранее благодарен.


text:
Q: how adding global function in backbone.js accessible from multiple templates? I have created two templates  one for table and another for form inputs. The function which is in one template is not accessible from the other template . I want one global function which is accessible from both the template . I am new to backbone world . So is there  any provision to do this ? Or is there any way access the function on one template from the another ?

A: There are a few ways of achieving this.
1. Add to Backbone directly
The simplest, but perhaps least desirable from a maintenance point of view, would be to add the function as a property of the Backbone object:
Backbone.myFunction = function (...) { ... };

2. Register a templating helper
The second option, depending on your templating engine of choice, you might be able to register helpers. Example:
Handlebars.registerHelper("myHelper", function (...) { ... });

3. Use dependency injection
A third option, if you are using something like require, would be to define the functions in a common dependency, and add it as a dependency to both views.


text:
Q: Left padded text TASK: // target - starting an argument in which to record results
target should be a "source" left supplemented with "fill_char" to length "cnt". If cnt is less than the length of the source, it becomes equal to the target source.
      // Now is moving on right and must to change something but I'm not sure what and how. Can you give me advice. And if you have some different decision please share with me. Thank you :)))!
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <batch_util.h>

int lpad(char* target, char* source, char fill_char, int cnt)
{
    int i;
    int source_size = strlen(source);
    for (i = 0; i < source_size; i++)
        target[i] = source[i];
    for (i = source_size; i < cnt; i++)
        target[i] = fill_char;
    target[i] = '\0';
    return 0;
}
int main(int argc, char* argv[])
{
    char source[128];
    char target[128];
    char fill_char;
    int cnt;
    scanf("%s\n", &source);
    scanf("%c\n", &fill_char);
    scanf("%d\n", &cnt);
    lpad(target, source, fill_char, cnt);
    printf("%s\n", target);
    return 0;
}

A: For starters you can use standard C string functions instead of loops.
It seems you mean the following
#include <stdio.h>
#include <string.h>

char * lpad( char *target, const char *source, char fill_char, size_t cnt )
{
    size_t source_size = strlen( source );

    if ( source_size < cnt )
    {
        memset( target, fill_char, cnt - source_size );
    }

    strcpy( target + ( source_size < cnt ? cnt - source_size : 0 ), source );

    return target;
}

#define N   16

int main(void)
{
    char *source= "monkey";
    char target[N];

    puts( lpad( target, source, '*', N - 1 ) );

    return 0;
}

The program output is
*********monkey

As for your code then the function does not append anything to the left.


text:
Q: Multiple lines in Google Charts with different number of datasets In Google Charts I want to display 3 different lines. But they do not have the same number of data points.
The following Image was made with Excel Chart, so that you can understand my problem better.
Line grey has only two data points, the orange line goes until 5 and the blue one has full data set.
So now to my real project:
in Google Chart I tried the same, so my dataArray looks like that (with 4 lines):
["20180629", 24.5, 28, 27.52, 24.6],
["20180630", 23, 28, 23.57, 24.4],
["20180701", 22.6, 26, 23, 23.5],
["20180702", 23, 25, 22.44, 23.5],
["20180703", 25.1, 28, 24.43, 26.3],
["20180704", 27.6, 30, 24.59, 21.4],
["20180705", 28.9, 24.1, 23.8, ],
["20180706", 24.4, , , ],
["20180707", 23.7, , , ],
["20180708", 24.8, , , ]

So you can see, that from 20180629 to 20180704 there is the full data set, in 20180705 is one missing and in 20180707 and 20180708 are 3 missing.
It is no opportunity, to display a 0 there, because this would show wrong temperature charts.
The Chrome Console shows this error:
Uncaught (in promise) Error: Row given with size different than 5 (the number of columns in the table).

A: you can use null in place of the empty data points...
["20180629", 24.5, 28, 27.52, 24.6],
["20180630", 23, 28, 23.57, 24.4],
["20180701", 22.6, 26, 23, 23.5],
["20180702", 23, 25, 22.44, 23.5],
["20180703", 25.1, 28, 24.43, 26.3],
["20180704", 27.6, 30, 24.59, 21.4],
["20180705", 28.9, 24.1, 23.8, null],
["20180706", 24.4, null, null, null],
["20180707", 23.7, null, null, null],
["20180708", 24.8, null, null, null]

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ["20180629", 24.5, 28, 27.52, 24.6],
    ["20180630", 23, 28, 23.57, 24.4],
    ["20180701", 22.6, 26, 23, 23.5],
    ["20180702", 23, 25, 22.44, 23.5],
    ["20180703", 25.1, 28, 24.43, 26.3],
    ["20180704", 27.6, 30, 24.59, 21.4],
    ["20180705", 28.9, 24.1, 23.8, null],
    ["20180706", 24.4, null, null, null],
    ["20180707", 23.7, null, null, null],
    ["20180708", 24.8, null, null, null]
  ], true);

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data);
});


text:
Q: Selecting only the highest value for a specific record with other unique columns? I have table that contains data similar to the following. The query that I need would result in the top result for Orange and Apple that has the highest cityID value.
id | fruit  | attr | cityID | personID
163 Apple   green   3685    235
163 Apple   red     3145    267
163 Apple   yellow  1522    560
164 Orange  big     1344    147
164 Orange  small   833     2673

The results I need would be
id | fruit  | attr | cityID | personID
163 Apple   green   3685    235
164 Orange  big     1344    147

I started trying to accomplish this with
select
   fruit_id,
   fruit,
   attr,
   max(cityID),
   personID
from fruits_cities
    group by
     fruit_id,
     fruit,
     attr,
     max(cityID),
     personID

A: This is a challenge.  You need to use some sort of comparison.  Here is an easy way:
select fc.*
from fruits_cities fc
where fc.cityId = (select max(CityId)
                   from fruits_cities fc2
                   where fc2.fruit_id = fc.fruit_id
                  );

A: The shortest code that may helps you.
SELECT fruit_id,fruit,attr,max(cityID),personID FROM `fruits_cities` GROUP BY fruit ORDER BY fruit_id


text:
Q: is it possible to relay item in context menu to self written function? Is it possible to get the event of a item in the contextmenu?
The undo function for the input box in Chrome is no good, I wrote about it earlier today. Instead I use a custom undo function that gets triggered by the keydown event of the input box and I have blocked the CTRL+Z keydown event of the document itself (otherwise it interferes).
But the context menu still exist with the old Chrome undo.
I'm looking for something like this. Does it exist?
document.getElementById("input1").addEventListener('contextMenuUndoClicked', function(evt){customUndoFunction(evt, this);}, false);

function customUndoFunction(evt, caller)
{
    evt.preventDefault();
    < undo stuff >
}

A: I'm not 100% sure what you are trying to do, is it just to prevent the browsers built-in context menu and have your own? If so then something like this perhaps? I don't think you can capture items clicked on the built in context menu, except in certain browsers from their extensions. This code and Undo and Redo worked in Chromium but did not work in FireFox or Opera for me.
#info {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 230px;
    height: auto;
    border-style: solid;
    border-radius: 5px;
    border-width: 1px;
    box-shadow: 10px 10px 5px #888888;
    padding: 20px;
    background-color: #F3F3F3;
}
.menu {
    position: fixed;
    width: 180px;
    height: auto;
    border-style: solid;
    border-radius: 5px;
    border-width: 1px;
    box-shadow: 10px 10px 5px #888888;
    background-color: #F3F3F3;
    visibility: hidden;
}
.menutitle {
    text-align: center;
    font-weight: bold;
    color: white;
    background-color: black;
}
.menuitem {
    text-indent: 10px;
}
.menuitem:hover {
    cursor: pointer;
    width: 100%;
    height: auto;
    background-color: blue;
}
.fadein, .fadeout {
    overflow: hidden;
    /* This container should not have padding, borders, etc. */
}
.fadein {
    visibility: visible;
    opacity: 1;
    -webkit-transition: opacity 2s linear;
    -moz-transition: opacity 2s linear;
    transition: opacity 2s linear;
}
.fadeout {
    visibility: hidden;
    opacity: 0;
    -webkit-transition: visibility 0s 2s, opacity 2s linear;
    -moz-transition: visibility 0s 2s, opacity 2s linear;
    transition: visibility 0s 2s, opacity 2s linear;
}
.fadein > div, .fadeout > div {
    /* Put any padding, border, min-height, etc. here. */
}
.fadeout > div {
    margin-top: -10000px;
    -webkit-transition: margin-top 0s 2s;
    -moz-transition: margin-top 0s 2s;
    transition: margin-top 0s 2s;
}

Hold CTRL for original context menu

<input id="input1" class="customContext customTextContext" type="text"></input>
<input id="input2" class="customContext customTextContext" type="datetime"></input>
<input id="input3" class="customContext customTextContext" type="number"></input>
<input id="input4" class="customContext customOtherContext" type="color"></input>

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global */

(function () {
    "use strict";

    var customTextContexts = document.getElementsByClassName("customTextContext"),
        info = document.getElementById("info"),
        inputTextContextMenu,
        inputOtherContextMenu;

    function hideMenus() {
        var menus = document.getElementsByClassName("menu");

        Array.prototype.forEach.call(menus, function (menu) {
            menu.style.visibility = "hidden";
        });
    }

    function toggleMenu(element) {
        var menus = document.getElementsByClassName("menu");

        Array.prototype.forEach.call(menus, function (menu) {
            if (menu.style.visibility === "visible") {
                menu.style.visibility = "hidden";
            } else if (element === menu) {
                menu.style.visibility = "visible";
            }
        });
    }

    function fadeout(element) {
        if (element.className.indexOf("fadein") !== -1) {
            element.className = element.className.replace("fadein", "fadeout");
        } else if (element.className.indexOf("fadeout") === -1) {
            element.className += "  fadeout";
        }
    }

    setTimeout(function () {
        fadeout(info);
    }, 3000);

    function context(evt) {
        var position;

        if (evt.target.className.indexOf("customContext ") !== -1) {
            if (!evt.ctrlKey) {
                evt.preventDefault();
                position = evt.target.getBoundingClientRect();

                if (evt.target.className.indexOf("customTextContext") !== -1) {
                    inputTextContextMenu.style.top = position.bottom + "px";
                    inputTextContextMenu.style.left = position.left + "px";
                    toggleMenu(inputTextContextMenu);
                } else if (evt.target.className.indexOf("customOtherContext") !== -1) {
                    inputOtherContextMenu.style.top = position.bottom + "px";
                    inputOtherContextMenu.style.left = position.left + "px";
                    toggleMenu(inputOtherContextMenu);
                } else {
                    hideMenus();
                }
            } else {
                hideMenus();
            }
        } else {
            hideMenus();
        }
    }

    function undoStuff() {
        hideMenus();
        document.execCommand('undo', false, null);
    }

    function redoStuff() {
        hideMenus();
        document.execCommand('redo', false, null);
    }

    function backStuff() {
        hideMenus();
        window.history.back();
    }

    function forwardStuff() {
        hideMenus();
        window.history.forward();
    }

    function reloadStuff() {
        window.location.reload();
    }

    function createInputTextContextMenu() {
        var menu = document.createElement("div"),
            rich = document.createElement("div"),
            title = document.createElement("div"),
            undo = document.createElement("div"),
            redo = document.createElement("div"),
            back = document.createElement("div"),
            forward = document.createElement("div"),
            reload = document.createElement("div"),
            line = document.createElement("hr");

        menu.id = "customTextContextMenu";
        menu.className = "menu";
        title.textContent = "Text context menu";
        title.className = "menutitle";
        undo.textContent = "Undo";
        undo.className = "menuitem";
        undo.addEventListener("click", undoStuff, false);
        redo.textContent = "Redo";
        redo.className = "menuitem";
        redo.addEventListener("click", redoStuff, false);
        back.textContent = "Back";
        back.className = "menuitem";
        back.addEventListener("click", backStuff, false);
        forward.textContent = "Forward";
        forward.className = "menuitem";
        forward.addEventListener("click", forwardStuff, false);
        reload.textContent = "Reload";
        reload.className = "menuitem";
        reload.addEventListener("click", reloadStuff, false);

        rich.appendChild(title);
        rich.appendChild(undo);
        rich.appendChild(redo);
        rich.appendChild(line);
        rich.appendChild(back);
        rich.appendChild(forward);
        rich.appendChild(reload);
        menu.appendChild(rich);

        return menu;
    }

    function createInputOtherContextMenu() {
        var menu = document.createElement("div"),
            rich = document.createElement("div"),
            title = document.createElement("div"),
            back = document.createElement("div"),
            forward = document.createElement("div"),
            reload = document.createElement("div");

        menu.id = "customOtherContextMenu";
        menu.className = "menu";
        title.textContent = "Other context menu";
        title.className = "menutitle";
        back.textContent = "Back";
        back.className = "menuitem";
        back.addEventListener("click", backStuff, false);
        forward.textContent = "Forward";
        forward.className = "menuitem";
        forward.addEventListener("click", forwardStuff, false);
        reload.textContent = "Reload";
        reload.className = "menuitem";
        reload.addEventListener("click", reloadStuff, false);

        rich.appendChild(title);
        rich.appendChild(back);
        rich.appendChild(forward);
        rich.appendChild(reload);
        menu.appendChild(rich);

        return menu;
    }

    inputTextContextMenu = createInputTextContextMenu();
    document.body.appendChild(inputTextContextMenu);
    inputOtherContextMenu = createInputOtherContextMenu();
    document.body.appendChild(inputOtherContextMenu);

    // right clicked context menu
    document.addEventListener("contextmenu", context, false);

    // other click hide context
    document.addEventListener("click", function () {
        hideMenus();
    }, false);
}());

on jsfiddle


text:
Q: Tracking email delivery using API Once we send email using REST API https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends/0df05557-9253-41c3-bdc0-29d90612fa31/send?access_token=.....;
a. do we get token id?
b. how do we verify delivery status using API
Please guide.
Thanks,
Ganga

A: You will not receive a token id, but you will receive a successful 202 response like this:
HTTP/1.1 202 Accepted

For more info, check out this page - https://code.exacttarget.com/apis-sdks/rest-api/v1/messaging/messageDefinitionSends.html


text:
Q: Action class is not working in Page Object Model Action class is not working in POM. I have a method in Page where i am trying to move to an element and then click on sub-tab. But its not working. Here is the Page class and test class, any one know what is the issue
Page Class
 public void clickManageCapacityTab() {
actions = new Actions(driver);
log.info("move to account admin tab");
actions.moveToElement(accountAdminTab).perform();
AutoUtility.sleep(1);
log.info("manage capacity tab is clicked");
manageCapacityTab.click();
}

Test Class
public class CheckManageCapacity extends BaseTest {
@Test(priority=6, groups={"checkintest"})
private void testCheckManageCapacity() {
LoginPage loginPage = new LoginPage(driver);
loginPage.signInApp(username, password);
NavigationPage navigationPage = new NavigationPage(driver);
navigationPage.clickManageTab();
navigationPage.clickManageCapacityTab();
}
}

Below is the exception i am getting
FAILED: testCheckManageCapacity
org.openqa.selenium.InvalidArgumentException: Could not find webelement key
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'ZAHID-LAPTOP', ip: '192.168.0.10', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{moz:profile=C:\Users\zafaque\AppData\Local\Temp\rust_mozprofile.T1V3FfIgWOuV, rotatable=false, timeouts={implicit=0.0, pageLoad=300000.0, script=30000.0}, pageLoadStrategy=normal, platform=ANY, specificationLevel=0.0, moz:accessibilityChecks=false, acceptInsecureCerts=false, browserVersion=54.0.1, platformVersion=10.0, moz:processID=19004.0, browserName=firefox, javascriptEnabled=true, platformName=windows_nt}]
Session ID: 0660b08a-ec93-467b-ae17-ef68624aaae9
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:150)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:115)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:45)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
at org.openqa.selenium.remote.RemoteWebDriver.perform(RemoteWebDriver.java:703)
at org.openqa.selenium.interactions.Actions$BuiltAction.perform(Actions.java:631)
at org.openqa.selenium.interactions.Actions.perform(Actions.java:593)
at page.NavigationPage.clickManageCapacityTab(NavigationPage.java:108)
at script.CheckManageCapacity.testCheckManageCapacity(CheckManageCapacity.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)


text:
Q: not decrypting what I crypted I have a weird problem...
Basing my solution on Decrypting a hardcoded file as byte[]
So, I wrote a small Cypher class to help out with crypting/decrypting... It used to mock-up a key hardcoded at some place and another pre-crypted key stored somewhere else. But that's somewhat irrelevant atm.
the crypting process went like this:

*

*retrieve the hardcoded byte array

*use it to decrypt key2

*use key2 to decrypt data

*use key1 to further decrypt data

*have decrypted data

I was storing the crypted data as a hex-string, used these two functions to get in-out of there
private static String byteArrayToHexString(byte[] b)
{
    StringBuffer sb = new StringBuffer(b.length * 2);
    for (int i = 0; i < b.length; i++)
    {
        int v = b[i] & 0xff;
        if (v < 16)
        {
            sb.append('0');
        }
        sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase();
}

private static byte[] hexStringToByteArray(String s)
{
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++)
    {
        int index = i * 2;
        int v = Integer.parseInt(s.substring(index, index + 2), 16); //THIS LINE
        b[i] = (byte) v;
    }
    return b;
}

That worked flawlessly; in fact it worked so good that I implemented it in my real project. The project failed to run due to the fact that i didn't thoroughly test.
Turns out it crypts/decrypts pretty much all files OK except one - that one doesn't want to decrypt.
I have pinpointed the issue however - THIS line throws an IllegalNumberFormat exception; at some point i got acquainted with this http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6259307 as well. I would and can revert to this method if someone describes a way to bypass a case when a string of length 2 is converted to four bytes which throw an IllegalNumberFormatException.
So, I figured that since I cannot decode a file (and obviously cannot share it here for you guys to try out) I needed to transform it somehow to make it transport-safe. Enter the Base64Coder class which encodes to base64 strings...
That seemed to have introduced a new issue - padding was getting effed up.
The question is simple - what am I doing wrong? I need to conform to this data and it has to be able to crypt/decrypt properly and equally. I'd like a proposal on the most light-weight solution possible with least copy/pasting... pseudocode won't do the trick here.
Here's what I'm doing now....
public static char[] encrypt2(byte[] value) throws GeneralSecurityException, IOException
{
    SecretKeySpec key1 = getSecretKeySpec(true);
    System.err.println("encrypt():\t" + key1.toString());
    Cipher cipher = Cipher.getInstance(CRYPTOSYS);
    cipher.init(Cipher.ENCRYPT_MODE, key1, cipher.getParameters());
    byte[] encrypted = cipher.doFinal(value);

    SecretKeySpec key2 = getSecretKeySpec(false);
    cipher = Cipher.getInstance(CRYPTOSYS);
    cipher.init(Cipher.ENCRYPT_MODE, key2, cipher.getParameters());
    byte[] encrypted2 = cipher.doFinal(encrypted);

    return Base64Coder.encode(encrypted2);
}

public static byte[] decrypt2(char[] message) throws GeneralSecurityException, IOException
{
    SecretKeySpec key1 = getSecretKeySpec(false);
    System.err.println("decrypt():\t" + key1.toString());
    Cipher cipher = Cipher.getInstance(CRYPTOSYS);
    cipher.init(Cipher.DECRYPT_MODE, key1);
    byte[] decrypted = cipher.doFinal(Base64Coder.decode(message));

    SecretKeySpec key2 = getSecretKeySpec(true);
    cipher = Cipher.getInstance(CRYPTOSYS);
    cipher.init(Cipher.DECRYPT_MODE, key2);
    byte[] decrypted2 = cipher.doFinal(decrypted);

    return decrypted2;
}

Note that keys are currently fully-exposed (hardcoded) for testing purposes.
Here's my test-case
public static void main(String... args) throws Exception
{
    //      byte[] data = "hello".getBytes();
    File PEM = new File(PATH_TO_FILES + SOURCE_PEM);
    File DER = new File(PATH_TO_FILES + SOURCE_DER);
    File cryptoPEM = new File(PATH_TO_FILES + "cryptopem");
    File cryptoDER = new File(PATH_TO_FILES + "cryptoder");

    byte[] cryptokey = encryptA(ASSET_KEY);
    System.out.println(new String(cryptokey));

    //pem key
    System.out.println("PEM");
    byte[] data = getBytesFromFile(PEM);
    char[] crypted = encrypt2(data);
    //      FileOutputStream fos = new FileOutputStream(cryptoPEM);
    FileWriter fw = new FileWriter(cryptoPEM);
    fw.write(crypted);
    fw.flush();

    //der key
    System.out.println("DER");
    data = getBytesFromFile(DER);
    crypted = encrypt2(data);
    fw = new FileWriter(cryptoDER);
    fw.write(crypted);
    fw.flush();

    //opentext
    System.out.println("checking PEM...");
    crypted = Base64Coder.encode(getBytesFromFile(cryptoPEM));
    byte[] decrypted = decrypt2(crypted,  false);
    byte[] decryptedData = decrypted;

    if (!Arrays.equals(getBytesFromFile(PEM), decryptedData)) { throw new Exception("PEM Data was not decrypted successfully"); }

    System.out.println("checking DER...");
    crypted = Base64Coder.encode(getBytesFromFile(cryptoDER));
    decrypted = decrypt2(crypted,  false);
    decryptedData = decrypted;

    if (!Arrays.equals(getBytesFromFile(DER), decryptedData)) { throw new Exception("DER Data was not decrypted successfully"); }
}

And I'm getting an InvalidBlockSizeException now.... Please, someone shed some light on this, I just want this to work...
Replacing 'key2' for an IV to be later used in a "AES/CBC/PKCS5Padding" is an option I'm considering right now. Essentially nothing will change except the second step of encrypting. Theoretically and metodically I'd keep things the same - unless of course a better solution is described.
At the end I'd like to point out that this is a programmer question, not a IT security-student question so proper code is valued more than a theoretical response that covers unlikely fringe cases.
EDIT:
well, I can't give you the numbers that cause the IllegalNumberFormatException because I lost the code from this morning. I can't seem to replicate the issue so I guess trying to figure that part is of no use.
Here's the output from the sample test:
encrypt():  javax.crypto.spec.SecretKeySpec@15dd7
5@��_׵G�j��!�c;D�i�lR?z�j\
PEM
encrypt():  javax.crypto.spec.SecretKeySpec@15dd7
DER
encrypt():  javax.crypto.spec.SecretKeySpec@15dd7
checking PEM...
decrypt():  javax.crypto.spec.SecretKeySpec@15c78
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

which means that Base64 is kinda messing it up...

A: I think the problem is here:
//opentext
System.out.println("checking PEM...");
crypted = Base64Coder.encode(getBytesFromFile(cryptoPEM));

Previously, you wrote char[] to the file, but now you're reading a byte[] from the file and re-encoding in base64.  The file's contents should already be base64-encoded!
You need a new function called getCharsFromFile that returns char[] or String and pass that directly to decrypt2.

A: Any reason why you dont use the Appache Commons for this?
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html

A: After reviewing the code this morning and tweaking a little bit I got it to work.
public static byte[] encrypt2(byte[] value) throws GeneralSecurityException, IOException
{
    SecretKeySpec key1 = getSecretKeySpec(true);
    System.err.println("encrypt():\t" + key1.toString());
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key1, cipher.getParameters());
    byte[] encrypted = cipher.doFinal(value);

    SecretKeySpec key2 = getSecretKeySpec(false);
    System.err.println("encrypt():\t" + key2.toString());
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key2, new IvParameterSpec(getIV()));
    byte[] encrypted2 = cipher.doFinal(encrypted);

    return encrypted2;//Base64Coder.encode(encrypted2);
}

public static byte[] decrypt2(byte[] message, boolean A) throws GeneralSecurityException, IOException
{
    SecretKeySpec key1 = getSecretKeySpec(false);
    System.err.println("decrypt():\t" + key1.toString());
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key1, new IvParameterSpec(getIV()));
    byte[] decrypted = cipher.doFinal(message);

    SecretKeySpec key2 = getSecretKeySpec(true);
    System.err.println("decrypt():\t" + key2.toString());
    cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, key2);
    byte[] decrypted2 = cipher.doFinal(decrypted);

    return decrypted2;
}


text:
Q: I don't understand passing arrays to functions in C The program I have works. Once I try to clean it up with functions I get totally lost. Can someone please review my code and help me understand what I'm doing wrong?
The program output needs to look like this (please note, this photo was taken prior to adding functions):

Ideally, after the update_level loop, I would then print the totals.
Below is my code with functions that I don't understand at all.
#include <stdio.h>

int update_level(int player[],int healthpoint);
int display_levels();

int main(void)
{
    int levels[6] = {1,2,3,4,5,6};  // levels is an array of 6 integers
    int players[6] = {0,0,0,0,0,0}; // players is an array of 6 integers
    int healthpoints;           // initialize variable

    printf("Enter total player health points (-1 to quit): ");  // user input
    scanf("%d", &healthpoints);         // reads user input

    for(j=0; j<=5; j++)
    {
        update_level(players[j],healthpoints);
    }

    return;
}   // end main

int update_level(int player[],int healthpoint);
{
    while (healthpoints != -1)
    {
        if ( healthpoints <= 9)
        {
            players[0] += 1;
        } //end if
        else if (healthpoints <= 19)
        {
            players[1] += 1;
        } //end else if
        else if (healthpoints <= 29)
        {
            players[2] += 1;
        } //end else if
        else if (healthpoints <= 39)
        {
            players[3] += 1;
        } //end else if
        else if (healthpoints <= 49)
        {
            players[4] += 1;
        } //end else if
        else
        {
            players[5] += 1;
        } // end else

        printf("Enter total player health points (-1 to quit): ");  // user input
        scanf("%d", &healthpoints);         // reads user input

    }   // end while

    return;
}   // end update_level

int display_levels()
{
    int i;      // initialize variable

    printf("T O T A L S\n\n");

    for (i = 0; i < 6; ++i){
        printf("Level %u%13d\n", levels[i], players[i]);
    }       // end for

    return;
} // end display_levels

A: With some help, I was able to debug my program. Below is the correct code.

#include <stdio.h>

int update_level(int players[],int healthpoints);
int display_levels(int levels[],int players[]);

int main(void)
{
    int levels[6] = {1,2,3,4,5,6};  // levels is an array of 6 integers
    int players[6] = {0,0,0,0,0,0}; // players is an array of 6 integers
    int healthpoints;           // initialize variable

    printf("Enter total player health points (-1 to quit): ");  // user input
    scanf("%d", &healthpoints);         // reads user input

    update_level(players,healthpoints);
    display_levels(levels,players);

    return;
}   // end main

int update_level(int players[],int healthpoints)
{
    while (healthpoints != -1)
    {
        if ( healthpoints <= 9)
        {
            players[0] += 1;
        } //end if
        else if (healthpoints <= 19)
        {
            players[1] += 1;
        } //end else if
        else if (healthpoints <= 29)
        {
            players[2] += 1;
        } //end else if
        else if (healthpoints <= 39)
        {
            players[3] += 1;
        } //end else if
        else if (healthpoints <= 49)
        {
            players[4] += 1;
        } //end else if
        else
        {
            players[5] += 1;
        } // end else

        printf("Enter total player health points (-1 to quit): ");  // user input
        scanf("%d", &healthpoints);         // reads user input

    }   // end while

    return;
}   // end update_level

int display_levels(int levels[],int players[])
{
    int i;      // initialize variable

    printf("T O T A L S\n\n");

    for (i = 0; i < 6; ++i){
        printf("Level %u%13d\n", levels[i], players[i]);
    }       // end for

    return;
} // end display_levels


text:
Q: Parse error: syntax error, unexpected '"', expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:... on line 22 I want to update a row in a table for my project, I'm copying a syntax I saw somewhere else here however, I think my problem comes when I try updating where ApplicantID is equal to $_SESSION["ID"].
I get this error
Parse error: syntax error, unexpected '"', expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\...\InsertPData.php on line 22

here is the php along side the SQL:
<?php
        include_once'dbconnect.php';
        session_start();

        function INSERT()
        {
            $Name=$_POST['name'];
            $Relation=$_POST['Relation'];
            $Email=$_POST['Email'];
            $Address=$_POST['Address'];
            $Postcode=$_POST['Postcode'];
            $Mobile_Number=$_POST['Mobile_Number'];
            $Home_Number=$_POST['Home_Number'];
            $INSERT="UPDATE Applicants
            SET ParentName='$Name',
            Relationtoapplicant='$Relation',
            ParentEmail='$Email',
            ParentAddress='$Address',
            ParentPostcode='$Postcode',
            ParentMobile='$Mobile_Number',
            ParentHome='$Home_Number',
            WHERE ApplicantID=$_SESSION["ID"] "; #THIS IS LINE 22

            $data=mysql_query($INSERT) or die(mysql_error());
            if($data)
            {
                echo "Parents/Gauridan details hav been entered";
            }
            else print "error";
        }

        INSERT()
        ?>

I've already searched for a solution to this but haven't found something where the user is using a session thing. Thank you.

A: This is why an IDE with syntax highlighting is helpful. StackOverflow uses syntax highlighting on code blocks as well and actually already gives you the answer based on your code:
$INSERT="UPDATE Applicants
WHERE ApplicantID=$_SESSION["ID"] ";

See how ID is suddenly black instead of dark red? That's because you are terminating the string there. The double quotes should either be escaped or replaced with single quotes, like:
$INSERT="UPDATE Applicants
WHERE ApplicantID=$_SESSION[\"ID\"] ";

Or
$INSERT="UPDATE Applicants
WHERE ApplicantID=$_SESSION['ID'] ";

See how the ID bit stays dark red? This is because now your string is not suddenly terminated.
Also, please do not use mysql_ functions anymore. They have been deprecated since 2013 and are currently not even a part of PHP anymore. So if you'd update your PHP to the latest version, this code would not work. On top of that, this code is vulnerable to SQL injection attacks.
Also see Why shouldn't I use mysql_* functions in PHP? and How can I prevent SQL-injection in PHP?.


text:
Q: Tkinter Canvas Scroll / Drag Notification I want to redraw the canvas whenever the view changes (custom scrolling of a large image).
Currently I hook into a couple of functions to achieve this: xview_moveto, yview_moveto, scan_dragto
Is there an event that can be used to do this cleaner? Or another way to do it?
current code looks something like:
class CustomCanvas(Tkinter.Canvas):
    def xview(self, *args):
        r = Tkinter.Canvas.xview(self, *args)
        if args:
            self.event_generate("<<ScrollEvent>>")
        return r
    def yview(self, *args):
        r = Tkinter.Canvas.yview(self, *args)
        if args:
            self.event_generate("<<ScrollEvent>>")
        return r
    def xview_moveto(self, *args):
        Tkinter.Canvas.xview_moveto(self, *args)
        self.event_generate("<<ScrollEvent>>")
    def yview_moveto(self, *args):
        Tkinter.Canvas.yview_moveto(self, *args)
        self.event_generate("<<ScrollEvent>>")
    def scan_dragto(self, *args):
        Tkinter.Canvas.scan_dragto(self, *args)
        self.event_generate("<<ScrollEvent>>")

A: If you're not adverse to some out-of-the-box thinking, you can solve this with a little bit of custom Tcl code. I write this not because it's the best solution per se, but because it's an interesting one.
The solution works like this: when you scroll, ultimately what gets called is a subcommand of the underlying tk widget to actually perform the scroll. For example, self.canvas.xview_moveto(...) results in a tcl command that looks something like .123455.234123 xview moveto .... The strange looking series of numbers and dots is the internal name of the widget. It is also the name of a command which implements the scrolling behavior.  "xview" is called a subcommand in tcl nomenclature, though it can be thought of like a method on the widget object.
Now, the cool thing with Tcl is, you can rename any command and replace it with something different. Since everything that happens to this widget calls this command, we can create a proxy through which all commands are sent.
In your case, you would like an event to fire whenever the canvas is scrolled. We know it scrolls whenever the widget command is called with an "xview" or "yview" subcommand. So, by replacing the widget command with a proxy, and having the proxy look for these subcommands, we can accomplish that very thing.
Here's a working example using python 2.7:
# use 'tkinter' instead of 'Tkinter' if using python 3.x
import Tkinter as tk

class CustomCanvas(tk.Canvas):
    def __init__(self, *args, **kwargs):
        '''A custom canvas that generates <<ScrollEvent>> events whenever
           the canvas scrolls by any means (scrollbar, key bindings, etc)
        '''
        tk.Canvas.__init__(self, *args, **kwargs)

        # replace the underlying tcl object with our own function
        # so we can generate virtual events when the object scrolls
        tcl='''
            proc widget_proxy {actual_widget args} {
                set result [$actual_widget {*}$args]
                set command [lindex $args 0]
                set subcommand [lindex $args 1]
                if {$command in {xview yview} && $subcommand in {scroll moveto}} {
                    # widget has been scrolled; generate an event
                    event generate {widget} <<ScrollEvent>>
                }
                return $result
            }

            rename {widget} _{widget}
            interp alias {} ::{widget} {} widget_proxy _{widget}
        '''.replace("{widget}", str(self))
        self.tk.eval(tcl)

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        # create an instance of the custom canvas. Make sure it
        # has a largeish scroll region, for demonstration purposes
        self.canvas = CustomCanvas(self, width=400, height=400,
                                   borderwidth=0, scrollregion=(0,0,1000,1000))
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.hsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.canvas.configure(xscrollcommand=self.hsb.set, yscrollcommand=self.vsb.set)

        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.vsb.grid(row=0, column=1, sticky="ns")
        self.hsb.grid(row=1, column=0, sticky="ew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        # this binds to the virtual event that is sent by the proxy
        self.canvas.bind("<<ScrollEvent>>", self.on_scroll)

        # some data, just so that we can see that the canvas
        # really is scrolling
        for y in range(0, 1000, 100):
            for x in range(0, 1000, 100):
                self.canvas.create_text(x, y, text="%s/%s" % (x,y), anchor="nw")

    def on_scroll(self, event):
        print "widget scrolled..."

if __name__ == "__main__":
    root = tk.Tk()
    view = Example(root)
    view.pack(side="top", fill="both", expand=True)
    root.mainloop()

Caveats: this will only work for when you scroll the area, though it should work even if you scroll with the keyboard (eg: page up, page down, etc). If you resize the window the event won't fire. You can handle that case by binding to <Configure>. Also, I left out error checking for the sake of brevity, though it should be fairly robust. Finally, you can only use this specific implementation once in a program since I hard-coded "widget_proxy" rather than make it something more unique. That's an exercise left for the reader.


text:
Q: What method will return ActiveRecord owner object from class method? Let's say I have users which have items:
class User < ActiveRecord::Base
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to :user
end

Now I want to add a class method to item for a customized record creation:
def self.create_personalized
  create description: "#{user.name}' item"
end

But of course, since this is a class method, user is undefined.  But if I call it using user.items.create_personalized, then there is an associated user via the relationship.  I know that Item.create_personalized is aware of the user because this works:
def self.create_personalized
  item = create
  item.update_attribute :description, "#{item.user.name}'s item"
end

But clearly that's not the best way to access the owner object.  What is the correct method?

A: If you do
Item.scope_attributes

then you'll get a hash of any attributes from the current scope that apply to item. These are the ones that would be extracted from the scope if you called create. These are the DB level attributes so you'll get a user id rather than the user itself.

A: The best option I've found is current_scope.proxy_association.owner.  It's still a bit indirect, but it returns the exact object I'm looking for.
def self.create_personalized
  user = current_scope.proxy_association.owner
  create description: "#{user.name}'s item"
end


text:
Q: How can I go deep by a variable amount into a multidimensional array in PHP? I have a multidimensional array called $organized_comments and an array called $ancestors which is given by a function (unimportant) which lists all ancestors of an element in $organized_comments.
$organized_comments looks like this:
Array
(
    [1] => Array
        (
            [id] => 1
            [child] => Array
                       (
                           [id] => 2
                           [child] => Array
                                   (
                                   [id] => 3
                                   [child] => Array
                                           (
                                           )
                                   )
                       )
        )
)

And I ran my function with the input as 3 and its output was $ancestors equal to [1,2] which means that 3 ancestors from farthest out to closest were 1 and then 2.
I want to make a function that runs through $ancestors in a way that when it reaches [id] => 3, I can insert a value into the [child] key.
What I tried was this:
$ancestors_count = count($ancestors);
    $i = 0;
    $thing = '$organized_comments';
    foreach($ancestors as $parent_id_here) {
        $i = $i + 1;
        if ($i != $ancestors_count) {
        $thing = $thing . "['$parent_id_here']";
        } else {
        ///MY ACTION
        }
    }

But that obviously didn't work since I was just adding strings.  What can I do to get to [id] => 3?
Thank you!  Please tell me if I have been unclear at any point.

A: Based on your $thing concatenation logic, I conclude that ['child'] can only contain a single element, and array keys always match corresponding item id.
echo 'Before: ', json_encode($organized_comments, JSON_PRETTY_PRINT), "\n"; // more readable than print_r()

$ancestors = [1, 2];
$item = &$organized_comments;
foreach ( $ancestors as $ancestor_id ) {
    $item = &$item[$ancestor_id]['child'];
}
if ( $item ) {
    // $id = array_key_first($item); // php 7.3+
    $id   = array_keys($item)[0];
    $item = &$item[$id];
    // do your thing here
    $item['foo'] = 'bar';
}
unset($item); // destroy reference to avoid accidental data corruption later

echo 'After: ', json_encode($organized_comments, JSON_PRETTY_PRINT), "\n";

Output:
Before: {
    "1": {
        "id": 1,
        "child": {
            "2": {
                "id": 2,
                "child": {
                    "3": {
                        "id": 3,
                        "child": []
                    }
                }
            }
        }
    }
}
After: {
    "1": {
        "id": 1,
        "child": {
            "2": {
                "id": 2,
                "child": {
                    "3": {
                        "id": 3,
                        "child": [],
                        "foo": "bar"
                    }
                }
            }
        }
    }
}


text:
Q: RGB Normalizied give Black image Here , I am trying to do normalize RGB image.
Here is my code.
cv::Mat channels[3], normalize_rgb;
    split(image, channels);

    for (int i = 0; i < image.size().height; i++)
    {
        for (int j = 0; j < image.size().width; j++)
        {
            int b = (int)(image).at<cv::Vec3b>(i, j)[0];
            int g = (int)(image).at<cv::Vec3b>(i, j)[1];
            int r = (int)(image).at<cv::Vec3b>(i, j)[2];

                            double sum = b + g + r;
            double bnorm = b / sum * 255;
            double gnorm = g / sum * 255;
            double rnorm = r / sum * 255;

            channels[0].at<uchar>(i, j) = bnorm;
            channels[1].at<uchar>(i, j) = gnorm;
            channels[2].at<uchar>(i, j) = rnorm;
        }
    }
    merge(channels, 3, normalize_rgb);
    normalize = normalize_rgb.clone();

Problem:  after normalizing r,g, b value is giving me very small value which turns to 0. and hence I get black image.
Anyone can please help me to figure out problems. thanks

A: Change image to double first. It is black because when you divide int by int you get zero. And then you're trying to set uchar = double which is completely wrong.
Try:
double bnorm = double (b) / sum * 255;

A: You need to divide the sum by the number of pixels.
In a 1000x1000 image you want to divide by the average, not by one million times the average.
Note that dividing by the average may give you values bigger than 255 (values higher than the average) so clamping is required after the scaling. Probably a better solution would be aiming at the average becoming 128, not 255 with
double bnorm = b * k;
double gnorm = g * k;
double rnorm = r * k;

where k is computed once per image as
double average = sum / (image.size().height*image.size().width);
double k = 127.0 / average;

but note that this can still produce values higher than 255 in output.
If you want to stretch you need to normalize with the maximum value, not with the average and in this case clamping is not needed.

A: I found a link which related to RGB Normalization, there is a  mathematical list in the article.
So actually, u need to divide a var total, and each total is just the sum of each pixel, not the whole image(width() * height()). Maybe you should try this:
for (int i = 0; i < image.size().height; i++)
{
    for (int j = 0; j < image.size().width; j++)
    {
        int b = (int)(image).at<cv::Vec3b>(i, j)[0];
        int g = (int)(image).at<cv::Vec3b>(i, j)[1];
        int r = (int)(image).at<cv::Vec3b>(i, j)[2];
        int sum = b + g  + r;

        double bnorm = b / sum * 255;
        double gnorm = g / sum * 255;
        double rnorm = r / sum * 255;

        channels[0].at<uchar>(i, j) = bnorm;
        channels[1].at<uchar>(i, j) = gnorm;
        channels[2].at<uchar>(i, j) = rnorm;
    }
}


text:
Q: tell socat to stop on connection refuse with fork enabled I'm using this instruction to forward a port to another, both on a local machine:
socat -d -d TCP4-LISTEN:80,reuseaddr,fork TCP4:127.0.0.1:8000

I need to keep the port open unless the destination port get closed (connection refuse).
Is it possible to ask socat to terminate on connection refuse (with fork enabled)?

A: AFAIK this is not possible with current versions


text:
Q: Gatsby unable to create multiple child sections from GraphQL queries? I'm using Craft CMS headless mode with Gatsby and i'm trying to generate 2 sets of pages from the GraphQL data output by Craft. One section is posts which i intend to be "/notes/note-slug" and one is projects intended to be "/work/project-slug".
After setting up my gatsby-node.js file as close to what i expect to work as possible, Gatsby kicks off and gives me an error of 'Cannot read property 'id' of undefined' on the projects section.
const path = require("path")

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  const projectTemplate = path.resolve(`src/templates/project.js`)
  const blogPostTemplate = path.resolve(`src/templates/note.js`)

  return graphql(`
    {
      craft {
        projects: entries(section: "work") {
          id
          slug
        }
        blogPosts: entries(section: "notes") {
          id
          slug
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      Promise.reject(result.errors)
    }

    // Create all single project pages
    result.data.craft.projects.forEach(({ project }) => {
      createPage({
        path: `/work/${project.slug}`,
        component: projectTemplate,
        context: {
          id: Number(project.id),
          slug: project.slug,
        },
      })
    })

    // Create all single note pages
    result.data.craft.blogPosts.forEach(({ note }) => {
      createPage({
        path: `/notes/${note.slug}`,
        component: blogPostTemplate,
        context: {
          id: Number(note.id),
          slug: note.slug,
        },
      })
    })

    return Promise.resolve()
  })
}

My GraphQL query is sound, after testing the same query within my gatsby-node.js file, this is what is returned.
{
  "data": {
    "craft": {
      "projects": [
        {
          "id": "34",
          "slug": "some-slug"
        },
        {
          "id": "130",
          "slug": "have-a-slug"
        }
      ],
      "blogPosts": [
        {
          "id": "15",
          "slug": "another-slug"
        },
        {
          "id": "27",
          "slug": "one-slug"
        }
      ]
    }
  }
}

I'm struggling to see where i've gone wrong here, both section's slugs and id's are available yet the error is referring to:
gatsby-node.js:31 result.data.craft.projects.forEach
Apologies if there's not enough context here, i'll try and supply more if required. First question on StackOverflow so just learning the ropes :D


text:
Q: MYSQL ON DUPLICATE KEY UPDATE with more than one key? Say i have a record with id=1, b=20 and c=30. id is my primary key.
I would like to insert into the database a new record only if there is no record with b=20 and c=30.
So far i have set a primary key to id but what about b & c? How can i do that query?
Thank you.

A: You can create a unique key on B and C with.
ALTER TABLE MyTable ADD UNIQUE MyIndex(b,c);


text:
Q: Oracle SQL; Column Update According To Condition In Another Table I have this code:
UPDATE Properties pr
SET price = 5000
WHERE EXISTS (SELECT cm.propertyno
              FROM Comments cm
              GROUP BY cm.propertyno
              HAVING COUNT(cm.propertyno) < 2);

I want to update a column in the Properties table based on the condition of a column in the Comments table. When I run the code above, all rows are updated. Whereas I want the rows with less than 2 propertyno in the Comments table to be updated.
Structure of the tables:

A: Use a correlated subquery:
UPDATE Properties pr
    SET price = 5000
    WHERE EXISTS (SELECT cm.propertyno
                  FROM Comments cm
                  WHERE cm.propertyno = pr.propertyno
                  GROUP BY cm.propertyno
                  HAVING COUNT(cm.propertyno) < 2
                 );

Your version just checks if the GROUP BY query returns any rows -- and presumably it does.  There is no connection to the outer query.
Presumably that connection is on propertyno.


text:
Q: pulling a second unknown IP address We currently have several devices on our network. In the last couple of days, a few of those devices are obtaining IP address in another IP range from an unknown source.
Today I left for about an hour and when I came home my phone would connect to the network but there was no Internet connection. However, I could access Internet from a desktop PC on the same physical network. The issue first appeared on another phone and laptop.
What is the cause and how do I fix it?

A: It sounds like your phone and laptop are connecting to an incorrect nearby wireless access point.  In your phone and laptop wireless settings, check to see if thats the case and remove that connection and be sure to set them to automatically connect to your access point.

A: This definitely sounds like there are multiple DHCP servers.  Since multiple devices are showing the problem, the issue is not likely to be a single broken device that is using a DHCP client.
Since a phone is known to be an issue for at least one device, the issue appears to affect wireless devices.
With some devices, including newer Microsoft Windows versions, you can get some information about the DHCP server that is providing the broken Internet connection.  How you do this would vary between different devices.  With modern versions of Microsoft Windows, running IPConfig /ALL wills how a "DHCP Server" address.  Then, that IP address (e.g. 192.0.2.1) can be used to look for looked up in the ARP table by running "arp -a", which is useful for providing the MAC-48 address.  The first six hexadecimal digits (ignore any other characters like colons or hyphens or periods) of the MAC-48 address is the OUI.  Using the MAC address lookup @ Coffer (or the information can be retrieved from the more official source, IEEE's OUI.txt) can be used to figure out who manufactured that device (assuming that people haven't been making manual changes to a MAC-48 address).
If you confirm that the DHCP server is not equipment that belongs to you, then you need to sever the connection that causes your equipment to contact the DHCP server.  In the case of wireless connections, the typical approach is to tell your own equipment to not automatically connect to certain devices, like unsecured devices.  Then you shouldn't be able to connect to that device unless you enter its password (unless you somehow have its password saved, which seems quite unlikely, but even that situation could be fixed by erasing the saved password).


text:
Q: Using Bluetooth to Send Video I am a second year Electrical Engineering major. I have done a little with the Arduino, but it is not powerful enough to handle video (from what I understand). I would like to capture video from something like a webcam and send it over Bluetooth to either a computer or phone/tablet. Does anyone have any suggestions on how to approach this? I have not found a PCB with a microprocessor powerful enough to handle this that includes Bluetooth. Will I have to make the circuit on my own? I have not designed circuits yet, so I would have no idea on how to design the circuit and handle the transmitter. Any suggestions and help would be greatly appreciated, thanks!

A: Although most people don't believe that bluetooth carries video, in fact video is specified in the Bluetooth spec as the VDP (Video Distribution Profile). You will have to find a module that supports it, such as the following one:
KCWirefree Module
You haven't specified the frame rate for your application, but I believe that bluetooth will be relatively limited in this sense due to the high throughput required.
Despite all this, VDP is rarely supported and can lead to many issues in getting your application running. Your best bet is to use WiFi for this application since it's widely usable and will be much more practical for basically any application. WiFi can support streaming data very well (depending on a lot of parameters such as range, throughput, processing power available, etc).


text:
Q: Кеширование изображений из БД на локальный диск Entity Framework Разрабатываю настольное приложение. Для работы с базой использую Entity Framework (Code First подход).
В БД есть таблица People
CREATE TABLE [dbo].[People]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [nvarchar](50) NOT NULL,
    [PhotoOriginal] [varbinary](max) NULL
)

В EF ей сопоставлены 2 сущности: Person (id, Name, PhotoOriginal )
[Table("Person")]
public partial class Person:INotifyPropertyChanged
{

    public Person()
    {
        Result_question = new HashSet<Result_question>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    [Required]
    [StringLength(50)]
    public string FirstName{get;set;}

    PhotoOriginal _PhotoOriginal;

    virtual public PhotoOriginal PhotoOriginal
    {
        get
        {
            return this._PhotoOriginal;
        }
        set
        {
            if (this._PhotoOriginal != value)
            {
                this._PhotoOriginal = value;
                this.NotifyPropertyChanged("PhotoOriginal");
            }
        }

    }

и PhotoOriginal (id, Image).
[Table("Person")]
public partial class PhotoOriginal:INotifyPropertyChanged
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    byte[] _Image;

    [Column("PhotoOriginal")]
    public byte[] Image
    {
        get
        {
            return this._Image;
        }
        set
        {
            if (this._Image != value)
            {
                this._Image = value;
                this.NotifyPropertyChanged("Image");
            }
        }
    }

    virtual public Person person { get; set; }
}

Код из DBModel
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<PhotoOriginal>()
            .HasKey(e => e.id);

        modelBuilder.Entity<Person>()
            .HasKey(e => e.id)
            .HasRequired(e => e.PhotoOriginal)
            .WithRequiredPrincipal(e => e.person);

        modelBuilder.Entity<Person>().ToTable("People");
        modelBuilder.Entity<PhotoOriginal>().ToTable("People");
    }

Хочу, чтобы при первом обращении к свойству person.PhotoOriginal изображение грузилось из базы и сохранялось на локальный диск. При последующих обращениях (после перезапуска программы тоже) EF не лез в БД, а подтягивал его с диска.
Как можно организовать подобную работу? Как модифицировать сущности? Может на какой обработчик подписаться и отлавливать обращение EF к бд? Приорететнее не писать обертку для сущностей.

A: Можно использовать Second Level Cache for Entity Framework. Он хранит данные в памяти, но можно вместо InMemoryCache написать свою реализацию кэша, хранящего данные на диске.

A: То, что вам надо называется кэширование. EF обеспечивает кэширование только на время жизни контекста. Ранее запрошенные из БД объекты хранятся в памяти. При уничтожении контекста, тем более при перезапуске программы кэш сбрасывается. И это правильно.
Для вашей задачи надо использовать стороннюю библиотеку или даже специализированный продукт: redis, memcached или подобные.

*

*https://github.com/enyim/EnyimMemcached

*https://github.com/StackExchange/StackExchange.Redis


text:
Q: Disposing swt widget dynamically does not resize the parent composite I am adding a SWT Label dynamically as follows:
myLabel = new Label(composite, SWT.NONE);
myLabel.setText("CUSTOM MESSAGE");
composite.layout(true, true);
composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));

Now I am trying to dispose this same widget dynamically as follows:
if(myLabel!=null && !myLabel.isDisposed())
    myLabel.dispose();
composite.layout(true, true);
composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
composite.pack(true);

I also tried with and without the last line composite.pack(true).
The page shows the newly added label properly but when I dispose the label, label is disposed but the space occupied by it remains as it is.

I am using this code in my custom eclipse view.
Here are the few links I referred:
SWT/JFace: remove widgets
SWT composite - redraw problem
Adding more code:
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;

public class MyView extends ViewPart {

    private Composite composite ;
    private Label customLabel ;

    @Override
    public void createPartControl(Composite parent) {

        composite = new Composite(parent, SWT.NONE);
        composite.setLayout(new GridLayout(1, false));

        createTempField("Hello");
        //do stuff
        clearTempField();
        //do stuff
        createTempField("Bye");

    }

    private void createTempField(final String message){
        if(customLabel!=null && !customLabel.isDisposed())
            customLabel.setText(message);
        else if(composite!=null){
            customLabel = new Label(composite, SWT.NONE);
            customLabel.setText(message);
            composite.layout(true, true);
            composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
        }
    }

    private void clearTempField() {
        if(customLabel!=null && !customLabel.isDisposed())
            customLabel.dispose();
        composite.layout(true);
        composite.layout(true, true);
        composite.pack(true);
    }

}


text:
Q: How to load a WPF resource dictionary at design-time I have a WPF window in which some properties are defined as dynamic resources like this:
<Window x:Class="LocSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        MinHeight="350" MinWidth="525"
        Title="{DynamicResource ResourceKey=ResId_Title}"
        FlowDirection="{DynamicResource ResId_FlowDirection_Default}" >
    <Grid>
       <Label Content="{DynamicResource ResId_FirstName}" />
    </Grid>
</Window>

The ResourceDictionary is loaded at runtime to reflect the language choice of the user. And to enable the user to switch the language on the fly.
This works fine at runtime, but at design-time, the resource-defined properties are not shown. It is clear to me that the designer can't show them, because they are not defined at design-time.
I need a way to load a default ResourceDictionary at design-time so that the designer can show anything.

A: EDIT:
In Blend, you can use a Design-time Resources Dictionary file for this case. Visual Studio can read that file but doesn't have the tooling to create one. But if you're not afraid of project files, you can do that by hand.

*

*Add a file DesignTimeResources.xaml to your project.

*Open your project file (*.csproj) and find registration of the DesignTimeResources.xaml file.

*Replace this registration with the following code

<Page Include="Properties\DesignTimeResources.xaml" Condition="'$(DesignTime)'=='true' OR ('$(SolutionPath)'!='' AND Exists('$(SolutionPath)') AND '$(BuildingInsideVisualStudio)'!='true' AND '$(BuildingInsideExpressionBlend)'!='true')">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
  <ContainsDesignTimeResources>true</ContainsDesignTimeResources>
</Page>

Now you can merge all the resource dictionaries you need in the file. Compiler will ignore it, but the designer won't.
See not my article for more details.


text:
Q: android how to remove bracket form database retrive value my database return my value with bracket how do i remove bracket form string  and save without bracket value in my array string?? help me pelase help me value is properly getting i just want to remove bracket around my string and save in ArrayList Meal_groupid
           static ArrayList<String> Meal_groupid = new ArrayList<String>();
        Meal_groupid.add(mCursor2.getString(mCursor2.getColumnIndex("meal_group_id")));

        value is = "[AT]";

       i did  like this

           String formatedString = "[ABC]"

                    .replace("[", "")   //remove the right bracket
                    .replace("]", "");

    Log.i("Formating Stirng",""+formatedString);

   Meal_groupid.add(mCursor2.getString(mCursor2.getColumnIndex("meal_group_id")).replace("[",
                      "").replace("]", ""));
              Log.i("MEalGroup ID",""+Meal_groupid);

    in     logcat  Formating Stirng    ABC

             MEalGroup ID

A: When you get set or get the string you can do a replace to remove the [ and ].
For example:
Meal_groupid.add(mCursor2.getString(mCursor2.getColumnIndex("meal_group_id")).replace("[", "").replace("]", ""));

Hope this helps.

A: As per my knowledge "[" is considered as regex so you need to replace string using
mString.replaceAll("\\[", " ");


text:
Q: java.lang.IllegalStateException: Failed to load ApplicationContext while doing in memory database unit testing using hsqldb spring boot gradle Can some one tell me how to do in-memory database testing using hsqldb for integration tests in spring boot. I don't want to use any xml dataset for that. I am using gradle for build. This is my application-test.properties in src/test/resources:
spring.profiles.active: test
spring.jpa.database: HSQL
spring.datasource.catalog=opensecret
spring.datasource.url= jdbc:hsqldb:mem:${spring.datasource.catalog}
spring.jpa.hibernate.ddl-auto: update
spring.jpa.hibernate.dialect= org.hibernate.dialect.HSQLDialect
spring.datasource.driver-class-username=org.hsqldb.jdbcDriver
spring.datasource.username: root
spring.datasource.password: password

This is my UserServiceImplTest class:
package com.opensecret.Service.user;

import com.opensecret.model.Authority;
import com.opensecret.model.UserInfo;
import com.opensecret.Service.user.UserService;
import com.sun.prism.impl.BaseContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@Rollback(true)
@ActiveProfiles("test")
public class UserServiceImplTest{

    @Autowired
    private UserService userService;

    @Before
    public void setUp(){
        UserInfo userInfo = new UserInfo();
        userInfo.setEmail("abc@email.com");
        userInfo.setUsername("james");
        userInfo.setPassword("password");
        userInfo.setAuthority(Authority.USER.toString());
        userInfo.setEnabled(true);
        userInfo.setCreated_at(new Date());
        userInfo.setUpdated_at(new Date());
        userService.createUser(userInfo);
    }

    @Test
    public void testGetAllUsers() throws Exception {
        Collection<UserInfo> users = userService.getAllUsers();
        assertEquals(users.size(), 1);

        List userList = new ArrayList(users);
        UserInfo user = (UserInfo) userList.get(0);
        assertEquals(user.getEmail(),"abc@email.com");
        assertEquals(user.getUsername(),"james");
        assertEquals(user.getPassword(),"password");
        assertEquals(user.getAuthority(),"USER");
        assertEquals(user.isEnabled(),true);
    }
}

I am getting this error
    java.lang.IllegalStateException: Failed to load ApplicationContext

        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
        at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
    Caused by: java.lang.IllegalArgumentException: Cannot load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration or @ContextHierarchy.
        at org.springframework.util.Assert.notNull(Assert.java:115)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:91)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
        ... 28 more
10:57:38.709 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@20398b7c] to prepare test instance [com.opensecret.Service.user.UserServiceImplTest@6737fd8f]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228) ~[spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230) [spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249) [spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89) [spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193) [spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74) [junit-rt.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [idea_rt.jar:na]
Caused by: java.lang.IllegalArgumentException: Cannot load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration or @ContextHierarchy.
    at org.springframework.util.Assert.notNull(Assert.java:115) ~[spring-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:91) ~[spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 28 common frames omitted10:57:38.724 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@32709393 testClass = UserServiceImplTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@3d99d22e testClass = UserServiceImplTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'null', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null].


text:
Q: Onclick is not a reserved word. So how does javascript know to associate a function called onclick with a click event I am watching this tutorial video to really understand (as opposed to just use) javascript events.
http://www.youtube.com/watch?v=bOCbA2TYJ0M
At minute 1:29 the author assigns a function to the onclick attribute of an object.

I know this handles a click event -- but I don't see onclick as a reserved word.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words
How does the browser map the .onclick function to the clicking of the mouse? Is there anything fundamental about the javascript language that associates the onclick function with the act of clicking a mouse -- or do browsers just associate the click event with the on click function by convention?

A: Reserved words are words that have a special meaning in the context of the language. The onclick function has no special meaning to the language javascript, but only has a meaning to the browser, therefore it is not a reserved word.
Think of it this way: if onclick would have been a reserved word it would have been impossible to create an onclick function that would not be a click event handler nor would it be possible to create a variable called onclick.
As you said, the browser associates the click event with the on click function by convention.

A: As user mrhobo already said onclick has no special meaning to the language javascript. I would like to complement information  on the part [onclick] only has a meaning to the browser.
In the html 4.01. specification for the button-element you will find this definition:
<!ELEMENT BUTTON - -
     (%flow;)* -(A|%formctrl;|FORM|FIELDSET)
     -- push button -->
<!ATTLIST BUTTON
  %attrs;              -- %coreattrs, %i18n, %events --
  ....
>

In the list of %events you will find.
<!ENTITY % events
 "onclick     %Script;       #IMPLIED  -- a pointer button was clicked --
  ondblclick  %Script;       #IMPLIED  -- a pointer button was double clicked--
  onmousedown %Script;       #IMPLIED  -- a pointer button was pressed down --
  onmouseup   %Script;       #IMPLIED  -- a pointer button was released --
  onmouseover %Script;       #IMPLIED  -- a pointer was moved onto --
  ....
>

The part %events is defined in chapter 18.2.3 Intrinsic events: The onclick event occurs when the pointing device button is clicked over an element. This attribute may be used with most elements.
So to implement html the browser has to provide an onclick-attribute for button to comply with the specification.


text:
Q: ImportError: DLL load failed: The file cannot be accessed by the system Traceback (most recent call last):

  File "<ipython-input-9-a40793f9ded7>", line 7, in <module>
    from sklearn.model_selection import train_test_split

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\__init__.py", line 76, in <module>
    from .base import clone

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\base.py", line 16, in <module>
    from .utils import _IS_32BIT

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\__init__.py", line 20, in <module>
    from .validation import (as_float_array,

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 21, in <module>
    from .fixes import _object_dtype_isnan

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\fixes.py", line 18, in <module>
    from scipy.sparse.linalg import lsqr as sparse_lsqr  # noqa

  File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\__init__.py", line 113, in <module>
    from .isolve import *

  File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\isolve\__init__.py", line 6, in <module>
    from .iterative import *

  File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py", line 10, in <module>
    from . import _iterative

ImportError: DLL load failed: The file cannot be accessed by the system.

Got this error while trying to run some already used python scripts on pycharm. Has anybody had this error before and has he solved it? It started after I installed a package in python but never used it. The problem is located when I try to import train_test_split on scikit-learn and tensorflow, the sklearn package and seaborn. The other parts of the code seem unaffected.
I have already reinstalled anaconda and python as well as changing the python files. Any help would be greatly appreciated.

A: After reinstalling the python as well as updating all the packages (conda update --all) and changing the PATH file, it seems that the issue is solved in all of my IDE's except PyCharm. It seems that all that remains is an interpreter issue. I will post updates if something else comes into my attention.


text:
Q: How to keep linearGradient position where the animate stopped Is there any option to keep the gradient position where the animation finished ?

<svg id="battery" width="110px" height="88px" viewBox="0 0 110 88" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
  <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
    <g id="Group" fill="#EAEAEA">
      <path d="M104,30.2724875 C104.164709,30.2576038 104.331485,30.25 104.5,30.25 C107.537566,30.25 110,32.7220822 110,35.7458573 L110,53.1708094 C110,56.2060875 107.531385,58.6666667 104.5,58.6666667 C104.331455,58.6666667 104.164681,58.6590557 104,58.6441617 L104,82.0033234 C104,85.3151964 101.311488,88 97.9970362,88 L6.0029638,88 C2.68761844,88 0,85.3182852 0,82.0033234 L0,5.99667663 C0,2.68480358 2.68851188,0 6.0029638,0 L97.9970362,0 C101.312382,0 104,2.68171476 104,5.99667663 L104,30.2724875 L104,30.2724875 Z M5,10.991014 C5,7.68226832 7.68678744,5 11.0051618,5 L92.9948382,5 C96.3113975,5 99,7.68493655 99,10.991014 L99,77.008986 C99,80.3177317 96.3132126,83 92.9948382,83 L11.0051618,83 C7.68860254,83 5,80.3150634 5,77.008986 L5,10.991014 Z"
      id="loading-frame" fill="url(#loading)"></path>
      <linearGradient id="loading" x1="0">
        <stop offset="50%" stop-color="#ff0000"></stop>
        <stop offset="50%" stop-color="#eaeaea"></stop>
        <animate attributeName="x1" dur="3s" from="-100%" to="100%" />
      </linearGradient>
    </g>
  </g>
</svg>

A: You have to specify an additional attribute for animate:
fill="freeze"

<svg id="battery" width="110px" height="88px" viewBox="0 0 110 88" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
  <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
    <g id="Group" fill="#EAEAEA">
      <path d="M104,30.2724875 C104.164709,30.2576038 104.331485,30.25 104.5,30.25 C107.537566,30.25 110,32.7220822 110,35.7458573 L110,53.1708094 C110,56.2060875 107.531385,58.6666667 104.5,58.6666667 C104.331455,58.6666667 104.164681,58.6590557 104,58.6441617 L104,82.0033234 C104,85.3151964 101.311488,88 97.9970362,88 L6.0029638,88 C2.68761844,88 0,85.3182852 0,82.0033234 L0,5.99667663 C0,2.68480358 2.68851188,0 6.0029638,0 L97.9970362,0 C101.312382,0 104,2.68171476 104,5.99667663 L104,30.2724875 L104,30.2724875 Z M5,10.991014 C5,7.68226832 7.68678744,5 11.0051618,5 L92.9948382,5 C96.3113975,5 99,7.68493655 99,10.991014 L99,77.008986 C99,80.3177317 96.3132126,83 92.9948382,83 L11.0051618,83 C7.68860254,83 5,80.3150634 5,77.008986 L5,10.991014 Z"
      id="loading-frame" fill="url(#loading)"></path>
      <linearGradient id="loading" x1="0">
        <stop offset="50%" stop-color="#ff0000"></stop>
        <stop offset="50%" stop-color="#eaeaea"></stop>
        <animate attributeName="x1" fill="freeze" dur="3s" from="-100%" to="100%" />
      </linearGradient>
    </g>
  </g>
</svg>


text:
Q: Glade editor not showing icons in palette I've just installed the GTK+ Glade 3.6.7 designer on Windows XP and there are no icons in the palette.  I can select small icons or large icons from the view menu but neither will show.  I just get red X images. The toolbar icons do show.

A: This sounds like a bug. You can file a bug report here.