text:
Q: Get Client system's directory/folder list using client script HTML/JS Related to this topic I know that impossible to get local computer folder list from webpage.
https://forums.asp.net/t/1326036.aspx?Get+Client+system+s+directory+folder+list+using+client+script
But how about if I open a html file on my own computer, it will be any way to do it?
Or i need to create .exe which will display my html and include some function to read files on computer...
Thank for any sugesstions.


text:
Q: Creating Charts & Graphs with Python I'm looking for a python library/module that will allow me to create eye catching charts. The module must have/support the following

*

*Windows Support
As I work mainly in windows(using Eclipse in Windows), this is crucial, a simple install .exe file (or adequate install instructions a must)

*Work on Python 2.7
I've got Python 2.7.2 installed don't really want to go get some other thing.

*Not require being on the web
I've looked at googlepychart, and it looks like you need to be on the web to make it work, I'm not on the world wide web, actually behind a VERY restrictive firewall.

*Output should be viewable from HTML browser
While I cannot get onto the WorldWideWeb, I can see localhost, it would be great if the chart result be viewable in a browser.

*Good documentation, at the very least some samples on how I can use the library.

If there are any suggestions on how I can create a web app using python that simply display/charts the data i pass in, such advice would be much appreciated

A: If you can do without using a browser, you can use one of Python Plotting Libraries. If you insist on using the browser, you would be better off using a javascript-based library for the view. I have used web2py web framework before along with protovis. But a simpler web framework like Bottle or CherryPy can also be used to pass the data to the view. Bottle has a Simple Template Engine (very similar to what I used in Web2py).
Developing in two languages (one of which is javascript) is a bit of a pain. You could use something like Pyjamas that translates python into javascript but I am not really sure if this would work out well, and I have no experience with it.

A: You may want to give details on the types of charts you want to make. Simple graphs are easy with sage and there are lots of options as compared to matlab. If you want more of a powerpoint chart, or picture you can insert into a word doc, then that's a little different.
If you can get something to create chart images, then you can hook it into a python web framework, such as django or pylons. That will allow you to set up a loopback server to host the page on your machine and view it on your machine. This is quite a bit more complex though.
My suggestion is to break your program down into pieces. It's like building a house out of lego brinks. You have an idea what you want it to look like, but the details determine everything. Break it down into the smallest pieces you can, and define larger pieces as groups of smaller pieces
The house is just several rooms. A room is just 4 walls, a floor and a ceiling. A wall is just several boards, and a board is 2x4.  Once you break all the parts down, then you'll know not only what you need to make, but what you need to find for each piece.
You've got a good start with your list of requirements. That defines what you want your program to do. Now you need to work backwards to define the different parts. Don't get hung up on how they work, define the way they mesh.
For a simple python script to create a web server: see here. Note the section on dynamic content. By plugging that into a "black box" that produces your charts, you suddenly have a simple working setup. The charts section doesn't care how the user gets them, it just makes a chart and passes it out. The server doesn't care how the chart is made, it just serves it up.
This section of the sage manual has instructions for saving a plot after you create it.

A: Plotly lets you make graphs using their online Python sandbox. Their gallery has some example scientific graphs with the Python scripts that generated them: https://plotly.com/python/. Here's a sample from the gallery:

A: matplotlib has become a mature and widely used graphing package.
As for your interaction with a web browser, you may have to use another package in conjunction. I suggest CherryPy because it is simple.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setup a testdirectory for a Rails Plugin I started to create a rails plugin which includes some class and instance methods of Controller and Model.
I fist tried to setup the tests for the Model.
Add a models directory in my test dir. But i noticed - i need the geokit-rails plugin for my model to be able to "acts_as_mappable"
How to get the plugin into the test dir?
I tryied to copy it to /test/plugins/geokit-rails and include it in my test_helper?
require 'geokit'
require PLUGIN_ROOT + '/test/plugins/geokit-rails/lib/geokit-rails.rb'

I get an error from the plugin
MissingSourceFile: no such file to load — geokit-rails/defaults

any suggestions?

A: i got the plugin running with some changes in geokit-rails/lib/geokit-rails.rb
dir = File.join(File.dirname(__FILE__))
require dir + '/geokit-rails/defaults'
require dir + '/geokit-rails/adapters/abstract'
require dir + '/geokit-rails/acts_as_mappable'
require dir + '/geokit-rails/ip_geocode_lookup'


text:
Q: How to smoothen 2D color map in matplotlib My question is if there is any way to smoothen 2D color map using matplotlib? My code:
def map():
    # setup parameters
    j = 0
    N = 719
    N2 = 35
    x = np.linspace(190, 800, N)
    y = np.linspace(10, 360, N2) # (1,2,3), 1 - start Temp, 2- end temp + 10K, 3 - how many steps to reach it
    z = []
    A = np.zeros([35,719]) # [1 2], 1 - number of spectras, 2 - delta wavelength
    # run
    for i in range(10,360,10):
            Z = []
            file_no = (str(0) + str(i))[-3:]
            data = np.genfromtxt('C:\\Users\\micha_000\\Desktop\\Measure\\' + '160317_LaPONd_g500_%s_radio.txt'%file_no,skip_header = 12)
            for line in data:
                Z.append(line[1]-6000)
            A[j,:] = Z
            j = j+1
    X, Y = np.meshgrid(x,y)
    fig, ax = plt.subplots()
    cs = ax.contourf(X, Y, A, cmap=cm.viridis)
    norm = colors.Normalize(vmin = 0, vmax = 1)
    plt.xlabel('wavelength [nm]')
    plt.ylabel('temperature [K]')
    plt.title('LaPONd_g500')
    cbar = fig.colorbar(cs, norm = norm)
    plt.savefig('C:\\Users\\micha_000\\Desktop\\Measure\\LaPONd_g500_radio_map.png')
    plt.show()
    plt.close()

And here is an example of what i receive:

Is there any way to make it look better by smoothening pixels transitions?

A: The problem is not the palette (which are all smooth in matplotlib), but that fact that you are using contourf(), which generates a finite set of countours, each with a single color, and is therefore not smooth. The default is something like 10 countours.
One quick solution:, increase the number of contour levels  by specifying levels (you can also give an array of which levels to include):
cs = ax.contourf(X, Y, A, cmap=cm.viridis, levels=100)

Better yet, since it seems your data data is already on a grid (e.g. X,Y,Z values for each pixel), you should use pcolormesh(X,Y,A) instead of contour to plot it. That will plot with fully continuous values, rather than steps.

A: open the png as an array, and blur it with a mean value filter. search convolution filters to learn more. I've just used a 25 pixel square averaging filter, but you could use a gaussian distribution to make it look smoother..
import numpy as np
from scipy import ndimage, signal, misc

img = ndimage.imread('C:/.../Zrj50.png')

#I used msPaint to get coords... there's probably a better way
x0, y0, x1, y1 = 87,215,764,1270 #chart area (pixel coords)

#you could use a gaussian filter to get a rounder blur pattern
kernel = np.ones((5,5),)/25 #mean value convolution

#convolve roi with averaging filter
#red
img[x0:x1, y0:y1, 0] = signal.convolve2d(img[x0:x1, y0:y1, 0], kernel, mode='same', boundary='symm')
#green
img[x0:x1, y0:y1, 1] = signal.convolve2d(img[x0:x1, y0:y1, 1], kernel, mode='same', boundary='symm')
#blue
img[x0:x1, y0:y1, 2] = signal.convolve2d(img[x0:x1, y0:y1, 2], kernel, mode='same', boundary='symm')

#do it again for ledgend area
#...

misc.imsave('C:/.../Zrj50_blurred.png', img)

Using a gaussian instead is pretty easy:
#red
img[x0:x1, y0:y1, 0] = ndimage.gaussian_filter(img[x0:x1, y0:y1, 0], 4, mode='nearest')


text:
Q: connection line is hidden when div1 and div2 in same line there are 2 divs, box1 and box2 and are connected by .line. Connection line is working fine when 'box1' in left of box2 or box1 in right of 'box2'.However, if both are in same line(one in top and other one  on bottom) line is removed !

why connection line is removed when divs in same line ?

$(function () {
$('.box').draggable().on('drag', function () {
    var x1 = $('.box1').position().left;
    var y1 = $('.box1').position().top;
    var x2 = $('.box2').position().left;
    var y2 = $('.box2').position().top;

    if (x1 > x2) {
        var x3 = x1;
        var y3 = y1;
        x1 = x2;
        y1 = y2;
        x2 = x3;
        y2 = y3;
    }
    if (x1 == x2  ) {
        $('.line').css({
            height: Math.abs(y2 - y1),
            left: x1 + ($('.box1').width() / 2),
            width: 1,
            '-webkit-transform': 'rotate(0deg)',
            '-moz-transform': 'rotate(0deg)',
            '-ms-transform': 'rotate(0deg)',
            '-o-transform': 'rotate(0deg)',
            'transform': 'rotate(0deg)',
            'zoom': 1
        });
    } else {  // else calculate angle and rotate line
        var a = (y2 - y1) / (x2 - x1);
        var radians = Math.atan(a);
        var degrees = radians * (180 / Math.PI);
        $('.line').css({
            top: y1 + ($('.box1').height() / 2),
            left: x1 + ($('.box1').width() / 2),
            width: Math.abs(x2 - x1),
            height: 1,
            'transform-origin': '0 0',
            '-webkit-transform': 'rotate(' + degrees + 'deg)',
            '-moz-transform': 'rotate(' + degrees + 'deg)',
            '-ms-transform': 'rotate(' + degrees + 'deg)',
            '-o-transform': 'rotate(' + degrees + 'deg)',
            'transform': 'rotate(' + degrees + 'deg)',
            'zoom': 1
        });
    }
});
});
.box{ draggable:true; position:absolute; width:100px; height:100px; background:red; cursor:move; }
.box1{ top:25px; }
.box2{ left:200px; }
.line{ height:1px; width:1px; background:blue; position:absolute; -moz-transform-origin:0% 0%; -webkit-transform-origin:0% 0%; transform-origin:0% 0%; }

    <form id="form1" runat="server">

    </form>

A: You need to calculate distance between 1 points using both axles now only by X in your case when x1 != x2:
http://www.mathwarehouse.com/algebra/distance_formula/index.php
In JS:
Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2))

$(function () {
$('.box').draggable().on('drag', function () {
    var x1 = $('.box1').position().left;
    var y1 = $('.box1').position().top;
    var x2 = $('.box2').position().left;
    var y2 = $('.box2').position().top;

    if (x1 > x2) {
        var x3 = x1;
        var y3 = y1;
        x1 = x2;
        y1 = y2;
        x2 = x3;
        y2 = y3;
    }
    if (x1 == x2  ) {
        $('.line').css({
            height: Math.abs(y2 - y1),
            left: x1 + ($('.box1').width() / 2),
            width: 1,
            '-webkit-transform': 'rotate(0deg)',
            '-moz-transform': 'rotate(0deg)',
            '-ms-transform': 'rotate(0deg)',
            '-o-transform': 'rotate(0deg)',
            'transform': 'rotate(0deg)',
            'zoom': 1
        });
    } else {  // else calculate angle and rotate line
        var a = (y2 - y1) / (x2 - x1);
        var radians = Math.atan(a);
        var degrees = radians * (180 / Math.PI);
        $('.line').css({
            top: y1 + ($('.box1').height() / 2),
            left: x1 + ($('.box1').width() / 2),
            width: Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)),
            height: 1,
            'transform-origin': '0 0',
            '-webkit-transform': 'rotate(' + degrees + 'deg)',
            '-moz-transform': 'rotate(' + degrees + 'deg)',
            '-ms-transform': 'rotate(' + degrees + 'deg)',
            '-o-transform': 'rotate(' + degrees + 'deg)',
            'transform': 'rotate(' + degrees + 'deg)',
            'zoom': 1
        });
    }
});
});
.box{ draggable:true; position:absolute; width:100px; height:100px; background:red; cursor:move; }
.box1{ top:25px; }
.box2{ left:200px; }
.line{ height:1px; width:1px; background:blue; position:absolute; -moz-transform-origin:0% 0%; -webkit-transform-origin:0% 0%; transform-origin:0% 0%; }

    <form id="form1" runat="server">

    </form>


text:
Q: How to use Ionic CLI with pnpm How is it possible to use pnpm instead of npm with ionic cli?
it has some good benefits rather than npm, Like smaller storage usage, Showing progress when some package is downloading and etc...

A: Run this command to change the default package manager of ionic CLI from npm to pnpm:
ionic config set -g npmClient pnpm

also if you want to use yarn instead of npm :
ionic config set -g npmClient yarn


text:
Q: How to add Items from an ArrayList of Objects to a JList. I want to add the toStrings from items in an Arraylist of Objects to a Jlist through a for loop. I tried this.
for (int i = 0; i < customer.slist.size(); i++) {
        ((DefaultListModel) checkOutList.getModel()).addElement(customer.slist.toString());//slist is an array of objects.
    }

But it didnt work. Also NetBeans tells me .addElement()is not a method for a JList when I tried
checkOutList.addElement("anything")

A: instead of

customer.slist.toString()

try:

customer.slist.get(i).toString();

in your code.

A: I have this implementation:
This is custom JList:
@SuppressWarnings("serial")
public class JListCustomered<T extends JListPresentedInterface> extends JList<T>{

private List<T> list;
private List<T> selectedList;

public JListCustomered(List<T> list){
    super();
    this.list=list;
    setCellRenderer(new JListRenderer());
    setModel(new ListModel());
}

public void loadData(List<T> list){
    getSelectedList().clear();
    this.list=list;
    setModel(new ListModel());
}

/** {@link JListCustomered#list} */
public List<T> getList() {
    if(list==null)
        list=new ArrayList<T>();
    return list;
}

/** {@link JListCustomered#selectedList} */
public List<T> getSelectedList() {
    if(selectedList==null)
        selectedList=new ArrayList<T>();
    return selectedList;
}

public class JListRenderer extends JLabel implements ListCellRenderer<T>{
    JSeparator separator;

    private JListRenderer(){
        separator=new JSeparator(JSeparator.HORIZONTAL);
        setOpaque(true);
    }

    /** @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean) */
    public Component getListCellRendererComponent(JList<? extends T> list, T value, int index, boolean isSelected, boolean cellHasFocus) {
        if(value.isSeparator()){
             return separator;
        }

        List<T> selected = getSelectedList();
        if (isSelected) {
            if (!selected.contains(value)) {
                getSelectedList().add(value);
            }
            this.setBackground(getSelectionBackground());
        } else {
            if (selected.contains(value)) {
                getSelectedList().remove(value);
            }
            setBackground(Color.WHITE);
        }
        setFont(list.getFont());
        setText(value.getJListName());
        return this;
    }
}

private class ListModel implements javax.swing.ListModel<T>{

    /** @see javax.swing.ListModel#getSize() */
    public int getSize() {
        return getList().size();
    }

    /** @see javax.swing.ListModel#getElementAt(int) */
    public T getElementAt(int index) {
        return getList().get(index);
    }

    /** @see javax.swing.ListModel#addListDataListener(javax.swing.event.ListDataListener) */
    public void addListDataListener(ListDataListener l) {
    }

    /** @see javax.swing.ListModel#removeListDataListener(javax.swing.event.ListDataListener) */
    public void removeListDataListener(ListDataListener l) {
    }

}
}

below interface for object, which you want add to JList:
public interface JListPresentedInterface {

public String getJListName();
public boolean isSeparator();
}

you can reaload data on JList using method loadData, get selected list getList


text:
Q: detect non ascii characters in a string How can I detect non-ascii characters in a vector of strings in a grep like fashion.  For example below I'd like to return c(1, 3) or c(TRUE, FALSE, TRUE, FALSE):
x <- c("façile test of showNonASCII(): details{",
    "This is a good line", "This has an ümlaut in it.", "OK again. }")

Attempt:
y <- tools::showNonASCII(x)
str(y)
p <- capture.output(tools::showNonASCII(x))

A: A bit late I guess but it could be useful for the next readers.
You can find these functions:

*

*showNonASCII(<character_vector>)

*showNonASCIIfile(<file>)
in the tools R package (see https://stat.ethz.ch/R-manual/R-devel/library/tools/html/showNonASCII.html). It does exactly what is asked here: show non ASCII characters in a string or in a text file.

A: Came across this later using pure base regex and so simple:
grepl("[^ -~]", x)
## [1]  TRUE FALSE  TRUE FALSE

More here: http://www.catonmat.net/blog/my-favorite-regex/

A: another possible way is to try to convert your string to ASCII and the try to detect all the generated non printable control characters which couldn't be converted
grepl("[[:cntrl:]]", stringi::stri_enc_toascii(x))
## [1]  TRUE FALSE  TRUE FALSE

Though it seems stringi has a built in function for this type of things too
stringi::stri_enc_mark(x)
# [1] "latin1" "ASCII"  "latin1" "ASCII"

A: A stringr regex solution:
library(stringr)
x <- c("façile test of showNonASCII(): details{",
    "This is a good line",
    "This has an ümlaut in it.", "OK again. }")
str_detect(x, "[^[:ascii:]]")
# => [1]  TRUE FALSE  TRUE FALSE

The [^[:ascii:]] pattern matches any non-ASCII character.
The [[:ascii:]] pattern matches any ASCII character.
If you ever need to make sure the whole string consists of non-ASCII chars, use
str_detect(x, "^[^[:ascii:]]+\\z")

where ^ matches the start of string and \z matches the very end of string.

A: Why don't you extract the relevant code from showNonASCII?
x <- c("façile test of showNonASCII(): details{",
       "This is a good line", "This has an ümlaut in it.", "OK again. }")

grepNonASCII <- function(x) {
  asc <- iconv(x, "latin1", "ASCII")
  ind <- is.na(asc) | asc != x
  which(ind)
}

grepNonASCII(x)
#[1] 1 3


text:
Q: CakePHP add model name to information returned in queries I want to include the model name in the returned results of a query using CakePHP's find() methods.
For instance, if I do a
$person = $this->Person->find("first", array(
    "conditions" => array (
        "Person.id" => $id
    )
));

I get back
Person{id:1, name:Abraham Lincoln}

I want to get back
Person{id:1, name:Abraham Lincoln, model: Person}

I'm fairly front-end oriented. I know I could loop through results and add these at the controller level, but that seems tedious, especially since most of my queries are far more complex, utilizing contain(). I imagine somewhere in CakePHP's core there's a place this kind of functionality could be added, I just don't know where.
Essentially, I'm looking for where CakePHP casts the database query to a php variable, so I can inject my additional model value.
I do know I will never use the column name "model" anywhere in my application. I'm also certain I want this information where I'm requesting it to be in every singe query, as little sense as it may make.

A: Add this to every model where you need it:
public function afterFind($results, $primary = false) {
    foreach($results as $ikey => $item) {
        foreach($item as $skey => $subitem) {
            if(is_array($subitem))
                $results[$ikey][$skey]['model'] = $skey;
            else $results[$ikey]['model'] = $skey;
        }
    }
    return $results;
}

Unfortunately I wasn't able to get this work when I stored it in AppModel.


text:
Q: JSON and webservice in Android Listview I'm try to get the data from server using web service I have a web service.
The webservice returns data in JSON format.
this is my web service
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function GetTituli() As String
    Dim conn As SqlConnection = New SqlConnection("Server=192.168.0.123\cmdsql;uid=user;pwd=password;database=testjoson")
    conn.Open()
    Dim cmd As SqlCommand = New SqlCommand("Select Id_Agjenda,Titulli,Useri,data_takimit,Kategoria,data_e_publikimit,e_kryer,rezultati from tblagjenda ;", conn)
    Dim ds As DataSet = New DataSet()
    Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
    da.Fill(ds)
    conn.Close()
    Dim TitulliArray()() As String = New String(ds.Tables(0).Rows.Count)() {}
    Dim i As Integer = 0
    For Each rs As DataRow In ds.Tables(0).Rows
        TitulliArray(i) = New String() {rs("Titulli").ToString()}
        i = i + 1
    Next
    Dim js As JavaScriptSerializer = New JavaScriptSerializer()
    Dim sJSON As String = js.Serialize(TitulliArray)
    Return sJSON
End Function

this is my json
[["test from json"],["test from json2"],["test from jso3"],["test from json4"]]

this is my activity
enter code here
public class Notat_e_studentit extends Fragment {
SessionManager session;
private static final String Soap_Action_JSONEXP="http://tempuri.org/GetTituli";
private static final String METHOD_NAME_JSONEXP="GetTituli";
private static final String NAMESPACEEXP="http://tempuri.org/";
private static final String URL_jsEXP="http://mydomain/webservice/Service1.asmx?wsdl";
private String TAG="beni";
ListView listnewlend;
private static String responseJSON;
ProgressBar pg;
Gson gson=new Gson();
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
    session=new SessionManager(getActivity());
    session.checkLogin();
    View view=inflater.inflate(R.layout.notat_e_studentit,container,false);
    return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
    listnewlend=(ListView)getActivity().findViewById(R.id.cmdlista);
    Thread cmdthredlista=new Thread(){
        @Override
    public void run(){
            SoapObject cmdrequest=new SoapObject(NAMESPACEEXP,METHOD_NAME_JSONEXP);
            System.out.println("requsest "+cmdrequest);
            SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet=true;
            envelope.setOutputSoapObject(cmdrequest);
            HttpTransportSE ahttptransport=new HttpTransportSE(URL_jsEXP);
            try {
                System.out.println("request "+cmdrequest);
                ahttptransport.call(Soap_Action_JSONEXP,envelope);
                //final SoapPrimitive response=(SoapPrimitive)envelope.getResponse();
                SoapPrimitive response=(SoapPrimitive)envelope.getResponse();
                responseJSON=response.toString();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String[] placelist;
                            placelist=gson.fromJson(responseJSON,String[].class);
                            ArrayAdapter<String>cmdlistaadapteri;
                            cmdlistaadapteri=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,placelist);
                            listnewlend.setAdapter(cmdlistaadapteri);
                        }
                        catch (Exception e){
                            e.printStackTrace();
                            System.out.println("error ");
                        }
                    }
                });
            }
            catch (Exception e){
                e.printStackTrace();
                System.out.println("error ");
            }
        }
    };
    cmdthredlista.start();
}}

but the data will not dispaly in the listview.
this is my logcat
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 3

11-20 14:41:07.186      903-903/com.cmd.dfa W/System.err﹕ at com.google.gson.Gson.fromJson

A: You have
[
 ["a"],
 ["b"],
 ["c"]
]

It's a List of List...
You should have
[
 "a",
 "b",
 "c"
]

which is a list of (object) String.
You json should be
["test from json", "test from json2" , "test from jso3" , "test from json4"]

If you can't change your json, you may want to try with
ArrayList<ArrayList<String>> placelist;
placelist = gson.fromJson(response, new TypeToken<ArrayList<ArrayList<String>>>()
{
}.getType());

And retrieve a string with
placelist.get(index).get(0); // 0

but it's .......bad ;-)


text:
Q: Get key from first array on Search Array in Array PHP I have some question about searching a value in multidimensional array.
This is my code
$groep = array(
                1 => array("111","222"),
                2 => array("333","444")
                );
$groepje = 0;
foreach($groep as $row => $value){
    if(array_search($serial,$value)){
        $groepje = $row;
    }
}

Now i want to set $groepje to the 'head'key of the array, so if $serial = 111 it have to give back 1, if $serial = 444 it have to give back 2.
What i do get is the wrong number, so 0 if its 111 or 333.
Can someone tell me what i'm doing wrong?
Thanks!

A: *

*You can use in_array to search for the specified serial.

*I renamed some of your variables to make it clearer.

*Used break to break out of the loop once we know we've found what we're looking for.

*assuming you define $serial above your foreach
http://sandbox.onlinephpfunctions.com/code/ca34f236ca2d19af8c098120de1707f14bed285a
<?php

$groep = array(
    1 => array("111","222"),
    2 => array("333","444")
);

$groepje = 0;
$serial= '333';

foreach($groep as $key => $data) {

    if (in_array($serial, $data)) {
        $groepje = $key;
        break;
    }
}

// 2
echo $groepje;


text:
Q: simple UPDATE query on large table has bad performance I need to do the following update query through a stored procedure:
UPDATE table1
SET name = @name (this is the stored procedure inputparameter)
WHERE name IS NULL

Table1 has no indexes or keys, 5 columns which are 4 integers and 1 varchar (updatable column 'name' is the varchar column)
The NULL records are about 15.000.000 rows that need updating. This takes about 50 minutes, which I think is too long.
I'm running an Azure SQL DB Standard S6 (400DTU's).
Can anyone give me an advise to improve performance?

A: As you don't have any keys, or indexes, I can suggest following approach.
1- Create a new table using INTO (which will copy the data) like following query.
  SELECT
       CASE
              WHEN NAME IS NULL THEN @name
              ELSE NAME
       END AS NAME,
       <other columns >
INTO   dbo.newtable
FROM table1

2- Drop the old table
drop table table1

3- Rename the new table to table1
exec sp_rename 'dbo.newtable', 'table1'

Another approach can be using batch update, sometime you get better performance compared to bulk update (You need to test by adjusting the batch size).
WHILE EXISTS (SELECT 1 FROM table1 WHERE name is null)
BEGIN
    UPDATE TOP (10000) table1
    SET name = @name
    WHERE n ame is null
END

A: can you do with following method ?
UPDATE table1
SET name = ISNULL(name,@name)

for null values it will update with @name and rest will be updated with same value.

A: No.  You are updating 15,000,000 rows which is going to take a long time.  Each update has overhead for finding the row and logging the value.
With so many rows to update, it is unlikely that the overhead is finding the rows.  If you add an index on name, the update is going to actually have to update the index as well as updating the original values.
If your concern is locking the database, you can set up a loop where you do something like this over and over:
UPDATE TOP (100000) table1
    SET name = @name (this is the stored procedure inputparameter)
    WHERE name IS NULL;

100,000 rows should be about 30 seconds or so.
In this case, an index on name does help.  Otherwise, each iteration of the loop would in essence be reading the entire table.


text:
Q: Is it possible to find out if/when my account has received a (review) ban before? I'm wondering if there's a way for a user to find out if (and when) their account has ever received a review ban (or any other kind of ban for that matter) on a given site.
Can this information be determined somehow by the user or does it require asking help from a moderator? If you're a site moderator, would you be okay with receiving such requests?

A: Well - wierdly enough, the only site I've ever been review banned on happened while I was a sitting moderator. From what I can tell on the user end  there's no indicator on your profile, or at all other than on the specific review queue while you review. Mods do have access to this information however, and can look it up.
Personally I'd be fine with it - it's your own information and it's not hugely taxing to check for a single user. YMMV with other mods.


text:
Q: Why does the "wrong" instance variable get modified? I'm confused because I thought this referred to the current object calling on the method.
So why didn't the instance variable x in my object not get changed when calling on an inherited method?
Superclass:
public class SuperBoss
{
  int x = 50;

  public void changeX()
  {
   this.x  = 20;
  }
}

Subclass:
public class Boss extends SuperBoss
{
 int x = 10;
 public static void main(String[] args)
 {
  Boss b = new Boss();
  b.changeX();
  System.out.println(b.x); //prints 10
 }
}

Why does it print 10 and not 20?

A: Short answer: Because field accesses are not virtual in Java.

SuperBoss declares x.
When Boss declares x, x does not become a 'virtual' field - it becomes a new field that is hidden from the superclass's field.
When you call changeX on your Boss, which is a method in SuperBoss, SuperBoss doesn't know about Boss.x and accessing x is not virtual, so it just accesses SuperBoss.x.
If you need accesses to x to be virtual, you need to provide a getX method, and override the getX method in Boss. Now when SuperBoss's methods call getX, it gets rerouted to the getX in Boss.

A: When you declare int x = 10 in your subclass you're hiding the superclass variable from everyone when they're looking at the subclass.
When the superclass calls this.x it's not looking at the subclass, so it's allowed to get it's own version of the variable.
Variables are not actually stored by they're code name at runtime, so redefining them like this doesn't work - SuperBoss#x will resolve to one symbol in the symbol table and Boss#x will resolve to another, so they both still exist, if you know how to get at them.


text:
Q: Using client-customized resources (resx) as well as default resources I'm trying to find info on how best to allow localization and client-customization of resource files.
It will be simple to give a demo, but first what I am doing: We have an app that is a product, but we allow clients to customize that product.
What I want (I think) is to create out product with a message "Welcome" (English) and "Welkom" (Afrikaans). The product needs to support different languages.
But, the client is allowed to change "Welcome" to "Hey Again" in the English resources.
However we release an update (say v2) and we add a new key "Bye" to the resources.
What is the best practice to prevent overriding the client's customizations, but update the default resources so that it is now at the latest version with both keys?
In pseudo-code:
Load default resources (English) - this is done by .NET
Load default regional resources (Afrikaans) - this is done by .NET
Load the client resources (English) - ?
Load the client regional resources (Afrikaans) - ?

Thus, the final request for "Bye" in any language returns "Bye" (new), but the final request for "Welcome" in English returns "Hey Again" (client) and "Welkom" (default) in Afrikaans.

A: As T.S. mentioned above, I would also recommend a database resource provider.
http://msdn.microsoft.com/en-us/library/aa905797.aspx
Depending on your application, you can use the standard MS SQL Resource provider or customize it in case it's an app where MS SQL makes no sense.


text:
Q: glTexImage2D much slower on Android 4.2.2 than 4.2.0 We recently upgraded our Android devices from 4.2.0 to 4.2.2 only to realize that everything is now stuttering madly.
On Android 4.2.0 or lower, this call required roughly 15 ms.
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, buffer.position(position));

On Android 4.2.2, the same call requires between 100 - 195 ms. What on earth has changed that would cause this? We are multiple developers testing across multiple devices and are all getting this. I can't see anything in the change logs that would affect this. I have no idea how to move forwards from here.
As a note, the buffer in the above call is a ByteBuffer returned from MediaCodec.

A: this is a bug according to the bug database
https://code.google.com/p/android/issues/detail?id=53135&q=nexus%2010&sort=-id&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars


text:
Q: Are Postscript expressions allowed in pscircle's radius? I am using PSTricks and I'm trying to draw a circle whose radius is computed as a Postscript expression. This is a simplified, minimal example:
\documentclass{article}
\usepackage{pst-plot, auto-pst-pdf}
\begin{document}
\begin{pspicture}
\def\side{2}
\def\radius{\side\space .5 sub}
\pscircle(! 2 1){\radius}
\pscircle(! 2 1){1.5}
\end{pspicture}
\end{document}

While the "pscircle" with radius literally 1.5 is drawn correctly, the one with the predefined radius "\radius" (which should simply be equal to 2 - .5) generates a small circle and the character string ".5 sub".
What am I doing wrong? Is the radius in braces parsed differently from other graphic parameters, and so it doesn't accept my Postscript expression?

A: You are already using Postscript code in the centre coordinates of the circles, indicated by a ! at the beginning. The same needs to be done with the radius as well:
\pscircle(! 2 1){!\radius}

Besides, pkg auto-pst-pdf is not needed anymore, since it is possible to directly typeset to PDF with lualatex, thanks to Marcel Krueger's Postscript interpreter written in Lua:
\documentclass{article}
\usepackage{pst-plot}
\begin{document}
\begin{pspicture}
\def\side{2}
\def\radius{\side\space .5 sub}
\pscircle(! 2 1){!\radius}
\pscircle(! 2 1){1.5}
\end{pspicture}
\end{document}


text:
Q: Python flask returns 405 error when using twitter api I am using python and I apologize as this is probably a very simple concept that I am not grasping but I am not very familiar with the flask framework. Right now I'm making a server with flask but run into a 405 error every time I try to do something with the twitter api shortly after. Right now my code looks something like this
In a separate file:

from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/', methods=['GET', 'POST', 'DELETE'])
def home():
    return "Hello world!"

def run():
  app.run(host='0.0.0.0',port=8080)
  app.run(debug=True, host="0.0.0.0")

def keep_alive():
    t = Thread(target=run)
    t.start()

Then I call my code in the main file:

from flaskfile import flask_file
flask_file()

MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json'
POST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/update.json'

CONSUMER_KEY = consumerkey
CONSUMER_SECRET = secret
ACCESS_TOKEN = accesstoken
ACCESS_TOKEN_SECRET = tokensecret

#fileName = check_and_download()
VIDEO_FILENAME = (filename)

oauth = OAuth1(CONSUMER_KEY,
  client_secret=CONSUMER_SECRET,
  resource_owner_key=ACCESS_TOKEN,
  resource_owner_secret=ACCESS_TOKEN_SECRET)

class VideoTweet(object):

  def __init__(self, file_name):
    '''
    Defines video tweet properties
    '''
    self.video_filename = file_name
    self.total_bytes = os.path.getsize(self.video_filename)
    self.media_id = None
    self.processing_info = None

  def upload_init(self):
    '''
    Initializes Upload
    '''
    print('INIT')

    request_data = {
      'command': 'INIT',
      'media_type': 'video/mp4',
      'total_bytes': self.total_bytes,
      'media_category': 'tweet_video'
    }

    req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, auth=oauth)
    media_id = req.json()['media_id']

    self.media_id = media_id

    print('Media ID: %s' % str(media_id))

  def upload_append(self):
    '''
    Uploads media in chunks and appends to chunks uploaded
    '''
    segment_id = 0
    bytes_sent = 0
    file = open(self.video_filename, 'rb')

    while bytes_sent < self.total_bytes:
      chunk = file.read(4*1024*1024)

      print('APPEND')

      request_data = {
        'command': 'APPEND',
        'media_id': self.media_id,
        'segment_index': segment_id
      }

      files = {
        'media':chunk
      }

      req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, files=files, auth=oauth)

      if req.status_code < 200 or req.status_code > 299:
        print(req.status_code)
        print(req.text)
        sys.exit(0)

      segment_id = segment_id + 1
      bytes_sent = file.tell()

      print('%s of %s bytes uploaded' % (str(bytes_sent), str(self.total_bytes)))

    print('Upload chunks complete.')

  def upload_finalize(self):
    '''
    Finalizes uploads and starts video processing
    '''
    print('FINALIZE')

    request_data = {
      'command': 'FINALIZE',
      'media_id': self.media_id
    }

    req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, auth=oauth)
    print(req.json())

    self.processing_info = req.json().get('processing_info', None)
    self.check_status()

  def check_status(self):
    '''
    Checks video processing status
    '''
    if self.processing_info is None:
      return

    state = self.processing_info['state']

    print('Media processing status is %s ' % state)

    if state == u'succeeded':
      return

    if state == u'failed':
      sys.exit(0)

    check_after_secs = self.processing_info['check_after_secs']

    print('Checking after %s seconds' % str(check_after_secs))
    time.sleep(check_after_secs)

    print('STATUS')

    request_params = {
      'command': 'STATUS',
      'media_id': self.media_id
    }

    req = requests.get(url=MEDIA_ENDPOINT_URL, params=request_params, auth=oauth)

    self.processing_info = req.json().get('processing_info', None)
    self.check_status()

  def tweet(self):
    '''
    Publishes Tweet with attached video
    '''
    request_data = {
        #leave status blank
      'status': '',
      'media_ids': self.media_id
    }

    req = requests.post(url=POST_TWEET_URL, data=request_data, auth=oauth)
    print(req.json())

if __name__ == '__main__':
  videoTweet = VideoTweet(VIDEO_FILENAME)
  videoTweet.upload_init()
  videoTweet.upload_append()
  videoTweet.upload_finalize()
  videoTweet.tweet()

The error returned states the following:
"Error response
Error code: 405
Message: Method Not Allowed.
Error code explanation: 405 - Specified method is invalid for this resource."
Basically I call the flask file then use twitter api to upload a file, but for some reason using the twitter api always results in a 405 error and my flask server is no longer accessible. How can I adjust my flask file to allow me to upload using the api?

A: 405 errors are thrown when the wrong request method is used. For example a POST request being sent when a GET request was expected, or a GET request being sent when a POST request was expected.
In your check_status function you have
req = requests.get(url=MEDIA_ENDPOINT_URL, ...

But according to Twitter's documentation you should be using a post request here
req = requests.post(url=MEDIA_ENDPOINT_URL, ...


text:
Q: How do I force the XSL to write this out with a closing tag? I have this XSL snippet:
     <xsl:if test="@BookmarkId">

          <xsl:attribute name="name">
            <xsl:value-of select="concat('week', @BookmarkId)"/>
          </xsl:attribute>

      </xsl:if>

The output is:

But in this instance I require it to be:

How can I do this?
Thank you.

A: Please use this solution
 <xsl:if test="@BookmarkId">

      <xsl:attribute name="name">
        <xsl:value-of select="concat('week', @BookmarkId)"/>
      </xsl:attribute>
      <![CDATA[ ]]>

  </xsl:if>


text:
Q: how to flip div's css in run time I have two div's using bootstrap

 this div use the left side of the page

this div use the right side of the page

it works correctly when I use English language, but my web site use many language as Arabic also, So I need to flip the two div's in run time.
I try to set it an offset class but it useless!
How can I do that ?

A: you can use
   col-md-6 {direction : 'rtl'; }
as for run time you can set it using jquery depend on what you mean by runtime

A: You can use Javascript to set
direction: rtl;  /* Right to Left */

or
direction: ltr;  /* Left to Right */
based on the language is is being displayed in
To get lang of page
var x =  navigator.language; /* Language of the browser */

execute on page load

A: try this one:
#LiveNewsItemTitle0
{
/*  position: absolute;
    left: 270px;
    top : 58px;
    background-size:cover;
    width : 275px;
    height : 105px;*/
    font-size: 11pt;

    z-index: 1;
    direction:rtl;

}

معلومات الـ"mtv": سلام سيحمل التشكيلة الحكومية إلى

use this link for preview: http://fiddle.jshell.net/FKLvy/2/


text:
Q: Rails i18n and yml structure for form labels According to the ActionView documentation. Quote:

The text of label will default to the attribute name unless a translation is found in the current I18n locale (through views.labels.<modelname>.<attribute>) or you specify it explicitly.

I have a "user" model and a registration form. Here's a snippet of the relevant part:
<% form_for(@user) do |f| %>
    ...
    <p>
    <%= f.label :username %>
    <%= f.text_field :username, :class => 'full_width' %>
    </p>
    ...
<% end %>

Dots hide unimportant code.
As I understand the documentation, if I provide a translation in my locale file, in this case :dk, my dk.yml looking like so:
dk:
    views:
        labels:
            user:
                username:
                    "blahblah"

Rails should translate the label text and insert "blahblah" instead of "Username".
This is not happening, so I must have missed something. Any help appreciated.

A: In Rails 3.1 that is a little bit changed.
<% form_for @post do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>
  <%= f.submit %>
<% end %>

en:
  helpers:
    label:
      post:
        title: 'Customized title'

A: I think I found another solution here.
My app was version 2.3.5. I've now changed it to 2.3.8 and <%= f.label :username %> now uses the translation in:
dk:
  activerecord:
    attributes:
      user:
        username:

I found the hint in this ticket:
https://rails.lighthouseapp.com/projects/8994/tickets/745-form-label-should-use-i18n

A: That's because the label method you are calling is not the one from ActionView::Helpers::FormHelper but is in fact the label_tag method from ActionView::Helpers::FormTagHelper. The form_for method is rewriting the code in the given block by adding _tag to the used form helpers. So you're not looking at the documentation for the right method!
I've not yet used that method, as sometimes the label for a field can be different from multiple forms using the same model, so I've written my own helper.


text:
Q: Why "bgcolor" for "pre" not shown? I make HTML report - cannot see yellow BG color for report. Why.
Html has code like

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

1

You see here yellow bg for "1".
I use Firefox.

A: You are using very outdated HTML notations. The correct markup would be:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    Black text with yellow background


text:
Q: Question about $\operatorname{Aut}(S_6)$ and $\operatorname{Aut}(A_6)$ From (1), (2), (3), $[\operatorname{Aut}(S_6):\operatorname{Inn}(S_6)]=2$.
My question:
$1$. How to prove $\operatorname{Aut}(S_6)\cong S_6\rtimes_\varphi \mathbb Z_2$?
$2$. How to prove $\operatorname{Aut}(S_6)\not\cong S_6\times \mathbb Z_2$?
$3$. How to prove $\operatorname{Aut}(A_6)\cong \operatorname{Aut}(S_6)$?

My effort:
$1$. For 1, it remains to show there exists $\sigma\in \operatorname{Aut}(S_6)\setminus \operatorname{Inn}(S_6)$ s.t. $\sigma^2=\text{id}$.
$2$. For 2, $Z(S_6\times\mathbb Z_2)=\mathbb Z_2$, it's sufficient to show $Z(\operatorname{Aut}(S_6))\neq\mathbb Z_2$.
$3$. For 3, I proved $\operatorname{Aut}(S_n)\leqslant\operatorname{Aut}(A_n)$ (Is this correct?) and $[\operatorname{Aut}(A_6):\operatorname{Inn}(S_6)]\leqslant 2$.
Update:
I wrote my answer below, but there still remain three questions:
$1$. I copied the result from a book to give an explicit element $\psi\in\operatorname{Aut}(S_6)\setminus \operatorname{Inn}(S_6)$ of order $2$, and I wonder if there's a way to avoid doing so, i.e. find an element of order $2$ in $\operatorname{Aut}(S_6)\setminus \operatorname{Inn}(S_6)$ without writing it out explicitly.
$2$. I used the specific element $\psi$ to show $\mathbb Z_2\cong \langle \psi\rangle$ is not normal in $\operatorname{Aut}(S_6)$, I wonder if we can analysis the center of $\operatorname{Aut}(S_6)$ instead. And what is center of $\operatorname{Aut}(S_6)$?
$3$. Is there a better way to prove $\operatorname{Aut}(A_6)\cong \operatorname{Aut}(S_6)$?
Thanks for your time and effort!

A: For 1,  there exists $\psi\in \operatorname{Aut}(S_6)\setminus \operatorname{Inn}(S_6)$ s.t. $\psi^2=\text{id}$.
$\quad\psi:(12)\mapsto(15)(23)(46), (13)\mapsto(14)(26)(35), (14)\mapsto(13)(24)(56),\\\qquad (15)\mapsto(12)(36)(45), (16)\mapsto(16)(25)(34).$
Therefore $\operatorname{Aut}(S_6)\cong S_6\rtimes\mathbb Z_2$.

For 2, we have short exact sequence for groups: $1\to S_6\overset{f}{\to}\operatorname{Aut}(S_6)\overset{\pi}{\to} \mathbb Z_2\to 1 $, $\mathbb Z_2=\{\pm1,\times\}$.
This sequence right splits, so there exists homomorphism $g:\mathbb Z_2 \to \operatorname{Aut}(S_6)$ s.t. $\pi\circ g=\text{id}.$
Let $g(-1)=\psi\not\in \operatorname{Inn}(S_6)$, then $g(1)=\psi^2=\text{id}$.
$f:S_6\to \operatorname{Inn}(S_6)$, $g:\mathbb Z_2 \to \langle\psi\rangle$.
Claim: $\langle\psi\rangle$ is not normal subgroup of $\operatorname{Aut}(S_6)$, so $\operatorname{Aut}(S_6)\not \cong S_6\times\mathbb Z_2$.
For $\sigma\in S_6$, define $\gamma_\sigma \in \operatorname{Inn}(S_6)$ to be action by conjugation of $\sigma$.
It's sufficient to prove $\gamma_\sigma\psi\gamma_\sigma^{-1}\neq\psi$, i.e.$\gamma_\sigma\psi\neq\psi\gamma_\sigma$ for some $\sigma\in S_6$.
Let $\sigma=(12)$, $\gamma_\sigma\psi((12))=\gamma_\sigma((15)(23)(46))=(12)(15)(23)(46)(12)=(13)(25)(46)$.
$\psi\gamma_\sigma(12)=\psi((12))=(15)(23)(46)$. $\gamma_\sigma\psi\neq\psi\gamma_\sigma$ for $\sigma=(12)$.
Thus $\operatorname{Aut}(S_6)\cong S_6\rtimes\mathbb Z_2$ and $\operatorname{Aut}(S_6)\not \cong S_6\times\mathbb Z_2$.

For 3, fix $1\neq\alpha\in A_n$, $c_\alpha\in\text{Inn}(A_n)$ is action by conjugation of $\alpha$.
Define $\varphi:\text{Aut}(S_n)\to\text{Aut}(A_n)$, $\varphi(\beta)=\beta c_\alpha \beta^{-1}$ for $\beta\in \text{Aut}(S_n)$.
Easy to check $\varphi$ is monomorphism, so $\text{Aut}(S_n)\leqslant\text{Aut}(A_n)$
Together with $[\text{Aut}(A_6):\text{Inn}(S_n)]\leqslant2$ and $[\text{Aut}(S_6):\text{Inn}(S_n)]=2$, we have
$\text{Aut}(A_6)=\text{Aut}(S_6)$.


text:
Q: Python 3 clear list/restart if total > a set number but it keeps going Warning: I am new to Python.  This code WILL be primitive.
I am appending random numbers into a list until I get to "4".
When adding elements of list...
1. If I get 10, break while loop and print list.
2. If I get <10, resume.
3. If I get > 10, clear list and resume.
So far, the first 2 work. But when it is >4, it just keeps going.
I tried this just using variables and not a list but I had problems with global vs local values.
import random
import time

totalNums = []
count = 1
while count > 0:
    rndNum = random.randint(3, 5)
    totalNums.append(rndNum)
    overLoadCheck = sum(list(totalNums))
    print ("Operation #:", count, "Current Num:", rndNum, "Total Nums:", overLoadCheck)
    time.sleep(1)
    if overLoadCheck > 10:
        totalNums.clear
    elif overLoadCheck == 10:
        break
    count = count + 1

print (totalNums)


text:
Q: java.lang.IllegalStateException: EntityManager is closed with HSQL I am building a simple spring web application for educational purposes and I have a little problem with the persistence level- java.lang.IllegalStateException: EntityManager is closed is thrown when I try to get something from the database. The objects are persisted, but when I get try to make a query that exception is thrown. So I am using Hibernate with HSQL inmemory db and here is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
         version="2.0">

<persistence-unit name="pp_persistence_unit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>

    <properties>
        <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:testDB"/>
        <property name="sqltool.charset" value="UTF-8" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
        <property name="show_sql" value="true"/>
        <property name="hibernate.hbm2ddl.auto" value="create"/>
        <property name="current_session_context_class" value="thread"/>
        <property name="hibernate.show_sql" value="true" />
    </properties>
</persistence-unit>

The stacktrace from the error is the following:
 SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/web-app] threw exception [Request processing failed; nested exception is
java.lang.IllegalStateException: EntityManager is closed] with root cause
java.lang.IllegalStateException: EntityManager is closed
at org.hibernate.jpa.internal.EntityManagerImpl.checkOpen(EntityManagerImpl.java:105)
at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:491)
at web.task.dao.ConnectionDao.getConnectionsCount(ConnectionDao.java:67)
at web.task.transformation.ConnectionTransformator.getPagesCount(ConnectionTransformator.java:48)
at web.task.business.ConnectionService.getPagesCount(ConnectionService.java:45)
at web.task.controllers.ConnectionController.getAllConnections(ConnectionController.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

Here it ii the getConnectionsCount() method
public int getConnectionsCount() {
    Query query = entityManager.createQuery("select count(c.id) from Connection c");
    return (Integer)query.getSingleResult();
}

I really don't know what is the problem. I had an assumption that it could be from the encoding of the database, but I tried to set it to UTF-8, but the error was still the same.
Sorry for forgetting, here is my application-context.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<context:component-scan base-package="web.task.business">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>

<context:component-scan base-package="web.task.dao">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
</context:component-scan>

<context:component-scan base-package="web.task.transformation">
    <context:include-filter type="annotation" expression="web.task.annotations.Transformation" />
</context:component-scan>

<bean id="ppEntityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="pp_persistence_unit" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="ppEntityManagerFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />


text:
Q: Javascript framework: Knockout, backbone, ember… I'm currently on a web application project written in javascript with node.js and Express server-side and it's time to consider the client-side of this application. The two questions are:

*

*Should I consider using a framework or can I write it without such a tool?

*And if not, which framework?

I've chosen three of these: backbone, knockout and Ember. I read all the questions I found about them but I'm still hesitating. The points to consider are:

*

*It is good to mix html with javascript like knockout does?

*Will my application be easily maintainable?

*Will the framework continue and not diappear tomorrow, leaving me in a very uncomfortable situation?

EDIT: And what do you think about JavaScriptMVC?

A: As @Christian Varga has said in the comments, it depends. However, I would make the following observations:

It is good to mix html with javascript like knockout does?

With knockout you are not forced to mix javascript into the html. See Unobstrusive Event Handling.

Will my application be easily maintainable?

In my experience with knockout , if the application gets especially large the pages do get complicated. However, if you are going for a SPA style page then the code will always get fairly involved. I haven't worked with Ember or Backbone but certainly Backbone does have a reputation for being be good for larger applications.

Will the framework continue and not diappear tomorrow, leaving me in a
  very uncomfortable situation?

I think you have picked your three frameworks to consider wisely. Knockout and Backbone both have fairly wide adoption. Knockout is to be shipped with MVC4 which gives you some confidence behind its future. Ember is newer but there seems to be a lot of excitement behind it. There is a good discussion of Ember with various references to knockout and backbone here
Hope this helps you evaluate what will be best for your project.

A: All those are good frameworks. You can choose anyone and you won't make a huge mistake. Of course, you might like one most than others, but that's a matter of taste. All those frameworks will make your app easy mantainable.
Now, I want to add something more. You asked "Should I consider using a framework"? You can build your own stuff, that's something cool. I'd just recomend to keep in mind good organization of your project. In my short experience, Js is a mess. And these FWs help you to keep your code clean and organized.
1 more thing to add to organization: You should consider some AMD tool, like Require.js

A: If you're thinking of building an application with scalability and maintainability in mind you might want to consider a reference architecture such as Boilerplatejs.
BoilerplateJS incorporates best practices to be used when building a large scale application. Furthermore it ships with libraries such as knockoutjs and also utilities that would help structure and organize your code.


text:
Q: JSFL: convert text from a textfield to a HTML-format string I've got a deceptively  simple question: how can I get the text from a text field AND include the formatting? Going through the usual docs I found out it is possible to get the text only. It is also possible to get the text formatting, but this only works if the entire text field uses only one kind of formatting. I need the precise formatting so that I convert it to a string with html-tags.
Personally I need this so I can pass it to a custom-made text field component that uses HTML for formatting. But it could also be used to simply export the contents of any text field to any other format. This could be of interest to others out there, too.
Looking for a solution elsewhere I found this:
http://labs.thesedays.com/blog/2010/03/18/jsfl-rich-text/
Which seems to do the reverse of what I need, convert HTML to Flash Text. My own attempts to reverse this have not been successful thus far. Maybe someone else sees an easy way to reverse this that I'm missing?  There might also be other solutions. One might be to get the EXACT data of the text field, which should include formatting tags of some kind(XML, when looking into the contents of the stored FLA file). Then remove/convert those tags. But I have no idea how to do this, if at all possible. Another option is to cycle through every character using start- and endIndex, and storing each formatting kind in an array. Then I could apply the formatting to each character. But this will result in excess tags. Especially for hyperlinks! So can anybody help me with this?

A: A bit late to the party but the following function takes a JSFL static text element as input and returns a HTML string (using the Flash-friendly  tag) based on the styles found it its TextRuns array. It's doing a bit of basic regex to clear up some tags and double spaces etc. and convert /r and /n to
 tags. It's probably not perfect but hopefully you can see what's going on easy enough to change or fix it.
function tfToHTML(p_tf)
{
    var textRuns = p_tf.textRuns;
    var html = "";

    for ( var i=0; i<textRuns.length; i++ )
    {
        var textRun = textRuns[i];
        var chars = textRun.characters;

        chars = chars.replace(/\n/g,"
");
        chars = chars.replace(/\r/g,"
");
        chars = chars.replace(/  /g," ");
        chars = chars.replace(/.
/g,".
");

        var attrs = textRun.textAttrs;

        var font = attrs.face;
        var size = attrs.size;
        var bold = attrs.bold;
        var italic = attrs.italic;
        var colour = attrs.fillColor;

        if ( bold )
        {
            chars = ""+chars+"";
        }

        if ( italic )
        {
            chars = ""+chars+"";
        }

        chars = ""+chars+"";

        html += chars;
    }

    return html;
}


text:
Q: How to prevent odd scrollbar flash? I don't think what I am doing is all that unusual, but I'm certainly getting an unusual result.
I have a normal UITableView, and when one of the cells is touched, I push a viewController onto the navigationController stack. Nothing I have not done 100 times before.
This particular viewController is another UITableViewController, with one section, and one cell. This one cell contains a UITextView. It's a totally generic "Enter your notes" screen. This screen sets the UITextView to be the firstResponder in viewDidAppear.
The problem is this... as the new keyboard is sliding on to the screen, over the new viewController... I get something that looks suspiciously like a "scrollbar flash" only it's on the LEFT side of the screen. The effect is that I have a dot flash in the upper left hand corner of my screen. I can reproduce this in both the simulator and the device.
weird dot http://matthewcave.com/images/weird_dot.png
I can post code, but I was wondering if someone had seen this before, and had a quick answer as to how I could make it go away. If I were to post code, what would you want to see? Posting the whole viewController class seems like overkill, but I literally have no idea where the problem is.
Thanks a bunch.

A: I wonder if that is a table or section header that is sized very small?

A: I found a fix for this while desperately trying to find a work around. I had the idea that I would change the scrollbar color to white (at least temporarily, to make it less visible). But I found that no mater if it is set to white or black, as long as the color is forced, you won't see the dot. I wish I had a further explanation, but this is by far the simplest fix out there.
//configure tableview behavior
self.tableView.rowHeight = 178.0f;
self.tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite; //hide the scrollbar dot
self.tableView.scrollEnabled = NO;


text:
Q: Using non-instantiated values in Angular

          <input class="toggle"
            type="checkbox"
            [checked]="todo.isDone"
            (click)="toggleTodo(todo)">
          {{todo.title}}
          <button class="destroy" (click)="destroyTodo(todo)"></button>

        <input class="edit"
               #updatedTodo
               [value]="todo.title"
               (blur)="updateTodo(todo, updatedTodo.value)"
               (keyup.escape)="todo.editing = false"
               (keyup.enter)="updateTodo(todo, updatedTodo.value)">

https://github.com/amejiarosario/angular-todo-app/blob/master/src/app/todo/todo.component.html
I modified the code from this repository and one thing I noticed is that the editing property is not found in the original todos array objects, and is being created inside the html component or maybe elsewhere, I am thinking it's being instantiated in the event listeners, but is it a good idea to do that? I had trouble with it, so I had to instantiate it inside the todos.
Also, instantiating it here in the event listeners means we can't modify the property editing inside the service component, right?

A: It is set in the event listeners, yes.
Here:

And here:
(keyup.escape)="todo.editing = false"

Of course, if it is not initialized anywhere else, then it will be initialized here. But regardless, it's a terrible idea to mutate objects in such a way from Angular point of view. It would not work with OnPush change detection strategy for example. Principle of immutability is important for Angular because if you manage change detection correctly, it will only do checks by references and mutated changes won't necessarily show up. What those events should really do is trigger functions that update that specific object by reconstructing it and then replace it in the array by reconstructing the array as well. E.g.
setIsEditing(todoToUpdate: Todo, editing: boolean): void {
  this.todos = this.todos.map(todo => todo === todoToUpdate ? {...todoToUpdate, editing} : todo);
}

Of course in this way changes to todos will destroy and recreate todo DOM elements by *ngFor (which is intended). But you can also improve that by using a trackBy function. Something like
component.ts
trackById(index, todo: Todo): string {
  return todo.id;
}

component.html

You don't always have to do this, but I just wanted to show you an example. The reason you would do this is to achieve great performance in real world app. But your app seems more like a learning app, thus does things in the simplest way possible, I think that's also why properties are added in the event handlers.

A: HTML attributes only consist of text, not parentheses ((/)), brackets ([/]), or curlies ({/}). I think that's why your code was not working, it isn't an Angular problem.


text:
Q: jquery datetimepicker gives 404 not found (.png files) error I'am using this datetimepicker on my website. My html file includes .js and .css files ;
<link rel="stylesheet" type="text/css" href="asts/css/style.css">
<script type="text/javascript" src="asts/js/modernizr.2.0.6.js"></script>
<script type="text/javascript" src="asts/js/jquery_1.7.1.js" ></script>
<script type="text/javascript" src="asts/js/jquery-ui-1.8.17.custom.min.js" ></script>
<script type="text/javascript" src="asts/js/jquery-ui-timepicker-addon.js" ></script>
<script type="text/javascript" src="asts/js/jquery.ui.slider.js" ></script>
<script type="text/javascript" src="asts/js/gonnasphere.js" ></script>

Also, I've imported the css files of custom minified package and datetime-picker-addon by @import url statement. I've also included the css/images folder with necessary icons.
When I click the text field, the jquery ui plugin works correctly. All the functions and ui works. However, firebug gives me the following network errors ;

*

*NetworkError: 404 Not Found - http://subdomain.domain.com/asts/css/images/ui-bg_highlight-soft_100_eeeeee_1x100.png

*NetworkError: 404 Not Found - http://subdomain.domain.com/asts/css/images/ui-bg_gloss-wave_35_f6a828_500x100.png

*NetworkError: 404 Not Found - http://subdomain.domain.com/asts/css/images/ui-bg_glass_100_f6f6f6_1x400.png

*NetworkError: 404 Not Found - http://subdomain.domain.com/asts/css/images/ui-bg_highlight-soft_75_ffe45c_1x100.png
Can you please help me to prevent getting this error ?

A: Those are jQueryUI assets, probably used by jquery.ui.slider.js.
Download the slider (+ its dependencies) from http://jqueryui.com/download and you will find the required CSS & images in \css\<selected-theme>

A: I've figured out the problem. It was a folder fault. When I changed the file paths of .png files in the  jquery-ui-1.8.17.custom.css file, it doesn't show any error.
Before I changed, it was ;
url(images/ui-bg_inset-soft_50_c9c9c9_1x100.png)

After ;
url(../images/ui-bg_inset-soft_50_c9c9c9_1x100.png)

A: I had the same problem, I need to download the the JQueryUI assets and put the images folder in the stylesheets folder. I was using the .min files and had to switch for the non min one.
It fixed my problem.


text:
Q: Nested DIV's and z-index I'm trying to create this type of an overlapping by using z-index on divs:

However, if I set the z-index of the parent to a smaller number than z-index of the "non-child" element, the child stays at the back with it's parent too.
I'm wondering if there is any way to overcome this issue..

A: Are you trying to do something like this ?
http://codepen.io/mudittuli/full/rEgkw

A: It's hard to tell without seeing your code, but I believe you are using some of the DIVs as ancestors; try to use all of them separately. That example does what you want:
<!DOCTYPE html>

        <title>Positioning test</title>

Parent

Not-child

Child


text:
Q: match and group sets of similar strings in a loop I am trying to match and group similar strings from a list but I'm not sure how to approach this.
I have the following list:
tablenames =[
            'SCS_q104',
            'SCS_q102[{SCS_q102$_$_$SCS_q102_1}].SCS_q102_grid',
            'SCS_q102[{SCS_q102$_$_$SCS_q102_2}].SCS_q102_grid',
            'SCS_q102[{SCS_q102$_$_$SCS_q102_3}].SCS_q102_grid',
            'SCS_q102[{SCS_q102$_$_$SCS_q102_4}].SCS_q102_grid',
            'SCS_q105',
            'SCS_q106',
            'SCS_q107[{SCS_q107$_$_$SCS_q107_1}].SCS_q107_grid',
            'SCS_q107[{SCS_q107$_$_$SCS_q107_2}].SCS_q107_grid',
            'SCS_q107[{SCS_q107$_$_$SCS_q107_3}].SCS_q107_grid',
            'SCS_q108',
            'SCS_q109',
            ]

Expected outcome:
groupofgrids = [[
        'SCS_q102[{SCS_q102$_$_$SCS_q102_1}].SCS_q102_grid',
        'SCS_q102[{SCS_q102$_$_$SCS_q102_2}].SCS_q102_grid',
        'SCS_q102[{SCS_q102$_$_$SCS_q102_3}].SCS_q102_grid',
        'SCS_q102[{SCS_q102$_$_$SCS_q102_4}].SCS_q102_grid',
        ][
        'SCS_q107[{SCS_q107$_$_$SCS_q107_1}].SCS_q107_grid',
        'SCS_q107[{SCS_q107$_$_$SCS_q107_2}].SCS_q107_grid',
        'SCS_q107[{SCS_q107$_$_$SCS_q107_3}].SCS_q107_grid',
        ]]

From the expected outcome above you can see how I would like to group the strings.
if everything before and after the brackets are the same as the string before then they belong to the single group.
There are two groups in this example.
The expected outcome has to simply group the matching set of strings, doesn't really matter if its stored as a list of lists or dict of some kind.
My attempt so far:
groupofgrids = []
for item in tablenames:
    if "." in item:
        suffix = item.split(".")[-1]
        if suffix in item:
            groupofgrids.append(item)

print groupofgrids

This method doesn't really group the set of similar strings as I wanted simply because I not sure how to.
Any advice?

A: Since the similarity is based on the string other than the contents between the brackets [...], extract those sub-strings, join them using a separator(here I've used "-") and use that as a key to the dictionary
Try this -
import re
regex = re.compile(r'(.*?)\[.*?\]\.(.*)')
groupofgrids = {}
for item in tablenames:
    matches = regex.findall(item)
    if (len(matches) > 0 and len(matches[0]) == 2):
        key = "-".join(matches[0])
        if key in groupofgrids:
            groupofgrids[key].append(item)
        else:
            groupofgrids[key] = [item]
import json
print json.dumps(groupofgrids,sort_keys=True, indent=4)
#OUTPUT
'''
{
    "SCS_q102-SCS_q102_grid": [
        "SCS_q102[{SCS_q102$_$_$SCS_q102_1}].SCS_q102_grid",
        "SCS_q102[{SCS_q102$_$_$SCS_q102_2}].SCS_q102_grid",
        "SCS_q102[{SCS_q102$_$_$SCS_q102_3}].SCS_q102_grid",
        "SCS_q102[{SCS_q102$_$_$SCS_q102_4}].SCS_q102_grid"
    ],
    "SCS_q107-SCS_q107_grid": [
        "SCS_q107[{SCS_q107$_$_$SCS_q107_1}].SCS_q107_grid",
        "SCS_q107[{SCS_q107$_$_$SCS_q107_2}].SCS_q107_grid",
        "SCS_q107[{SCS_q107$_$_$SCS_q107_3}].SCS_q107_grid"
    ]
}
'''

If you want a nested list, then do this -
li = groupofgrids.values()
print json.dumps(li,sort_keys=True, indent=4)
#OUPTUT
'''
[
    [
        "SCS_q107[{SCS_q107$_$_$SCS_q107_1}].SCS_q107_grid",
        "SCS_q107[{SCS_q107$_$_$SCS_q107_2}].SCS_q107_grid",
        "SCS_q107[{SCS_q107$_$_$SCS_q107_3}].SCS_q107_grid"
    ],
    [
        "SCS_q102[{SCS_q102$_$_$SCS_q102_1}].SCS_q102_grid",
        "SCS_q102[{SCS_q102$_$_$SCS_q102_2}].SCS_q102_grid",
        "SCS_q102[{SCS_q102$_$_$SCS_q102_3}].SCS_q102_grid",
        "SCS_q102[{SCS_q102$_$_$SCS_q102_4}].SCS_q102_grid"
    ]
]
'''

A: Is this works for you:
group = dict()

for elm in tablenames:
    try:
        f,s = elm.split('.')
    except:
        pass
    else:
        group.setdefault(s,[])
        group[s].append(elm)

import pprint
pprint.pprint(group.values())

Output:
[['SCS_q107[{SCS_q107$_$_$SCS_q107_1}].SCS_q107_grid',
  'SCS_q107[{SCS_q107$_$_$SCS_q107_2}].SCS_q107_grid',
  'SCS_q107[{SCS_q107$_$_$SCS_q107_3}].SCS_q107_grid'],
 ['SCS_q102[{SCS_q102$_$_$SCS_q102_1}].SCS_q102_grid',
  'SCS_q102[{SCS_q102$_$_$SCS_q102_2}].SCS_q102_grid',
  'SCS_q102[{SCS_q102$_$_$SCS_q102_3}].SCS_q102_grid',
  'SCS_q102[{SCS_q102$_$_$SCS_q102_4}].SCS_q102_grid']]


text:
Q: Ubuntu 14.04 super slow after install I have a Compaq with Intel Atom CPU D410 @ 1.66 Ghz x2, RAM is 2 Gb and Intel IGDx86/MMX/SSE2.
When I boot Ubuntu from the live CD it worked like a charm even in my old computer, so I decided to install it as a dual boot with Windows 7. After the installation it was terribly slow. I have already try re-installing it but nothing changed.
Is it that my computer is just too old to run Ubuntu? If so, then why did it work perfectly fine from the liveCD? Thanks for your help.
The result of the command sudo fdisk -l is this
Disk /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders, total 976773168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xc4478cd1

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      206847      102400    7  HPFS/NTFS/exFAT
/dev/sda2          206848   840583167   420188160    7  HPFS/NTFS/exFAT
/dev/sda3       953223168   976771071    11773952    7  HPFS/NTFS/exFAT
/dev/sda4       840583168   953223167    56320000    5  Extended
/dev/sda5       840585216   861065215    10240000   83  Linux
/dev/sda6       861067264   871307263     5120000   82  Linux swap / Solaris
/dev/sda7       871309312   932749311    30720000   83  Linux

Partition table entries are not in disk order

A: I would check my hard disc. It probably does not have to do with your processor (because LiveCD worked perfectly).


text:
Q: Script to delete files under each userprofile I am looking for a script to run to remove files from each userprofile + path ex: userprofile\Appdata\Microsoft\Windows\WER\ReportQueue*
I tried
Remove-Item "C:\users + \AppData\Local\Microsoft\Windows\WER\ReportQueue\AppCrash*"

No go.
Also tried VBScript:
Set fso = CreateObject("Scripting.FileSystemObject")

strOneDrivePath = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%USERPROFILE%") & "\AppData\Local\Microsoft\Windows\WER\ReportQueue\"
Search strOneDrivePath

Sub Search(str)
    Set folder = fso.GetFolder(str)
    For Each file In folder.Files
        If file.DateLastModified < (Now() - 3) Then
            file.Delete True
        End If
    Next

    For Each subFolder In folder.SubFolders
        Search subFolder.Path
        If subFolder.Files.Count = 0  Then
            subFolder.Delete True
        End If
    Next
End Sub

A: $paths = Get-ChildItem -Directory c:\users | Select-Object $_.Name

ForEach ($path in $paths){
    If (test-path "c:\users\$path\AppData\Local\Microsoft\Windows\WER\ReportQueue\AppCrash")
    {
        Remove-Item -Path "c:\users\$path\AppData\Local\Microsoft\Windows\WER\ReportQueue\AppCrash\*" -Force

    }
}

A: You can use Get-ChildItem with the -Directory param to get the sub-directories within C:\Users, then join their paths ($_.FullName) with the child path you want.
Then use Test-Path and Remove-Item to delete the files you wish.
$path = "C:\Users"
$child_path = "AppData\Local\Microsoft\Windows\WER\ReportQueue"
$files_filter = "AppCrash*"

Get-ChildItem $path -Directory -Exclude Default*,Public | foreach {

    $joined_path = Join-Path -Path $_.FullName -ChildPath $child_path
    If (test-path $joined_path) {
        Remove-Item "$joined_path\$files_filter" -Force
    }
}


text:
Q: How to search in Quickblox Arrays I am using http://quickblox.com/developers/SimpleSample-customObjects-android#Search_operators to find keywords in "Array" data type.
But it searches by first string in array only. How to search among all strings in array?
public static void getNews(final Context context, final Handler handler, final int page) {
    ArrayList<String> catSearch = new ArrayList<>();
    ArrayList<NewsCategory> categories = Cache.getNewsCategories(context);
    for(NewsCategory category : categories) {
        if(Cache.isCategoryChecked(context, category.getId())) {
            catSearch.add(category.getId());
        }
    }

    ArrayList<String> tagSearch = new ArrayList<>();
    ArrayList<NewsTag> tags = Cache.getNewsTags(context, Cache.SELECTED_TAGS);
    for(NewsTag tag : tags) {
        tagSearch.add(tag.getTitle());
    }

    QBRequestGetBuilder builder = new QBRequestGetBuilder();
    if(tagSearch.size() == 0) {
        builder.ctn("LangId", Cache.getNewsLanguage(context)).
                in("CategoryId", catSearch.toArray());
    } else {
        builder.ctn("LangId", Cache.getNewsLanguage(context)).in("Tags", tagSearch.toArray()).
                in("CategoryId", catSearch.toArray());
    }

    QBCustomObjects.getObjects("News", builder,
            new QBEntityCallbackImpl<ArrayList<QBCustomObject>>() {
                @Override
                public void onSuccess(ArrayList<QBCustomObject> customObjects, Bundle params) {
                    ArrayList<String> images = new ArrayList<>();
                    ArrayList<News> newsArray = new ArrayList<>();
                    for (QBCustomObject object : customObjects) {
                        try {
                            HashMap<String, Object> pairs = object.getFields();
                            String id = object.getCustomObjectId();
                            long created = object.getCreatedAt().getTime();
                            News news = new News(pairs, id, created);
                            newsArray.add(news);
                            Log.e("", "Tags: " + pairs.get("Tags"));

                            if (!news.getPhoto().equals("")) {
                                images.add(news.getPhoto());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    Cache.saveNews(context, newsArray);

                    if (handler != null) {
                        handler.sendEmptyMessage(6);
                    }
                }

                @Override
                public void onError(List<String> errors) {
                    Helper.showErrorToast(context, errors);
                    if (handler != null) {
                        handler.sendEmptyMessage(1);
                    }
                }
            });
}

UPD:
We held some research and here is the results:
1. When we search for tag "Русский":
QBRequestGetBuilder builder = new QBRequestGetBuilder();
builder.in("Tags", "Русский");

https://api.quickblox.com/data/News.json?Tags[in]=%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9
RESULTS:
news id: 55b4a74f535c12b641004f3e; tags: [Русский,  советы]
news id: 55b91b78535c129a1d0039f2; tags: [Русский,  Россия]
news id: 55ba9482535c1238ce003522; tags: [Русский,  Россия]
news id: 55ba96c4535c1298ec0003fc; tags: [Русский,  советы]
news id: 55ba973f535c1298ec0004d7; tags: [Русский]
news id: 55ba9967535c12e2c00017f9; tags: [Русский,  Россия]
news id: 55ba99e3535c1298ec00099f; tags: [Русский,  Россия]
news id: 55bd592c535c12a8d6000327; tags: [Русский]
news id: 55bb32ae535c12e543006e15; tags: [Русский,  религия,  пятница,  Коран]
So, it was not searched for tag "Русский" when it is not a first tag in array. We have checked databse - we have some news with Tags ["Россия","Русский"]
2. When we search for tags "Русский", "Томск":
QBRequestGetBuilder builder = new QBRequestGetBuilder();
        builder.in("Tags", "Русский", "Томск");

https://api.quickblox.com/data/News.json?Tags[in]=%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9%2C%D0%A2%D0%BE%D0%BC%D1%81%D0%BA
3. When we search for tags "Томск", "Русский":
QBRequestGetBuilder builder = new QBRequestGetBuilder();
        builder.in("Tags", "Томск", "Русский");

https://api.quickblox.com/data/News.json?Tags[in]=%D0%A2%D0%BE%D0%BC%D1%81%D0%BA%2C%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9
RESULTS FOR 2 AND 3 THE SAME NOW:
news id: 555c46736390d8a0ca03ab61; tags: [Томск,  Алмере]
news id: 555c46b26390d8a7ce01439e; tags: [Томск,  Алмере,  Нидерланды,  Россия]
news id: 555c50bf6390d8b66300dadf; tags: [Россия, Томская область, Томск]
news id: 555d7f5c6390d8eb8504df15; tags: [Россия, Томская область, Томск,  Russia,  Moscow,  Москва]
news id: 556454536390d894de005c22; tags: [Томск,  Россия]
news id: 55a905ba535c1207e600251d; tags: [Томск,  Россия]
news id: 55b4a74f535c12b641004f3e; tags: [Русский,  советы]
news id: 55b91b78535c129a1d0039f2; tags: [Русский,  Россия]
news id: 55ba9482535c1238ce003522; tags: [Русский,  Россия]
news id: 55ba96c4535c1298ec0003fc; tags: [Русский,  советы]
news id: 55ba973f535c1298ec0004d7; tags: [Русский]
news id: 55ba9967535c12e2c00017f9; tags: [Русский,  Россия]
news id: 55ba99e3535c1298ec00099f; tags: [Русский,  Россия]
news id: 55bd592c535c12a8d6000327; tags: [Русский]
news id: 55bb32ae535c12e543006e15; tags: [Русский,  религия,  пятница,  Коран]
news id: 55666ac66390d8ce7900044f; tags: [Томск,  Россия]

A: According to that doc http://quickblox.com/developers/SimpleSample-customObjects-android#Search_operators
with arrays you can use only in, nin and all operators
UPD
For example, I have a class Post with a field tags. And a have a record where tags=["man","golf","car"]
This is my requests:
http://api.quickblox.com/data/Post.json?tags[in]=car&token=70f997fecf68b25f8992271b5f943503884f3f52

http://api.quickblox.com/data/Post.json?tags[in]=man&token=70f997fecf68b25f8992271b5f943503884f3f52

http://api.quickblox.com/data/Post.json?tags[in]=golf&token=70f997fecf68b25f8992271b5f943503884f3f52

They all return the same record:
{"class_name":"Post","skip":0,"limit":0,
  "items":[{"_id":"55ba0597535c12a4120011e8","_parent_id":"",
   "body":"How are you?",
   "created_at":1438254487,"tags":["man","golf","car"],
   "title":"best post","updated_at":1438254487,"user_id":291}]}


text:
Q: ggplot secondary y axes showing z scores using sec_axis ggplot2 now allows for adding a secondary y-axis if it is a one-to-one transformation of the primary axis.
For my graph, I would like to plot the original units on the left y-axis and z-scores on the right y-axis, but I am having trouble working out how to do this in practice.
The documentation suggests this secondary axes are added using the sec_axis() function e.g.,
scale_y_continuous(sec.axis = sec_axis(~.+10))

creates a second y-axis 10 units higher than the first.
Z-scores can be created in R using the scale() function. So I assumed I could do something like this to get a second y-axis displaying z-scores:
scale_y_continuous(sec.axis = sec_axis(scale(~.)))

However, this returns a "invalid first argument" error.
Does anyone have any ideas how to make this work?

A: You could use the z-score transformation formula. This works well:
library(tidyverse)
library(scales)
df <- data.frame(val = c(1:30), var = rnorm(30, 10,2))
p <- ggplot() + geom_line(data = df, aes( x = val, y = var))
p <- p + scale_y_continuous("variable", sec.axis = sec_axis(trans = ~./ sd(df$var) - mean(df$var)/ sd(df$var), "standarized variable"))
p

Or :
p + scale_y_continuous("variable", sec.axis = sec_axis(~ scale(.), "standarized variable"))


text:
Q: Space before / in the URL is removed by Apache HTTP Server I have apache http server running on Windows 2012 server.
It hosts webapp written using Flask and python.
@app.route('/temp/test/<market>/symbol/<path:symbol>/type/<product_type>/')
def test_func_not_in_use(market, symbol, product_type):
    return {'key': [market, symbol, product_type]}

Following is the URL and output:
http://<host:port>/temp/test/ICE_IPE/symbol/PSEG%20/PJM%20DA%20PK/type/MLEG/

{
  "key": [
    "ICE_IPE",
    "PSEG/PJM DA PK",
    "MLEG"
  ]
}

Notice that for symbol=PSEG%20/PJM%20DA%20PK value returned is PSEG/PJM DA PK
Space before / is removed.
I have verified that problem is not on Flask side by writing sample app and running it outside of apache. Also there are no rewrite rules defined in apache conf files.
Can someone please explain me what wrong here? And would love to see solution as well.


text:
Q: Google Maps won't start on iPhone 4 I tap on the icon for the app, the splash screen appears, and then it promptly crashes back to the home screen without a trace.
I've updated to the latest version of the app and the latest version of iOS but that hasn't helped.
I've tried turning the phone off and back on again and that hasn't helped either.
I'd like to try uninstalling and re-installing the app, but it's not clear how to do that from the phone itself.  I've tried to do so from iTunes on my PC, but it warns me that "This app will not be deleted from any iOS device that synchronizes with your iTunes library."
I'm at a loss.  I guess what I'm eventually going to have to do is just upgrade to the latest iPhone since it doesn't look like this old version is going to receive any more support.
Any ideas?


text:
Q: How do i access ( see ) on server the gps coordinates i have sent to the server from android? I have already gotten the coordinates and other paramaters i need. i have used this to post to my server:
                               String postData = "{\"request\":{\"type\":\"locationinfo\"},\"userinfo\":{\"latitude\":\""+latitude+"\",\"longitude\":\""+longitude+"\",\"speed\":\""+speed+"\"}}";

                                HttpClient httpClient = new DefaultHttpClient();

                                // Post method to send data to server
                                HttpPost post = new HttpPost();

                                try {
                                    post.setURI(new URI("http://10.0.2.15:80"));
                                } catch (URISyntaxException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }

                                // set your post data inside post method
                                try {
                                    post.setEntity(new StringEntity(postData));
                                } catch (UnsupportedEncodingException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }

                                // execute post request here
                                try {
                                    HttpResponse response = httpClient.execute(post);
                                } catch (ClientProtocolException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }

How am i sure it has gotten to the server? How do i see the coordinates on the server?
I want to save the values in a database and work on them.

A: When server accept your data just save them in database and as result that everything is saved, return the same data(accepted data from your client by server) to your client program.

Using this method, you will be sure in:

*

*Server accept your data

*Server accept right data

*Server saved data

Example:

Assume that I want to send 'Name = Michael' parameter to Server. When server accept parameter name i just save it in database and return the same parameter back to client ->'Name = Michael'.So, you can be sure that server get parameter.


text:
Q: convert in to int to string /*  In java-script while i converting the float to string for spiting the values. while converting it removes the last zeros after the dot. but i calculates the numbers not accecpting the zeros how to overcome this i have give in example 2.*/
//(Eg : 1)
    var num=2.15;
    var res=0;
    var str=num.toString();
    console.log("str",str);
    var numarray=str.split('.');
    var a=new Array();
    a=numarray;
    console.log(a[0]);
    console.log(a[1]);

/* OUTPUT :
 str => 2.15 ----> (Its bring the value)
 a[0] => 2
 a[1] => 15 */

//(Eg :2)
    var num=2.10;
    var res=0,a1,b1;
    var str=num.toString();
    console.log("str",str);
    var numarray=str.split('.');
    var a=new Array();
    a=numarray;
    console.log(a[0]);
    console.log(a[1]);

/* OUTPUT :
 str => 2.1  ---> (In that zero is not considering how to convert it )
 a[0] => 2
 a[1] => 1  -----> (I need whole value 10) */

A: You can check the length of numarray second item, if length is less than 2 means that it needs to concatenate a zero, try this:

var num = 2.10;
var res = 0, a1, b1;
var str = num.toString();

var numarray = str.split('.');
a = numarray;

console.log(a[0]);
console.log(a[1].length < 2 ? a[1] + '0' : a[1]);

A: if you know that you need to decimal places, you can do this.

var num=2.10;
var str = num.toFixed(2);
var arr = str.split('.');
console.log(arr);


text:
Q: IN Query for count very slow with loading of page, looking for another solution I have created the following Query:
$query = "SELECT COUNT(sire_id) as c, sire_id FROM dog WHERE sire_id IS NOT NULL GROUP BY sire_id ORDER BY c desc LIMIT 150 ";
$result = mysql_query($query) ;

$i=0;

while ($line = mysql_fetch_array($result)) {
  $sireQuery = "SELECT name, id, sire_id, dam_id, yearofbirth FROM dog WHERE id = " . $line["sire_id"];
  $sireResult = mysql_query($sireQuery) ;
  $sireLine = mysql_fetch_array($sireResult);
  $sr = mysql_query("SELECT name FROM dog WHERE id = " . $sireLine["sire_id"]);
  $sl = mysql_fetch_array($sr);
  $dr = mysql_query("SELECT name FROM dog WHERE id = " . $sireLine["dam_id"]);
  $dl = mysql_fetch_array($dr);
  $queryMS = "SELECT COUNT(DISTINCT dam_id) FROM dog WHERE sire_id = " . $line["sire_id"];
  $resultMS = mysql_query($queryMS);
  $totalMS = mysql_result($resultMS,0);

  $i++;

And now trying to get more info by adding the following
$queryoffS = "SELECT COUNT(id) FROM dog WHERE sire_id IN (SELECT id FROM dog WHERE sire_id = " .$line[sire_id]. ")";
$resultoffS = mysql_query($queryoffS);
$totaloffS = mysql_result($resultoffS,0);
$queryoffD = "SELECT COUNT(id) FROM dog WHERE dam_id IN (SELECT id FROM dog WHERE sire_id = " .$line[sire_id]. ")";
$resultoffD = mysql_query($queryoffD);
$totaloffD = mysql_result($resultoffD,0);
$totaloffspring = $totaloffS += $totaloffD;

But with adding that extra to my query the page loads really slow.
I wonder if there is a better way of writing this query so that it loads fast?

A: Revised query that I think will give you the counts you want with a single query.
SELECT dog.name, dog.id, dog.sire_id, dog.dam_id, dog.yearofbirth, parent_sire.name, parent_dam.name,
    COUNT(DISTINCT child.id) AS NumberOfChildren,
    COUNT(DISTINCT grandchild.id) AS NumberOfGrandChildren
FROM dog
LEFT OUTER JOIN dog AS parent_sire
ON dog.sire_id = parent_sire.id
LEFT OUTER JOIN dog AS parent_dam
ON dog.dam_id = parent_dam.id
LEFT OUTER JOIN
(
    SELECT id, sire_id AS parent_id
    FROM dog
    UNION
    SELECT id, dam_id AS parent_id
    FROM dog
) AS child
ON dog.id = child.parent_id
LEFT OUTER JOIN
(
    SELECT id, sire_id AS parent_id
    FROM dog
    UNION
    SELECT id, dam_id AS parent_id
    FROM dog
)  AS grandchild
ON child.id = grandchild.parent_id
GROUP BY dog.name, dog.id, dog.sire_id, dog.dam_id, dog.yearofbirth, parent_sire.name, parent_dam.name


text:
Q: Group by data in pandas dataframe I have a set of points in the following format. For each Id1, there is a set of Id2's with their latitude and longitude. For each group of Id1 and Id2, I need the first record in the group
except for the last group, in which i need both the first and last records. Please see below the output.
Just wondering is there a way in pandas I can achieve this. Any help would be appreciated. Thanks.
  Id1       Id2       Latitude        Longitude
  179       183       33.67           -83.24
  179       183       31.33           -83.11
  179       184       33.58           -83.34
  179       184       33.61           -83.14
  179       185       33.60           -83.54
  179       185       33.60           -83.54
  180       185       33.67           -83.64
  180       185       33.79           -83.74
  180       186       33.81           -83.84
  180       186       33.81           -83.84

Output:
  Id1       Id2       Latitude        Longitude
  179       183       33.67           -83.24
  179       184       33.58           -83.34
  179       185       33.60           -83.54
  179       185       33.60           -83.54
  179       186       33.79           -83.74
  179       186       33.81           -83.84
  180       185       33.67           -83.64
  180       186       33.81           -83.84
  180       186       33.81           -83.88

A: You can first find last value of column Id2, then filter where are no last values by boolean indexing and drop_duplicates:
last_row = df['Id2'].iloc[-1]
print (last_row)
186

df1 = df[df.Id2 != last_row].drop_duplicates(['Id1','Id2'])
print (df1)
   Id1  Id2  Latitude  Longitude
0  179  183     33.67     -83.24
2  179  184     33.58     -83.34
4  179  185     33.60     -83.54
7  180  185     33.67     -83.64

Then filter values with last value in Id2:
df2 = df[df.Id2 == last_row]
print (df2)
    Id1  Id2  Latitude  Longitude
5   179  186     33.81     -83.84
6   179  186     33.81     -83.84
9   180  186     33.81     -83.84
10  180  186     33.81     -83.84

And last concat together:
print (pd.concat([df1,df2]).reset_index(drop=True))
   Id1  Id2  Latitude  Longitude
0  179  183     33.67     -83.24
1  179  184     33.58     -83.34
2  179  185     33.60     -83.54
3  180  185     33.67     -83.64
4  179  186     33.81     -83.84
5  179  186     33.81     -83.84
6  180  186     33.81     -83.84
7  180  186     33.81     -83.84

If need only last group change condition:
lastId1 = df['Id1'].iloc[-1]
print (lastId1)
180
lastId2 = df['Id2'].iloc[-1]
print (lastId2)
186

mask = (df.Id1 == lastId1) & (df.Id2 == lastId2)
df1 = df[~mask].drop_duplicates(['Id1','Id2']).drop_duplicates(['Id1','Id2'])
print (df1)
   Id1  Id2  Latitude  Longitude
0  179  183     33.67     -83.24
2  179  184     33.58     -83.34
4  179  185     33.60     -83.54
5  179  186     33.81     -83.84
7  180  185     33.67     -83.64

df2 = df[mask]
print (df2)
    Id1  Id2  Latitude  Longitude
9   180  186     33.81     -83.84
10  180  186     33.81     -83.84

print (pd.concat([df1,df2]).reset_index(drop=True))
   Id1  Id2  Latitude  Longitude
0  179  183     33.67     -83.24
1  179  184     33.58     -83.34
2  179  185     33.60     -83.54
3  179  186     33.81     -83.84
4  180  185     33.67     -83.64
5  180  186     33.81     -83.84
6  180  186     33.81     -83.84

A: This one is a bit less pandas-oriented but it uses group-by operations:
# Function to check if row values are equal to last_group values
def compare_to_groups(x, last_groups):
    return  any((x[['Id1','Id2']] == last_groups[i]).all(1).any() for i in range(len(last_groups)))

# Get the last groups
last_groups = df.groupby('Id1')['Id1','Id2'].last().values

# Apply to each group
df.groupby(['Id1','Id2']).apply(lambda x: x if compare_to_groups(x, last_groups) else x.head(1)).reset_index(drop=True)

It should yield:
   Id1  Id2  Latitude  Longitude
0  179  183     33.67     -83.24
1  179  184     33.58     -83.34
2  179  185     33.60     -83.54
3  179  185     33.60     -83.54
4  180  185     33.67     -83.64
5  180  186     33.81     -83.84
6  180  186     33.81     -83.84

I hope this helps.