text:
Q: Remove an item from a list-view control I have a list-view control in my program and I want to remove the selected item. This is done with a button press.
The problem is that no matter what item I select it always deletes the first one...
I think the problem is with the list-view focus being lost. When the button is pressed, the list-view loses focus first, then it tries to remove an item that's not selected anymore, thus it removes the first one.
My question is: Is there any option to make the list-view not to lose its focus?
EDIT:
Here's the code :
stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#define WIN32_LEAN_AND_MEAN    // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <windowsx.h>
#include <commctrl.h>

// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here

Main.cpp
#include "stdafx.h"

LRESULT CALLBACK WindowFunc(HWND, UINT, WPARAM, LPARAM);

void CreateList();
void CreateButtons();

enum
{
    IDC_REMOVE_BUTTON = 1000,
    IDC_LIST
};

struct ListBox
{
    HWND hwnd;

    LVCOLUMN lvc;
    LVITEM   lv;

    ListBox(HWND h = 0, LVCOLUMN l = { 0 }, LVITEM lvi = { 0 })
    {
        hwnd = h;
        lvc = l;
        lv = lvi;
    }

};

int selitm = -1;

HINSTANCE g_hInstance;

HWND hwndRemoveButton;

HWND g_hwnd;

ListBox List;

int WINAPI WinMain(HINSTANCE hThisInst, HINSTANCE hPrevInst,
    LPSTR Args, int WinMode)
{
    HWND hWnd;
    MSG Message;
    WNDCLASSEX WinClass = { 0 };
    INITCOMMONCONTROLSEX icc = { 0 };

    g_hInstance = hThisInst;

    icc.dwSize = sizeof(icc);
    icc.dwICC = ICC_LISTVIEW_CLASSES;
    InitCommonControlsEx(&icc);

    WinClass.cbSize = sizeof(WNDCLASSEX);
    WinClass.hInstance = hThisInst;
    WinClass.lpszClassName = "Test";
    WinClass.lpfnWndProc = WindowFunc;
    WinClass.style = 0;
    WinClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    WinClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
    WinClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    WinClass.lpszMenuName = NULL;
    WinClass.cbClsExtra = 0;
    WinClass.cbWndExtra = 0;
    WinClass.hbrBackground = (HBRUSH)COLOR_WINDOW;

    if (!RegisterClassEx(&WinClass)) return 0;

    hWnd = CreateWindow("Test", "Test", WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 660, 350,
        NULL, NULL, hThisInst, NULL);

    ShowWindow(hWnd, WinMode);
    UpdateWindow(hWnd);

    while (GetMessage(&Message, NULL, 0, 0))
    {
        TranslateMessage(&Message);
        DispatchMessage(&Message);
    }

    return Message.wParam;
}

LRESULT CALLBACK WindowFunc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{

    switch (Message)
    {
    case WM_CREATE:

        g_hwnd = hWnd;

        CreateList();
        CreateButtons();

        ListView_InsertItem(List.hwnd, &List.lv);
        ListView_SetCheckState(List.hwnd, List.lv.iItem, true);
        ListView_SetItemText(List.hwnd, List.lv.iItem, 1, "One");
        ListView_SetItemText(List.hwnd, List.lv.iItem, 2, "$1");
        ListView_SetItemText(List.hwnd, List.lv.iItem++, 3, "2010-05-05");

        ListView_InsertItem(List.hwnd, &List.lv);
        ListView_SetCheckState(List.hwnd, List.lv.iItem, true);
        ListView_SetItemText(List.hwnd, List.lv.iItem, 1, "Two");
        ListView_SetItemText(List.hwnd, List.lv.iItem, 2, "$2");
        ListView_SetItemText(List.hwnd, List.lv.iItem++, 3, "2008-05-05");

        ListView_InsertItem(List.hwnd, &List.lv);
        ListView_SetCheckState(List.hwnd, List.lv.iItem, false);
        ListView_SetItemText(List.hwnd, List.lv.iItem, 1, "Three");
        ListView_SetItemText(List.hwnd, List.lv.iItem, 2, "$3");
        ListView_SetItemText(List.hwnd, List.lv.iItem++, 3, "2006-05-05");

        break;

    case WM_COMMAND:

        // The low word of wParam contains the menu ID.
        switch (LOWORD(wParam))
        {

        case IDC_REMOVE_BUTTON:

            selitm = ListView_GetFocusedGroup(List.hwnd);

            ListView_DeleteItem(List.hwnd, selitm);

            break;

        }

        break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(hWnd,
            Message,
            wParam,
            lParam);
    }
    return 0;
}

void CreateButtons()
{
    hwndRemoveButton = CreateWindow("Button", "Remove",
        BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE,
        20, 265, 70, 30,
        g_hwnd, (HMENU)IDC_REMOVE_BUTTON,
        g_hInstance, NULL);
}

void CreateList()
{

    List.hwnd = CreateWindow(WC_LISTVIEW, NULL,
    WS_CHILD | WS_VISIBLE | LVS_REPORT,
    20, 30, 600, 230,
    g_hwnd, (HMENU)IDC_LIST, g_hInstance, NULL);

    ListView_SetExtendedListViewStyle(List.hwnd, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP);

    List.lvc.mask = LVCF_TEXT | LVCF_SUBITEM | LVCF_WIDTH | LVCF_FMT;
    List.lvc.fmt = LVCFMT_LEFT;

    /* Add four columns to the list-view (first column contains check box). */
    List.lvc.iSubItem = 0;

    List.lvc.cx = 50;
    List.lvc.pszText = "Good?";
    ListView_InsertColumn(List.hwnd, List.lvc.iSubItem++, &List.lvc);

    List.lvc.cx = 300;
    List.lvc.pszText = "Name";
    ListView_InsertColumn(List.hwnd, List.lvc.iSubItem++, &List.lvc);

    List.lvc.cx = 150;
    List.lvc.pszText = "Cost";
    ListView_InsertColumn(List.hwnd, List.lvc.iSubItem++, &List.lvc);

    List.lvc.cx = 100;
    List.lvc.pszText = "Watched Since";
    ListView_InsertColumn(List.hwnd, List.lvc.iSubItem++, &List.lvc);

    List.lv.iItem = 0;

}

A: Your problem has nothing to do with focus.  You are using the wrong API to determine the selected item.  You are using ListView_GetFocusedGroup() when you need to use ListView_GetNextItem() instead:
selitm = ListView_GetNextItem(List.hwnd, -1, LVNI_SELECTED);
if (selitm != -1)
    ListView_DeleteItem(List.hwnd, selitm);

A: You are calling ListView_GetFocusedGroup. As documented this:

Gets the group that has the focus

Groups are a somewhat advanced feature of list views. Again, as documented:

Grouping allows a user to arrange lists into groups of items that are visually divided on the page, using a horizontal divider and a group title.

So, that's just not what you want. The API that you need to get the selected item is ListView_GetNextItem. Call it like this:
int selectedIndex = ListView_GetNextItem(List.hwnd, -1, LVNI_ALL | LVNI_SELECTED);
if (selectedIndex != -1)
    ListView_DeleteItem(List.hwnd, selitm);


text:
Q: PyGame: Char not moving I have written a code which aims to move a horse when pressing the right arrow key, but when I press it, it doesnt move. I can't seem notice where the problem is. I have typed print(a.locx) in def char() to see a.locx is increasing or not but its not and also in class Horse()'s method def location() when I press right arrow key self.locx is increasing and then instantly decreasing.
import pygame
from pygame import locals
def main():
    global window,width,height
    pygame.init()
    width ,height = 500,500
    window = pygame.display.set_mode((width,height))

    while True:
        window.fill((0,0,0))

        for event in pygame.event.get():
            if pygame.event == pygame.QUIT:
                pygame.quit()
        char()

        pygame.display.update()

def char():
    a = Horse()
    window.blit(a.horse1,(a.locx,a.locy))
    print(a.locx)
    a.location()

class Horse():
    def __init__(self):
        self.horse1 = pygame.image.load("C:/Users/niimet/Desktop/pygeym/blitz/Horse_Walk3.png")

        self.horse2 = []

        for horse in range(0,8):
            self.horse2.append(pygame.image.load(("C:/Users/niimet/Desktop/pygeym/blitz/Horse_Walk{}.png").format(horse+1)))

        self.horse3 = []

        for horse in self.horse2:
            self.horse3.append(pygame.transform.flip(horse,True,False))

        self.locx = 0
        self.locy = width - self.horse1.get_size()[1]

    def location(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_RIGHT]:
            print(self.locx,"1")
            self.locx += 200
            print(self.locx,"2")

main()

A: The issue is that you crate a new Horse object in every frame and so the horse continuously "starts" at its initial position.

def char():
   a = Horse() # <--- creates new Hors object with "self.locx = 0"
   # [...]

Create a Horse in global name space and use this object:
def main():
    global window, width, height, a

    pygame.init()
    width, height = 500,500
    window = pygame.display.set_mode((width,height))
    a = Horse()

    while True:
        window.fill((0,0,0))

        for event in pygame.event.get():
            if pygame.event == pygame.QUIT:
                pygame.quit()
        char()

        pygame.display.update()

def char():
    window.blit(a.horse1,(a.locx,a.locy))
    print(a.locx)
    a.location()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optimizing the declaration of variables in my project In my current project I am using 67 variables out of which few are string, int, decimal and bools.
I would like to optimize my declaration of code. I am using c#. What is the best way to do the declaration according to coding standards. It would be great if you can help me with an example.

A: Your question is very unclear, but from the sound of it, it kind of sounds like your variables are all lumped in one place, I'm assuming either as locals to Main() or fields in a single class?
If so the best advice we can give is remember your Single Responsibility Principle (SRP) and other good OOD techniques.
Your classes (and methods, etc) should be small enough to fulfill one and only one responsibility, any class (or method) that is that large is probably doing way too much.


text:
Q: Problem with a Delphi dbxpress application after upgrading Windows Server 2008 to Windows server 2012 I want to upgrade a Windows server 2008 to windows Server 2012, and, if possible, 2016 and 2019.
This server runs a Delphi XE2 Interbase XE3 dbexpress application.
After upgrading the server to windows server 2012, compilation of the app is OK, but it breaks during connection to the Database:
DBX error: Driver could not be properly initialized
Client library May be missing, of the wrong version,
May be missing from the driver or the system path
How to fix that ? Update the driver (dbxint.dll ?) ? upgrade to Delphi 10 ?
Thanks

A: I copied a newer version (12.0.354) of gds32.dll into windows32\system32 and it WORKS now !!!  I get this version from a Delphi 10 installation.


text:
Q: We are given an $18\times 18$ table, all of whose cells may be black or white. We are given an $18\times 18$ table, all
of whose cells may be black or white. Initially all the cells are
colored white. We may perform the following operation: choose one
column or one row and change the color of all cells in this column
or row. Is it possible by repeating the operation to obtain a
table with exactly $16$ black cells?
Now I wonder if a following solution is correct?

All the matrix here are $18\times 18$. Let $S$ be a matrix with all entry $1$ and $F$ be a matrix with exactly $16$ entries with $0$ and the other entries are $1$.
Let $A_i$ be a matrix with all entries $1$ on $i$-th row, for $1\leq
i\leq 18$ and the other are 0 and with all entries $1$ on
$(i-18)$-th column for $19\leq i\leq 36$ and the other are zero.
So, for example:
$$A_2 =\begin{bmatrix}
0 & 0 & \dots & 0&0\\
1&1&\dots &1&1\\
0 & 0 & \dots & 0&0\\
\vdots & \vdots & \dots & \vdots &\vdots\\
0 & 0 & \dots & 0&0
\end{bmatrix}
\;\;\;{\rm and}\;\;\; A_{19} =\begin{bmatrix}
1 & 0 & \dots & 0&0\\
1&0&\dots &0&0\\
1 & 0 & \dots & 0&0\\
\vdots & \vdots & \dots & \vdots &\vdots\\
1 & 0 & \dots & 0&0
\end{bmatrix}
$$
We can understand a table as a matrix with entry $1$ if
corresponding cell is white and $0$ if it is black. So $S$ is a
starting matrix and $F$ a final matrix. Now each recoloring of a
given matrix $M$ is actually $M+A_i$ for some $i\leq 36$
So after some transformations we have equality like this $$F = S +
a_1A_1+a_2A_2+...+a_{36}A_{36}$$ where $a_i\in \{ 0,1\}$ for all
$i$. Mark $F-S = D$, so $D$ is a matrix with exactly $16$ ones.
Now what can we say about $a_1,a_2,...$? Since $D$ has exactly $16$
ones it must have at least two columns and two rows with only
zeros. We can assume that all entries in first $2$ rows and first $2$
columns are $0$, so $D$ is like:
$$ D =\begin{bmatrix}
0 & 0 & 0&\dots & 0&0\\
0 & 0 &0 &\dots &0&0\\
0 & 0 & *& \dots & *&*\\
\vdots & \vdots & \vdots & \dots &\vdots& \vdots\\
0 & 0 & *&\dots & *&*
\end{bmatrix}
$$
If $a_1=1$ then each $a_{19},a_{20},...a_{36}$ must also be $1$
since in first row must be all $0$. But then we must have also
$a_2,...,a_{18}$ all $1$ since in first column are only $0$. This
means that $D$ is a zero matrix which is not true. So $a_1=0$ and thus
all $a_{19},a_{20},...a_{36}$ are $0$ and then also all
$a_2,...,a_{18}$ are $0$ so $D$ is zero matrix again. A
contradiction.

This is not a duplicate. I don't want a solution like in that link, I want a proof verification!

A: Changing all entries of a row or column is equivalent to adding a row of all 1's to that row or adding a column of all 1's to that column (modulo 2). Suppose we have added $k$ rows and $l$ columns of all 1's to the zero matrix and have obtained a matrix with exactly 16 entries equal to 1. First note that we can eliminate two equal rows (addition is commutative and two equal rows add up to zero modulo 2). So we can assume all the rows are different and all the columns are different. In particular $0\leq k,l\leq 18$.
Now, by adding $k$ different rows of all 1's and $l$ different columns of all 1's we get exactly $18k+18l-kl$ entries equal to 1. So we want
$$18k+18l-kl=16,~0\leq k,l \leq 18.$$
To solve this, rewrite it as $(18-k)(18-l)=18^2-16=4*7*11$. Since the product of every two of the numbers 4, 7, and 11 exceeds 18, this equation has no solutions within the required range.

A: Let $V$ be the vector space over the field with two elements, $\Bbb F_2$, generated by all matrices of shape $N\times N$, $N=18$, which have exactly one row, or exactly one column with one entries, all other entries being zero. We consider the following map from $V$ to $\Bbb F_2$:
$X$ in $V$ is mapped to
$$
f(X)=
(x_{11}+x_{22}+\dots+x_{N-1,N-1}+x_{N,N})
+
(x_{12}+x_{23}+\dots+x_{N-1,N}+x_{N,1})\ .
$$
(Sum on two consecutive fixed diagonals of $X$, where the indices are considered modulo $N$.)
Then each generator of $V$ is mapped to zero, since the "bits" taken in $f(X)$ are exactly two in each row and/or column. So $f$ vanishes on $V$. But it does not vanish on any quadratic submatrix $A=A(I)$ with ones exactly on the positions $I\times I$, $I$ being a proper interval of $\{1,2,\dots,N\}$. (For instance $I=\{1,\dots,16\}$ for our $N=18$.)
So in our case the answer to the problem is negative.
(The "change of the color on a line/columns" corresponds to adding a generator of $V$ to a matrix. We are starting with a zero matrix. The matrices that can be obtained are exactly those in the vector space $V$ of dimension $N+N-1$.)
Note: I can provide some simple computer check in sage, if needed.

Later edit: It is simpler to test the equations
$$
x_{is}-x_{js}-x_{it}+x_{jt}=0\ ,\qquad 1\le i<j\le N\ ,\ 1\le s<t\le N\ ,
$$
that can be extracted from all $2\times 2$ minors of a matrix $X$ in order to test/decide if a matrix $X$ can be realized. (The minus is also a plus, but makes it simpler to see that e.g. each of the above "one row matrix of ones" satisfy the equation, explicitly $1-1-0+0=0$, and correspondingly for the column matrices in the base of $V$...)

A: Yes, this proof looks good to me.


text:
Q: How can I make Steam use Nvidia Graphics on Ubuntu 21.10? My question is in the title.
I just want Steam and games launched by Steam to use proper acceleration. I expected this to work out of the box on a fresh Ubuntu 21.10 installation, but apparently, it doesn't. I am using the Nvidia 510 driver and nvidia-prime is installed.

A: Now it works. Not sure what I did.
Anyway, here is the answer to my question:

Launch Steam from terminal using DRI_PRIME=1 steam. Now every game you
launch from Steam will use the AMD GPU.
Alternatively, if you are using GNOME, you can right-click the steam
icon then choose "Launch using Dedicated Graphics Card".


text:
Q: Linq group by and order by create date I have a list of messages in db like so:
FromLoginId, ToLoginId, Message, CreateDate

*

*1, 2, "some message", 2/2/2010

*1, 2, "one more", 2/3/2010

*4, 2, "from 4 message", 3/4/2010

*5, 2, "from 5 mess", 1/3/2010

*5, 2, "newer 5", 3/2/2011

I need to have a list of messages grouped by FromLoginId ordered by createDate starting from the newest first.
EDIT: List of messages with the first newest message from the FromLoginId group.
so for example for loginid 2 I would get this result:
FromLoginId, ToLoginId, Message, CreateDate

*

*5, 2, "newer 5", 3/2/2011

*4, 2, "from 4 message", 3/4/2010

*1, 2, "one more", 2/3/2010

please help.
thanks

A: I think i figured it out. looks ok to me. can anyone please check it?
list.GroupBy(x => x.FromLoginId)
   .Select(x => x.OrderByDescending(y => y.CreateDate)
   .FirstOrDefault())
   .OrderByDescending(x => x.CreateDate)

A: If you group by FromLoginId you can't display the messages themselves, only the count of them, or any aggregate function that might interest you.


text:
Q: Analyzing Protobuf vs JSON and ran into issues with data size I was tasked to look at data sizes and process speed (speed to create the data) of equal data in JSON format vs. Protobuf, in Java.
For JSON, I'm using Jackson, and I created a Subscriptions class with a List<HashMap<String,String> field, called subscriptionList. Each HashMap would correspond to 1 subscription. I am reading from a file, each line is "|" delimited for fields, there are 523 fields. I loop through each field assigning to the subscription HashMap column name for the key and column value for the value. I loop through each line to create all 1000 subscriptions, I put them into an ArrayList<HashMap<String,String>>, then I create a Subscriptions, and set subscriptionList to the ArrayList with 1000 subscriptions. Finally I convert the Subscriptions object to string in JSON format, and write that to a text file, measure the size of the text file, and that's how I am measuring the size of the data.
For protobuf, the .proto file look something like,
message Subscriptions {
    repeated Subscription subscription = 1;
}
message Subscription {
    map<string, string> attr = 1;
}

I loop through each line and each column again, creating 1000 Subscription messages, I then repeatedly added the Subscription messages to a Subscriptions message. I then use the .getSerializedSize method, and that's how I measured the protobuf messages data sizes.
Currently, I see that the two formats give me basically the same data sizes, which I don't understand why. Protobuf messages are already inherently compressed some, and they're known to be less space demanding than raw JSON. I don't know what I am doing wrong, and I ran out of ideas to try.

A: You won't get much a difference between a map turned to a JSON object and the same map turned to a protobuf message. For example in protobuf there are no quotes around object keys and no braces around the first level message, but this doesn't make much of a difference, specially in large datasets.
You will see some difference in protobuf while using packed repeated fields (only primitive types) since those are converted to binary values hence largely decreasing in size compared to UTF8 encoding in JSON.


text:
Q: How much ram needed to hold a huge list? I want to create an empty list of lists:
shape = (70000,70000)
corr = np.empty(shape).tolist()

How can I know how much RAM I need to hold this list using windows operating system (64 bit)?

A: This will create a list-of-lists-of-floats. About half of the RAM used is for the floats themselves and half is for the references to them. The size of each reference is 8 bytes and the size of each float is also 8 bytes. That makes 70000 * 70000 * 8 * 2 bytes (approx 80G).
Lists look like this in memory:

image source: here
The 70001 lists objects themselves also have overhead (they maintain pointer into storage array, and their own length), but this will be negligible in comparison (probably ~4 MB).
Also note that Python lists overallocate space by an implementation-dependent factor, so consider these numbers a lower bound. Memory is over-allocated so that there are always some free slots available, which makes appends and inserts faster. The space allocated increased by about 12.5% when full.


text:
Q: Google maps/places API search by phone We have a signup page where the user enters his business phone number. We want to find his business information from the phone number for verification. How can this be done with Google places/maps api? Is there any better alternative? I am kind of lost.

A: After looking through the google api to double-check, their response doesn't return a phone number for the company either. https://developers.google.com/places/web-service/
It also may depend on the type of business you're looking for but Yelp does allow phone number searches in their API:
https://www.yelp.com/developers/documentation/v2/phone_search

A: Looks like you can get what you want using the Place details call of the web-service api.  Amongst the fields returned are the formatted_phone_number and international_phone_number.


text:
Q: How to stop Evolution from restoring deleted calendar events? I have an event that was created by someone else and sent to three separate calendars (two Google and one from another provider), so it appears three times on my Evolution calendar display. This is driving me nuts, so I want to delete two of them.
If I right-click on the duplicate events and select "Delete Appointment," they go away. But then they come back a few minutes later. This is true both for a Google calendar and one from another provider.
I have noticed this in other contexts too, where if I delete a single instance of a recurring event created by someone else it will reappear a few minutes later.
Why, why, why? How can I get this to stop?


text:
Q: How does Singleton pattern stay in memory throughout the lifetime of the program? I have the following code:
//init X (DB initialization with credentials)
$x = MySqlConnector::getMySql();

//I destroy $x
unset($x);
$x = null;

//I try to re-initialize the database, but it is already initialized
//as evident from my logs
$x = MySqlConnector::getMySql();

Relevant function:
public static function getMySql()
{
    if (null === static::$instance)
    {
        include 'include/config.php';
        static::$instance = new MySql(DBHOST, DBUSER, DBPASS);
    }

    return static::$instance;
}

That tells me that even after I kill off the variable that was holding the initialized object, somehow MySqlConnector stayed in memory.
How? I don't think it works with any other non-static class.

A: Static properties exist in the global scope, and are not associated to any particular instance.
You may be unsetting $x, but MySqlConnector::$instance stays defined.
Typically, in this kind of scenario, $instance will be a private static, so you wont be able to access the property directly, only through accesor methods, hence guaranteeing that only the Singleton class will have access to modify the property, and you wont be changing/setting/unsetting it but through properly defined methods, if they exist.
More info in the manual.


text:
Q: Apache reverse proxy forwarding https header I have successfully installed reverse proxy on Apache. It works like a charm. I'm using it to proxy https request to http. My problem is that I need to forward variable SERVER_HTTPS to my end server, to indicate if person is using ssl connection or just http. I have found one way to do:
 Each time I can forward HTTP_X_FORWARDED_PROTO variable and check on end server:
   if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
   $_SERVER['HTTPS']='on';

But this variant is not good for me, because I can't edit the end servers scripts. Lets say that I don't even have access to it. But I know how to check if it is forwarded. So, Generally my question is: Is there any way that I can forward this variable? I have seen one more variant, with Rewrite engine , but it didn't work for me and there is no detailed information. Maybe If I will set my server on Nginx + apache this will send this header variable?

A: If you can edit the end server configuration, take a look at mod_rpaf RPAF_SetHTTPS option :
https://github.com/gnif/mod_rpaf


text:
Q: My script works the first time and does anymore not after reload on this online IDE I have a slight problem with this online code editor. When I launch my snippet, it only works one time. If I try to bring any modification to the code, it crashes for unknown reasons.
https://playcode.io/313059?tabs=console&script.js&output
Any clue of what is going on here?

A: I just checked and I think that your code is executing while the editor is not loaded yet. Wait for the document or window to be loaded and then execute the code as following:
    $( document ).ready(function() {
      var block = document.getElementById('block');

      var block_scale = window
        .getComputedStyle(block, null)
        .getPropertyValue("transform");

      var matrix = block_scale.match(/\d+(?:\.\d+)?/gm);
      console.log(matrix[0]);
    });


text:
Q: Plot large raster in R I've got a large (8GB) raster file that I'd like to plot in R. I try to do the below, but I run out of memory. I'd like some input and ideas on what to do please? Thanks, James.
library(raster)
library(rasterVis)

# ---- setting the colours ------------#
my.at <- c( 0,0.5, 1, 2.5, 5, 10, 15, 20, 25, 30,35,40,45,50, 100, 260)

colours<-c("paleturquoise","lightcyan", "brown","burlywood","bisque2","darkorange2","lightpink",
       "darkred","gold1","mediumorchid1","hotpink2", "darkblue","darkblue", "violetred4","violetred4")

    pdf("plot_1b.pdf", width=10, height=20)
    par(bty='n')
    par(mar=c(0, 0,0,0))
    plot(raster("2015-06-23_001403_21674_63649.grd"),
         xlim=c(-1200000, -650000),
         ylim=c(-260000,550000),
         maxpixels=445500000000,
         breaks=my.at,
         col = colours,
         lab.breaks=my.at,
         legend=FALSE,
         axes=FALSE)
    dev.off()


text:
Q: How does Nearest Neighbor Image Resampling work in ArcGIS? I am trying to understand how nearest neighbor for the resampling of Image datasets works in ArcGIS.
The output raster cell value is the value of the closest cell value in the input raster:

In this case the center of each output cell is the middle cell of each 3x3 input cells.
what happens if they are all at the same distance?
if the output has half the dimension of the input, the center of the output will have the same distance to the 4 closest neigh input cells ?
InRas1=6x6
OutRas=3x3

He gets the majority of cell values? No
Or am I missing something here?

A: Following R.K. suggestion, I have made 3 diferent rasters to test the NN resampling method in arcGIS and when passing from InRas resolution to a resolution that is 1/2 of it, the value of the new cell is allways given by the lower right input cell.
On the left the different InRas files I've created (cell size1, 6x6), on the right the output of the Resampling Tool with Nearest Neighbor with output cell size of 2.
They usually recommend this method to be applied when resampling land use datasets, however I would probably go for a majority filter instead of a NN.

A: I looked up the NN algorithm in several remote sensing textbooks and everywhere it is stated that the algorithm "selects the value of the pixel center closest to the x,y location".
the question that should interest now is where the particular locations are in your different cases? for the 3x3 example it was in the center of the 6x6 block. in the 2x2 case it is in the lower right. hence it seems that the location of the 'x,y location' changes, perhaps because a 'target block' with even numbers does not have a center. I guess every programmer choses another corner for that special case.
further, in the textbooks the authors often illustrate resampling techniques with a 'target pixel' rotated by 45° and then laid onto an pixel of a larger image. in those examples it becomes clear where the "center location" is. however I think these are not well suited to explain 'resampling'...
hope that helped?

A: Nearest Neighbor calculates an index value based on the average distance from each feature to its nearest neighboring feature. For raster images, it is recommended that cell size be similar.  If cell size and resolution are not the same, the coarsest resolution becomes the parameter for the resampling calculation. Remember that the attributes will reflect the resolution of the original source.
For more detailed info on raster cell size resampling you can go to the ArcGIS Resource Center using the following link: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//00590000001m000000


text:
Q: oauth2client is now deprecated In the Python code for requesting data from Google Analytics ( https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py ) via an API, oauth2client is being used. The code was last time updated in July 2018 and until now the oauth2client is deprecated. My question is can I get the same code, where instead of oauth2client, google-auth or oauthlib is being used ?
I was googling to find a solution how to replace the parts of code where oauth2client is being used. Yet since I am not a developer I didn't succeed. This is how I tried to adapt the code in this link ( https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py ) to google-auth. Any idea how to fix this ?
import argparse

from apiclient.discovery import build
from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp

SCOPES = ['...']
DISCOVERY_URI = ('...')
CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
VIEW_ID = '...'

def initialize_analyticsreporting():
  """Initializes the analyticsreporting service object.

  Returns:l
    analytics an authorized analyticsreporting service object.
  """
  # Parse command-line arguments.
  credentials = service_account.Credentials.from_service_account_file(CLIENT_SECRETS_PATH)

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
authed_http = AuthorizedHttp(credentials)

response = authed_http.request(
    'GET', SCOPES)

  # Build the service object.
  analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)

  return analytics

def get_report(analytics):
  # Use the Analytics Service Object to query the Analytics Reporting API V4.
  return analytics.reports().batchGet(
      body=
    {
    "reportRequests":[
    {
      "viewId":VIEW_ID,
      "dateRanges":[
      {
        "startDate":"2019-01-01",
        "endDate":"yesterday"
      }],
      "dimensions":[
      {
        "name":"ga:transactionId"
      },
      {
        "name":"ga:sourceMedium"
      },
      {
        "name":"ga:date"
      }],
      "metrics":[
      {
        "expression":"ga:transactionRevenue"
      }]
    }]
  }
).execute()

def printResults(response):
  for report in response.get("reports", []):
    columnHeader = report.get("columnHeader", {})
    dimensionHeaders = columnHeader.get("dimensions", [])
    metricHeaders = columnHeader.get("metricHeader", {}).get("metricHeaderEntries", [])
    rows = report.get("data", {}).get("rows", [])

    for row in rows:
      dimensions = row.get("dimensions", [])
      dateRangeValues = row.get("metrics", [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print (header + ": " + dimension)

      for i, values in enumerate(dateRangeValues):
        for metric, value in zip(metricHeaders, values.get("values")):
          print (metric.get("name") + ": " + value)

def main():

  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  printResults(response)

if __name__ == '__main__':
  main()

I need to obtain response in form of a json with given dimensions and metrics from Google Analytics.

A: For those running into this problem and wish to port to the newer auth libraries, do a diff b/w the 2 different versions of the short/simple Google Drive API sample at the code repo for the G Suite APIs intro codelab to see what needs to be updated (and what can stay as-is). The bottom-line is that the API client library code can remain the same while all you do is swap out the auth libraries underneath.
Note that sample is only for user acct auth... for svc acct auth, the update is similar, but I don't have an example of that yet (working on one though... will update this once it's published).


text:
Q: Use values from dataset as reference line in scatterplot I have a dataset with K subjects, all analyzed for L aspects, M parameters per aspect and the mean and difference of 1 of these M parameters.
After Layered by ASPECTS, using
GGRAPH
  /GRAPHDATASET NAME="graphdataset" VARIABLES=read write
  /GRAPHSPEC SOURCE=INLINE.
BEGIN GPL
SOURCE: s=userSource(id("graphdataset"))
DATA: read=col(source(s), name("read"))
DATA: write=col(source(s), name("write"))
GUIDE: form.line(position(*,60), color(color.red))
ELEMENT: point(position(read*write))
END GPL.

[taken from http://www.ats.ucla.edu/stat/spss/library/ggraph_examples.htm]
I am able to create scatterplots with reference lines manually, but I would like to use a variable value in the dataset to replace the "60" or "65" in the code above. How can I do this?
I tried
GGRAPH
  /GRAPHDATASET NAME="graphdataset" VARIABLES=read write ref
  /GRAPHSPEC SOURCE=INLINE.
BEGIN GPL
SOURCE: s=userSource(id("graphdataset"))
DATA: read=col(source(s), name("read"))
DATA: write=col(source(s), name("write"))
DATA: ref=col(source(s), name("ref"))
GUIDE: form.line(position(*,"ref"), color(color.red))
ELEMENT: point(position(read*write))
END GPL.

Added is ref (constant value per ASPECT, present for each SUBJECT) in line 2, in DATA and in GUIDE. This does not work, however.


text:
Q: How to create function in my AngularJS? I'm new in AngularJS. I want to create cart shopping to WebSQL. How to create function addToCart and removeCart?.
Here is my code :
angular.module('ecommerce').factory('CartService',
    ['$webSql', '$http', '$q', 'urls',
        function ($webSql, $http, $q, urls) {

            var factory = {
                addToCart: addToCart,
                removeCart: removeCart
            };

            return factory;]
        }
    ]);

A: Function can be created in different ways .So in your case :
Solution 1 : Function Expression
angular.module('ecommerce').factory('CartService',
['$webSql', '$http', '$q', 'urls',
    function ($webSql, $http, $q, urls) {
        var addToCart = function () {//body of function}
        var factory = {
            addToCart: addToCart,
            removeCart: removeCart
        };

        return factory;]
    }
]);

Solution 2 : Function Declaration
angular.module('ecommerce').factory('CartService',
['$webSql', '$http', '$q', 'urls',
    function ($webSql, $http, $q, urls) {
        function addTocart () {//Body of function}
        var factory = {
            addToCart: addToCart,
            removeCart: removeCart
        };

        return factory;]
    }
]);

A function expression looks similar to function declarations, except that the function is assigned to a variable name.

A: angular.module('ecommerce').factory('CartService',
['$webSql', '$http', '$q', 'urls',
    function ($webSql, $http, $q, urls) {
        function addTocart () {
        $http.get(yoururl).then(response){
        console.log(response.data)
        }
        }
        var factory = {
            addToCart: addToCart,
            removeCart: removeCart
        };

    return factory;]
}
]);


text:
Q: Cannot read property 'previous' of undefined Functions in firebase throws me this error:
TypeError: Cannot read property 'previous' of undefined
at exports.sendNotifications.functions.database.ref.onWrite (/srv/index.js:5:19)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)

And my code is this:
exports.sendNotifications=functions.database.ref('/notifications/{notificationId}').onWrite((event)=>{
if(event.data.previous.val()){
  return;
}
if(!event.data.exists()){
  return;
}
})

Any idea how to fix this?

A: That often means that event does not have property data all the time. So you need to check first:
if('data' in event && event.data.previous.val()){
  return;
}

A: It happens because there is no data inside event so check that first. One of the ways is:
exports.sendNotifications=functions.database.ref('/notifications/{notificationId}').onWrite((event)=>{
if(!event.data){
  return;
}
if(event.data.previous.val()){
  return;
}
if(!event.data.exists()){
  return;
}
})


text:
Q: why does jspdf not working on mobile web app angular version 7 , jspdf 1.5.3
i have developing an webapp using angular7 which can use in mobile browser also . on button click i am generating pdf using jspdf but it is not working any mobile version . tried in all possible ways . alert i used to debug in mobile it  please help me with this
<button (click)="generatePDF()" class='btn btn-primary pdf'><i class="far fa-file-pdf"></i>Generate PDF</button>

public generatePDF() {
    var data = document.getElementById('contentToConvert');
    var data_width = document.getElementById('contentToConvert').clientWidth;
    html2canvas(document.querySelector('#contentToConvert')).
        then(canvas => {
            var imgWidth = data_width;
            var imgHeight = canvas.height * imgWidth / canvas.width;
            const contentDataURL = canvas.toDataURL('image/jpg', 0.5);
            let pdf = new jspdf('p', 'pt', [imgWidth + 10, imgHeight + 10], true);
            pdf.addImage(contentDataURL, 'PNG', 5, 5, imgWidth, imgHeight, undefined, 'FAST');
            let mydate = new Date()
            let month = mydate.getUTCMonth() + 1;
            let formatedDate = mydate.getUTCDate() + "_" + month + "_" + mydate.getFullYear();
            let fileName = formatedDate + '_' + 'Calendario_' + 'Darzalex_' + this._pdetails.Tratamientos
            pdf.save(fileName + ".pdf");
        });
}

A: Here you are converting to jpeg:

        const contentDataURL = canvas.toDataURL('image/jpg', 0.5);

And here you are adding the image as if it was a PNG:

        pdf.addImage(contentDataURL, 'PNG', 5, 5, imgWidth, imgHeight, undefined, 'FAST');

If you have still having issues I suggest posting more details about the results you are getting. If the image is not showing then I think aligning the image formats above (all JPEG or all PNG) might fix it. If the file is not being saved, then look at filesaver.js or your app's context.


text:
Q: How set value IsChecked in DataGridCheckBoxColumn.Header WPF I have been looking for two days and I have tried different things but without success
441/5000
I have a datagrid with a checkbox column with a checkbox header.
When I check the header checkbox, I have all my checkboxes checked and the reverse works too.
My problem:
If I check the header checkbox, all my column checkboxes are checked but if I uncheck one my header checkbox does not go off.
Can you help me ? How do I dynamically change the isChecked property of my header checkbox?
Candidate.cs
 public class Candidate : INotifyPropertyChanged
{
    public int CandidateID { get; set; }
    public int RegisterNo { get; set; }
    public string CandidateName { get; set; }
    private bool _IsSelected = false;
    private bool _IsChecked = false;
    public bool IsSelected { get { return _IsSelected; } set { _IsSelected = value; OnChanged("IsSelected"); } }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnChanged(string prop)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }

    #endregion
}

MainWindows.xaml.cs
    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        List<Candidate> tmp = new List<Candidate>();
        tmp.Add(new Candidate()
        {
            CandidateID = 1,
            CandidateName = "One",
            RegisterNo = 1
        });
        tmp.Add(new Candidate()
        {
            CandidateID = 2,
            CandidateName = "Two",
            RegisterNo = 2
        });
        tmp.Add(new Candidate()
        {
            CandidateID = 3,
            CandidateName = "Three",
            RegisterNo = 3
        });
        dgCandidate.ItemsSource = tmp;

    }
    private void chkSelectAll_Checked(object sender, RoutedEventArgs e)
    {
        foreach (Candidate c in dgCandidate.ItemsSource)
        {
            c.IsSelected = true;
        }
    }

    private void chkSelectAll_Unchecked(object sender, RoutedEventArgs e)
    {
        foreach (Candidate c in dgCandidate.ItemsSource)
        {
            c.IsSelected = false;
        }
    }
}

XAML

        <DataGrid AutoGenerateColumns="False" CanUserAddRows="False" Height="130" HorizontalAlignment="Left" IsReadOnly="False" Margin="62,164,0,0" Name="dgCandidate" TabIndex="7" VerticalAlignment="Top" Width="466" >
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="colCandidateID" Binding="{Binding CandidateID}" Header="SlNo" MinWidth="20" IsReadOnly="True" />
                <DataGridTextColumn x:Name="colRegistraion" Binding="{Binding RegisterNo}" Header="Reg. No." IsReadOnly="True"  />
                <DataGridTextColumn x:Name="colCandidate" Binding="{Binding CandidateName}" Header="Name" MinWidth="250" IsReadOnly="True"  />
                <DataGridCheckBoxColumn Binding="{Binding IsSelected}">
                    <DataGridCheckBoxColumn.Header>
                        <CheckBox Name="chkSelectAll" IsChecked="True"  Checked="chkSelectAll_Checked" Unchecked="chkSelectAll_Unchecked"></CheckBox>
                    </DataGridCheckBoxColumn.Header>
                </DataGridCheckBoxColumn>
            </DataGrid.Columns>
        </DataGrid>

I'm curious to see how we can do this?
Sorry for my english and thank you in advance

A: You need to determine whether to check or uncheck chkSelectAll whenever an individual item is checked. You can to this by handling the PropertyChanged for all Candidate objects:
public MainWindow()
{
    InitializeComponent();
    List<Candidate> tmp = new List<Candidate>();
    tmp.Add(new Candidate()
    {
        CandidateID = 1,
        CandidateName = "One",
        RegisterNo = 1
    });
    tmp.Add(new Candidate()
    {
        CandidateID = 2,
        CandidateName = "Two",
        RegisterNo = 2
    });
    tmp.Add(new Candidate()
    {
        CandidateID = 3,
        CandidateName = "Three",
        RegisterNo = 3
    });
    dgCandidate.ItemsSource = tmp;

    foreach (Candidate candidate in tmp)
    {
        candidate.PropertyChanged += Candidate_PropertyChanged;
    }
}

private void Candidate_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    _handle = false;
    chkSelectAll.IsChecked = (dgCandidate.ItemsSource as IEnumerable<Candidate>)?
        .All(x => x.IsSelected) == true;
    _handle = true;
}

private bool _handle;
private void chkSelectAll_Checked(object sender, RoutedEventArgs e)
{
    if (_handle && dgCandidate.IsLoaded)
    {
        foreach (Candidate c in dgCandidate.ItemsSource)
        {
            c.IsSelected = true;
        }
    }
}

private void chkSelectAll_Unchecked(object sender, RoutedEventArgs e)
{
    if (_handle)
    {
        foreach (Candidate c in dgCandidate.ItemsSource)
        {
            c.IsSelected = false;
        }
    }
}

You probably also want to set the UpdateSourceTrigger of the binding to PropertyChanged for the source property to get set immediately:
<DataGridCheckBoxColumn Binding="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}">
    <DataGridCheckBoxColumn.Header>
        <CheckBox Name="chkSelectAll" Checked="chkSelectAll_Checked" Unchecked="chkSelectAll_Unchecked"></CheckBox>
    </DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>


text: Q: Почему при сохранении проекта в другом месте на компьютере, в IDE местоположение не меняется Почему при сохранении делфи проекта на рабочем столе, например, его местоположение в среде никак не меняется и все модули хранятся все в прежнем месте?


text:
Q: Is there a way to write on xml files with Xamarin.Forms? I am working on a simple app that has saving/retrieving object data functionality.
I did manage to get data from a pre-filled xml file and display it as list in the app (see the following code).
        var assembly = typeof(App).GetTypeInfo().Assembly;

        Stream stream = assembly.GetManifestResourceStream("Fetch.Pieces.xml");
             ObservableCollection<Piece> ListPieces;

             using (var reader = new System.IO.StreamReader(stream))
             {
                 var serializer = new XmlSerializer(typeof(ObservableCollection<Piece>));
                 ListPieces = (ObservableCollection<Piece>)serializer.Deserialize(reader);
             }

However, i can't seem to find some documentation for the writing process, is there a simple way to do it?


text: Q: How to open UDP port 7 or 9 for WOL on ubuntu? I have made all the necessary changes required for wakeonlan on my Ubuntu 14.04 LTS. Yet it does not seem to work. Also http://www.canyouseeme.org/ is showing that my UDP ports 7 or 9 are not open. I want to know how to open these ports.


text:
Q: UICollectionViewFlowLayout: collectionView!.contentSize vs collectionViewContentSize Update
The issue seems to be resolved when using the designated collectionViewContentSize() method like so:
let contentSize = collectionViewContentSize()

Nevertheless, I would be very interested in an explanation behind this behaviour, so I've updated my question accordingly.
Original Question
I am trying to recreate the steps found in the first example of this article, but using Swift and Storyboards.
I have a custom UICollectionViewFlowLayout subclass with the following content:
import UIKit
class SpringyFlowLayout: UICollectionViewFlowLayout {

    private lazy var animator: UIDynamicAnimator = {
        return UIDynamicAnimator(collectionViewLayout: self)
        }()

    override func prepareLayout() {
        super.prepareLayout()

        let contentSize = collectionView!.contentSize
        let items = super.layoutAttributesForElementsInRect(CGRect(origin: CGPointZero, size: contentSize)) as! [UICollectionViewLayoutAttributes]

        if animator.behaviors.isEmpty {
            for item in items {
                let spring = UIAttachmentBehavior(item: item, attachedToAnchor: item.center)
                spring.length = 0
                spring.damping = 0.8
                spring.frequency = 1.0
                animator.addBehavior(spring)
            }
        }
    }

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
        return animator.itemsInRect(rect)
    }

    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
        return animator.layoutAttributesForCellAtIndexPath(indexPath)
    }

    override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
        let delta = newBounds.origin.y - collectionView!.bounds.origin.y
        for spring in animator.behaviors {
            let items = spring.items as! [UICollectionViewLayoutAttributes]
            if let attributes = items.first {
                attributes.center.y += delta
                animator.updateItemUsingCurrentState(attributes)
            }
        }
        return false
    }

I have the correct Layout class set in Storyboards. When I run the app, my Collection View is empty.
I have determined that the issue is in the following snipped:
override func prepareLayout() {
        super.prepareLayout()

        let contentSize = collectionView!.contentSize
        let items = super.layoutAttributesForElementsInRect(CGRect(origin: CGPointZero, size: contentSize)) as! [UICollectionViewLayoutAttributes]
//...
}

Since I subclass UICollectionViewFlowLayout, I thought I can rely on the super implementation to lay out the elements for me, and then modify their attributes. But when I check contentSize, it reports the width correctly, but the height is 0.
This leads to an empty items array -> no behaviors in animator -> animator.itemsInRect(_) returning an empty array -> the empty Collection View.
I just can't seem to find out what I'm missing. There should be no need to override the  contentSize() method, since I'm using a flow layout.

A: The issue it that collectionView doesn't yet have a content size, because it just started to prepare it's layout. I don't believe that calling collectionView!.contentSize will actually compute the size. The reason collectionViewContentSize() works is because it will compute the size using your other layout code.

A: Here's something you might find interesting.  I noticed in Ash Furrow's example in viewDidAppear a call to collectionViewLayout.invalidateLayout.  Ash notes this isn't necessary when using storyboards due a difference in timing of the first invocation of prepareLayout versus when storyboards are not used.
I tried invalidating the collection view layout in viewDidAppear along with your code and a storyboard.  Here is what I found:
Test Scenarios:
1) collectionView!.contentSize without invalidateLayout = cv is EMPTY
2) collectionViewContentSize() without invalidateLayout = cv WORKS
3) collectionView!.contentSize with invalidateLayout = cv WORKS
4) collectionViewContentSize() with invalidateLayout = cv WORKS
FYI


text:
Q: ajax xmlhttp response is null - javascript Here is my code:

I get :Cannot call method 'getElementsByTagName' of null    for this line:
var response=xmlhttp.responseXML.getElementsByTagName("theComment")[0].text;
The servlet sent the response, because in the debugger it says that the repsonse was received, but anyway here's the code inside the servlet:
response.setContentType("text/xml");
        try {
            response.getWriter().println("<theComment>asasasaasa
</theComment>");
        } catch (IOException e) {

            e.printStackTrace();
        }

The browser is chrome. Can anyone tell me why xmlhttp.responseXML is nul??

A:
 is not valid in xml try <theComment>asasasaasa
</theComment> instead.


text:
Q: creating n amount of threads I have a java method, where I want to create n amount of threads, and then make each thread print out the numbers from 1 to 100.
public void createThreads(int n){
    for (int i = 0; i < n; i++) {
        new Thread(() -> {
            for (int j = 0; j < 100; j++) {
                System.out.println(j);

            }
        });
    }
}

Whenever I run this method, nothing is printed out, even when I pass a parameter. How can I fix this?

A: Nothing is printed because you are not starting the threads.
public void createThreads(int n){
    for (int i = 0; i < n; i++) {
        new Thread(() -> {
            for (int j = 1; j <= 100; j++) {
                System.out.println(j);
            }
        }).start(); // <-- .start() makes the thread start running
    }
}

Also note that I've changed your for loop to for (int j = 1; j <= 100; j++), because the intention is to print numbers from 1 to 100 (an not from 0 to 99).

A: Creating threads isn't enough, you need to start them as well.
new Thread(() -> { ... }).start();

I would recommend a bit of refactoring here.
From a method with the name createThreads I expect the created threads to be returned - Thread[] createThreads(int n) (1).
The code isn't easily readable - moving a Thread's Runnable into a separate method would make it clearer (2).
The name createThreads becomes inaccurate if you both create and start threads (3) within the method. Either rename it to createAndStartThreads or create two separate methods createThreads and startThreads which is more preferable since a method should take a single responsibility.
public Thread[] createThreads(int n) {
    final Thread[] threads = new Thread[n];

    for (int i = 0; i < n; ++i) {
        threads[i] = new Thread(this::doTask);
    }

    return threads;
}

private void doTask() {
    for (int j = 1; j <= 100; j++) {
        System.out.println(j);
    }
}

public void startThreads(Thread[] threads) {
    for (Thread thread : threads) {
        thread.start();
    }
}

A: This is what I have done to create N number of threads.
 Here mentioning quite different approach if you want to specify name of your
 thread.
1. Thread T[] = new Thread[list.size()];
2. for (int i = 0; i < list.size(); i++) {
3.     T[i] = new Thread(new constructor_name());
4.     T[i].setName(list.get(i));
5.     T[i].start();
6. }

Explanation:

*

*Create array of threads with your list size.

*Execute loop till last element of the list.

*Within loop Initiate, Assign and Start the thread.

Execution of threads:
public void run() {
    try {
         method_name(Thread.currentThread().getName());
    } catch (Exception ex) {
         System.out.println(ex.getMessage());
    }
 }

Note: Here method_name(thread_parameter) is invoked synchronously for every element of list.


text:
Q: Binding empty dictionary to a listbox When i try to bind a dictionary to a listbox I get an ArgumentException. Cannot bind to the new value member.
I use the following code.
Can any one tell me what is wrong. Because when i enter i row in the dictionary its working fine...
this.contactpersonenListBox = new Dictionary<int, string>();

lsContactpersonen.DataSource = new BindingSource(this.contactpersonenListBox, null);
lsContactpersonen.DisplayMember = "Value";
lsContactpersonen.ValueMember = "Key";

A: It doesn't make a ton of sense to bind an empty dictionary since the dictionary object doesn't report any changes, so adding an item to the dictionary after setting the data source won't show up in the ListBox.
But to get rid of the error, try setting it like this:
BindingSource b = new BindingSource();
b.DataSource = this.contactpersonenListBox;
lsContactpersonen.DisplayMember = "Value";
lsContactpersonen.ValueMember = "Key";
lsContactpersonen.DataSource = b;


text:
Q: Use xcodebuild (Xcode 8) and automatic signing in CI (Travis/Jenkins) environments With the release of Xcode 8, Apple introduced a new way of managing the signing configuration. Now you have two options Manual and Automatic.
According to the WWDC 2016 Session about Code signing (WWDC 2016 - 401 - What's new in Xcode app signing), when you select Automatic signing, Xcode is going to:

*

*Create signing certificates

*Create and update App IDs

*Create and update provisioning profiles

But according to what Apple says in that session, the Automatic Signing is going to use Development signing and will be limited to Xcode-created provisioning profiles.
The issue comes when you try to use Automatic Signing on a CI environment (like Travis CI or Jenkins). I'm not able to figure out an easy way to keep using Automatic and sign for Distribution (as Xcode forces you to use Development and Xcode-created provisioning profiles).
The new "Xcode-created provisioning profiles" do not show up in the developer portal, although I can find then in my machine... should I move those profiles to the CI machine, build for Development and export for Distribution? Is there a way to override the Automatic Signing using xcodebuild?

A: I basically run into the same issue using Jenkins CI and the Xcode Plugin.
I ended up doing the build and codesigning stuff myself using xcodebuild.
0. Prerequisites
In order to get the following steps done successfully, you need to have installed the necessary provisioning profiles and certificates. That means your code signing should already be working in general.
1. Building an .xcarchive
xcodebuild -project <path/to/project.xcproj> -scheme <scheme-name> -configuration <config-name> clean archive -archivePath <output-path> DEVELOPMENT_TEAM=<dev-team-id>

*

*DEVELOPMENT_TEAM: your 10 digit developer team id (something like A1B2C3D4E5)

2. Exporting to .ipa
xcodebuild -exportArchive -archivePath <path/to/your.xcarchive> -exportOptionsPlist <path/to/exportOptions.plist> -exportPath <output-path>

Example of an exportOptions.plist:
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>method</key>
    <string>development</string>
    <key>teamID</key>
    <string> A1B2C3D4E5 </string>
</dict>
</plist>

*

*method: is one of development, app-store, ad-hoc, enterprise

*teamID: your 10 digit developer team id (something like A1B2C3D4E5)

This process is anyway closer to what you would do with Xcode manually, than what for example the Jenkins Xcode Plugin does.
Note: The .xcarchive file will always be develpment signed, but selecting "app-store" as method in the 2nd step will do the correct distribution signing and also include the distribution profile as "embedded.mobileprovision".
Hope this helps.

A: After trying a few options, these are the solutions that I was able to use on my CI server:

*

*Include the Developer certificate and private key as well as the auto generated provisioning profiles in the CI environment:
Using Automatic signing forces you to use a Developer certificate and auto-generated provisioning profiles. One option is to export your development certificate and private key (Application -> Utilities -> Keychain Access) and the auto-generated provisioning profiles to the CI machine. A way to locate the auto-generated provisioning profiles is to navigate to ~/Library/MobileDevice/Provisioning\ Profiles/, move all files to a backup folder, open Xcode and archive the project. Xcode will create auto-generated development provisioning profiles and will copy them to the Provisioning Profiles folder.
xcodebuild archive ... will create a .xcarchive signed for Development. xcodebuild -exportArchive ... can then resign the build for Distribution

*

*Replace 'Automatic' with 'Manual' when building on a CI environment
Before calling xcodebuild a workaround is to replace all instances of ProvisioningStyle = Automatic with ProvisioningStyle = Manual in the project file. sed can be used for a simple find an replace in the pbxproj file:
sed -i '' 's/ProvisioningStyle = Automatic;/ProvisioningStyle = Manual;/' <ProjectName>.xcodeproj/project.pbxproj
@thelvis also created a Ruby script to do this using the xcodeproj gem. The script gives you a better control over what is changed.
xcodebuild will then use the code signing identity (CODE_SIGN_IDENTITY) set in the project, as well as the provisioning profiles (PROVISIONING_PROFILE_SPECIFIER). Those settings can also be provided as parameters to xcodebuild and they will override the code signing identity and/or provisioning profile set in the project.

EDIT: with Xcode 9, xcodebuild has a new build settings parameter CODE_SIGN_STYLE to select between Automatic and Manual so there's no need to find and replace instances of automatic with manual in the project file, more info in WWDC 2017 Session 403 What's New in Signing for Xcode and Xcode Server

*

*Switch to manual signing
Manual signing will provide total control over the code signing identities and provisioning profiles being used. It's probably the cleanest solution, but with the downside of losing all the benefits of Automatic signing.
To learn more about code signing with Xcode 8 I really recommend this article as well as the WWDC2016 session 401 - What's new in Xcode app signing

A: I'm considering another option I've not seen mentioned here yet.  Setup two identical targets, that only differ in their signing settings.

*

*Development Target uses automatic signing to get all of those benefits when new devices / developers are added

*CI Target uses manual signing

Downside is that you would have to manage two identical targets.  Upside is that get the benefits of automatic signing for development, and don't have to maintain potentially brittle scripts that modify your project just before build time.

A: If you are using Xcode 8.x and Jenkins for CI. Then probably you would face issue with "Signing for "YourProjectName" requires a development team. Select a development team in the project editor.
Code signing is required for product type 'Application' in SDK 'iOS 10.1'".** BUILD FAILED ** when running the job.
What is the solution?.
Solution is:

*

*set Provisioning profile  to  None in Xcode project build settings.

*In jenkins, Create a execute shell before the Xcode setting and write the below command
sed -i '' 's/ProvisioningStyle = Automatic;/ProvisioningStyle = Manual;/' ProjectName.xcodeproj/project.pbxproj

Remember: keep that execute shell before Xcode settings in Build section of jenkins.
This works.

A: There is one more way to workaround nonfunctional signing in CI/CD pipeline when the signing specified in the target (or project) fails.
We use automatic signing for our apps to have a good developer experience, and in CI/CD only signing is done in the last step when .ipa is produced.

*

*Produce an unsigned .xcarchive

xcodebuild -workspace Runner.workspace  CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO <more parameters follow>

*Sign the final .ipa file with configuration in exportOptions.plist

xcodebuild -exportArchive -archivePath <.xcarchive> -exportOptionsPlist <exportOptions.plist> -exportPath <output-path>

A: For me, nothing worked. I solved my problem by changing a file in Xcode app installed on your Mac Mini (CI server with Jenkins), as shown in this link:
https://www.jayway.com/2015/05/21/fixing-your-ios-build-scripts/
Additionally I turned off automatic signing from Xcode.
All done! Finally works!

A: I noticed my Unity build was never adding a ProvisioningStyle key to my XCode project. I then found a way to manually add the ProvisioningStyle by using a "PostProcessBuild" build script. i.e. a unit of code that is called after the IOS XCode project has been built by Unity.
First I had a look at what the project.pbxproj file should look like - when it is set to Manual Provisioning:
/* Begin PBXDictionary section */
    29B97313FDCFA39411CA2CEA /* Project object */ = {
        isa = PBXProject;
        attributes = {
            TargetAttributes = {
                1D6058900D05DD3D006BFB54 /* Unity-iPhone */ = {
                    ProvisioningStyle = Manual;
                };
                5623C57217FDCB0800090B9E /* Unity-iPhone Tests */ = {
                    TestTargetID = 1D6058900D05DD3D006BFB54 /* Unity-iPhone     */;
                };
            };
        };

Then I created my code to replicate the "structure" of the file seen above. (using the XCodeEditor project found here: XCodeEditor)
[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget target, string path)
{
    // Create a new project object from build target
    XCProject project = new XCProject(path);

    if (target == BuildTarget.iOS)
    {
        //Add Manual ProvisioningStyle - this is to force manual signing of the XCode project
        bool provisioningSuccess = AddProvisioningStyle(project, "Manual");

        if (provisioningSuccess)
            project.Save();
    }
}

private static bool AddProvisioningStyle(XCProject project, string style)
{
    var pbxProject = project.project;

    var attr = pbxProject.data["attributes"] as PBXDictionary;
    var targetAttributes = attr["TargetAttributes"] as PBXDictionary;

    var testTargetIDGuid = FindValue(targetAttributes, "TestTargetID");

    if (!string.IsNullOrEmpty(testTargetIDGuid))
    {
        var settings = new PBXDictionary();
        //here we set the ProvisioningStyle value
        settings.Add("ProvisioningStyle", style);

        targetAttributes.Add(testTargetIDGuid, settings);

        var masterTest = FindValue(targetAttributes, "ProvisioningStyle");

        if (masterTest == style)
        {
            return true;
        }
    }

    return false;
}

private static string FindValue(PBXDictionary targetAttributes, string key)
{
    foreach (var item in targetAttributes)
    {
        var ma = item.Value as PBXDictionary;

        foreach (var di in ma)
        {
            var lookKey = di.Key;

            if (lookKey == key)
            {
                return di.Value.ToString();
            }
        }
    }

    return "";
}

A: What fixed it for me was this: http://code-dojo.blogspot.jp/2012/09/fix-ios-code-signing-issue-when-using.html
... copying certificates from Login keychain to System keychain.
You might also want to set all dev certificates to 'Allow all applications to access this item' (Right-click/Get Info/Access Control).

A: There is a tool called fastlane which makes using xcodebuild much easier and it is maintained meaning new updates will continue to provide support for changes to xcode. It makes it much easier to create scripts and config for building and codesigning your app among many other xcode automation tools it supports. I'd recommend giving it a look into.


text:
Q: javascript stop twitter bootstrap tab link from activating I'm using TB 3 in my app. I'm using some nav tabs and I want to by default disable a few as follows (this is not part of a drop-down menu):

Tab

My disable function:
$('.nav li.disabled').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
});

The goal is to remove .disabled when a condition is met so the link is re-enabled or clickable again. This changes the appearance of the tab only, not the functionality. Further tests show shown.bs.tab is still fired no matter what I do here.

A: Apparently, bootstrap doesn't "like" changing active tabs.
Here's the working jsFiddle (Bootstrap 3.0).
And the working jsFiddle (Bootstrap 2.3.2).
Here's the idea:
$(document).ready(function() {

  $('#store-tab').attr('class', 'disabled');
  $('#bank-tab').attr('class', 'disabled active');

  $('#store-tab').click(function(event) {
    if ($(this).hasClass('disabled')) {
      return false;
    }
  });
  $('#bank-tab').click(function(event) {
    if ($(this).hasClass('disabled')) {
      return false;
    }
  });

  $('.selectKid').click(function(event) {
    $('li').removeAttr("disabled");
    $('#bank-tab').attr('class', 'active');
    $('#store-tab').attr('class', '');
  });
});

Courtesy of.


text:
Q: Firefox Browser in private mode not working - Selenium C# I'm currently using selenium 3.8 with C#. I tried 2 script's segments below but it's not working.
[-----1----]
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.SetPreference("browser.private.browsing.autostart", true);
FirefoxOptions options = new FirefoxOptions();
options.Profile = firefoxProfile;
IWebDriver webDriver = new FirefoxDriver(driverService, options, TimeSpan.FromMinutes(1));

[-----2----]
FirefoxOptions options = new FirefoxOptions();
options.AddArgument("--private");
IWebDriver webDriver = new FirefoxDriver(options);

Please help me find a solution?

A: go to browser setting - advanced- and clear browsing data .
and open a new incognito mode window then open you

A: Use a single dash.
options.AddArgument("-private");


text:
Q: I am trying to use php function transliterator_transliterate but get an error when I call it Trying to use this function in php7 and in Laravel framework
transliterator_transliterate('Any-Latin; Latin-ASCII; [\u0080-\uffff] remove', $str);
Call to undefined function App\Http\Controllers\Backend\Core\Blog\transliterator_transliterate()
http://php.net/manual/en/transliterator.transliterate.php
It's supposed to be available on (PHP >= 5.4.0, PECL intl >= 2.0.0)
Do I need some extension for this function?

A: First of all make sure package php-intl is installed:
sudo apt install php-intl
sudo service php7.4-fpm restart

otherwise when you try to run the transliterator_transliterate() you get error Call to undefined function.
Source


text:
Q: Joining a POSIXct column to Date column using data.table in R In the following example, can someone explain to me why the date 2015-03-31 changed to 1034-04-03?
dt1 = data.table(id = c(1,2), date = as.POSIXct("2015-03-31 BST"), key = "id")
dt1
#    id       date
# 1:  1 2015-03-31
# 2:  2 2015-03-31
dt2 = data.table(id = c(1,2), date = as.Date(NA), key = "id")
dt2
#    id date
# 1:  1 <NA>
# 2:  2 <NA>
dt2[dt1, date := i.date]
dt2
#    id       date
# 1:  1 1034-04-03
# 2:  2 1034-04-03

My aim is to get date from dt1 to dt2 in Date format instead of POSIXct by id (different id would have different date). How would I do that?
Following is what I want:
dt2
#    id       date
# 1:  1 2015-03-31
# 2:  2 2015-03-31

EDIT:
I've tried the following:
dt2[dt1, date := as.Date(i.date)]
dt2
#    id       date
# 1:  1 2015-03-30
# 2:  2 2015-03-30

Unfortunately, it is giving me 2015-03-30 instead of 2015-03-31...??? How to get 2015-03-31 instead?

A: You can use
dt2[dt1, date:=as.Date(i.date)]

You might want to also see the question Convert column classes in data.table about changing data types in data.tables.


text:
Q: After explode function cannot insert all rows to mysql I have three tables:
users:
user_id (int, auto increment, primary key)
username (varchar (100))
(the rest is not immportant)

teams:
team_id(int, auto increment, primary key)
teamname (varchar (100))
(the rest is not important)

team_users:
team_id int,
user_id int,
primary key (team_id, user_id),
foreign key (team_id) references teams (team_id),
foreign key (user_id) references users (user_id)

I have a form in which a user can create a team and can also add member names, which are going to be comma separated values.
What I would like is to insert the team details into the team table and the member names,  after using explode and finding their matching user_ids in users table, insert into team_users together with the last created team id.
What I have so far is this:
<?php
session_start();
$conn = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');

if (!$conn) {
    die("connection failed: ".mysqli_connect_error());
}

$teamname = $_POST['teamname'];
$members = $_POST['members'];
$games = $_POST['games'];
$image = $_POST['image'];

$sql = mysqli_query($conn,"INSERT INTO teams (teamname, games, images, founded) VALUES ('$teamname', '$games', '$image', NOW())");
$id = mysqli_insert_id($conn);

if(!empty($id)) {
    $membernames = explode(',', $members);
    foreach($membernames as $value) {

        $sql = mysqli_query($conn,"insert into team_users (team_id, user_id)
        select teams.team_id, users.user_id
        from teams, users where users.username = '$value' and teams.team_id = '$id'");

    }

    if(false === $sql) die(mysqli_error($conn));
}
?>

My problem is that when I execute this, it inserts only one, the first added user's id into team_users, however a user can add more than one users to be a member of a team. Why am I doing wrong?
I've created a username column in team_users table and instead deleted user_id and changed the query (insert into team_users (team_id, username) values ('$id', '$value') to see if it would insert all member names and it does. But I don't need their usernames in team_users table, I'd need their user_id.
I'm very new to PHP and Mysql and I've read a lot of forums and similar questions but couldn't find the answer. I'm stucked on this since days, can someone please help? Thank you so mucH!

A: Try adding this as the first line inside your foreach loop.
$value = trim($value);
This is because, when you explode the comma separated string, there is high chance that white spaces may get added to it.
For e.g. When we write a comma separated string "Adam, Eve, William", notice the space after each comma. So when you explode with comma, the array will have Adam, <space>Eve, <space>William
So in your query only Adam works since Eve and William has a blank space added at the beginning.
When you trim, the spaces are removed. Hope this explains.


text:
Q: vue-bootstrap4-table - how to modify filtering query params? I use https://www.npmjs.com/package/vue-bootstrap4-table#8-filtering with django-rest-framework.
The problem is that this component uses totally different query params for sorting, filtering, etc.
vue-bootstrap4-table
http://127.0.0.1:8000/api/products/?queryParams=%7B%22sort%22:[],%22filters%22:[%7B%22type%22:%22simple%22,%22name%22:%22code%22,%22text%22:%22xxx%22%7D],%22global_search%22:%22%22,%22per_page%22:10,%22page%22:1%7D&page=1

"filters":[{"type":"simple","name":"code","text":"xxx"}],

but Django-rest-framework needs this format:
../?code__icontains=...

Do you know how to make vue-bootrstrap4-table to generate this format?
My app:
new Vue({
            el: '#app',
            data: {
                product_list_url: "{% url "api:product-list" %}",
                rows: [],
                total_rows:0,
                queryParams: {
                    sort: [],
                    filters: "",
                    global_search: "",
                    per_page: 10,
                    page: 1,
                },
                columns: [{
                    label: "Kód",
                    name: "code",
                    filter: {
                        type: "simple",
                        placeholder: "code"
                    },
                    sort: true,
                },
                    {
                        label: "Názov",
                        name: "name",
                        filter: {
                            type: "simple",
                            placeholder: "Enter name"
                        },
                        sort: true,
                    },
                ],
                config: {
                    checkbox_rows: true,
                    rows_selectable: true,
                    {#card_title: "Vue Bootsrap 4 advanced table",#}
                    server_mode: true,
                }
            },
            mounted() {
                this.fetchData();
            },
            methods: {
                onChangeQuery(queryParams) {
                    this.queryParams = queryParams;
                    this.fetchData();
                },
                fetchData() {
                    let self = this;
                    axios.get(self.product_list_url, {
                        params: {
                            "queryParams": this.queryParams,
                            "page": this.queryParams.page
                        }
                    })
                        .then(function (response) {
                            self.rows = response.data.results;
                            self.total_rows = response.data.count;
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                }

            },
        })


text:
Q: Magento 2 how to get order information using soap api I want to get order information using soap API
    $wsdlUrl = 'http://website.com/soap/default?wsdl=1&services=salesOrderRepositoryV1';
$serviceArgs = array('searchCriteria' =>
    array('filterGroups' =>
        array('filters' =>
            array('field' => 'increment_id',
                'value' => '000000002',
                'condition_type' => 'eq')
        )
    ));

$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, ['version' => SOAP_1_2, 'stream_context' => $context]);

$soapResponse =  $soapClient->__call('salesOrderRepositoryV1GetList', $serviceArgs);

if anyone knows about that then please let me know how to get the information?

A: Try the following code. Just add your url, and api username and password.
    <?php

    $proxy = new SoapClient('http://www.example.com/api/v2_soap/?wsdl');

     $session = $proxy->login('user', 'password');

     $result = $proxy->salesOrderInfo($session, '100000064');

     var_dump($result);


text:
Q: Type error using ArrayList? package mp1similar;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import EarthquakeRecord.Earthquakerecd;

public class MP1Similar
{

private static ArrayList arrayList  ;

public static void main(String[] args)
{
 ArrayList arrayList= null;
    try
    {
    BufferedReader br = new BufferedReader(new FileReader("data/Catalog.txt"));

    String line="";
    arrayList =new ArrayList();
    while((line = br.readLine())!=null)
        {
      //  System.out.println(line);
        StringTokenizer st = new StringTokenizer(line);
        while(st.hasMoreTokens())
            {
          //System.out.println(st.nextToken());
            arrayList.add(st.nextToken());
            //System.out.println(br.readLine());
            }
        }
    }

    catch (FileNotFoundException ex)
    {
         System.out.println(ex.getMessage());
         ex.printStackTrace();
    }
catch (IOException ex)
    {
          System.out.println(ex.getMessage());
          ex.printStackTrace();
    }
          int j=0;
    Earthquakerecd E[]= new Earthquakerecd[2000];
     for(int i=0;i< arrayList.size();i++)
    {
        System.out.println(arrayList.get(i));
        E[j] = new Earthquakerecd();

       E[j].setDate(arrayList.get(i));

    if (j>35 )
    {
        j=0;
    }
    j++;

    }

}

}

I am getting an error in the line E[j].setDate(arrayList.get(i)); It says that the actual argument cannot be converted to java.lang.String by method invocation.
All the fields in the object are String Types. The arrayList contains all the data extracted from the TXT file. I am trying to transfer all the data from the arrayList to the object array. The txt file has 35 columns and 1500 rows. The data being seperated by whitespace

A: Change:
ArrayList arrayList = null;
...
arrayList =new ArrayList();

to:
ArrayList<String> arrayList = null;
arrayList = new ArrayList<String>();

or just:
ArrayList<String> arrayList = new ArrayList<String>();

A: A List contains Object instances. The get() method returns Object. If you want a typesafe List, you must use the generic type information:
List<String> list = new ArrayList<String>();

If you use the raw type (without the <String> generic type information), then the compiler doesn't know that the List only contains String instances, and you thus have to cast the result:
String s = (String) list.get(i);

Side note: learn to indent your code and to respect Java naming conventions. It's unreadable as is.

A: I think the problem is that you're using the raw ArrayList type rather than using a parameterized ArrayList.  Consequently, all operations on the ArrayList will assume that the parameter and returns types are Object rather than String, since you haven't indicated to Java that you want the ArrayList to hold Strings.  Without this extra information from you, Java can't know that the objects stored within are exclusively Strings and not, say, Integers, other ArrayLists, JPanels, etc.
To fix this, change the line
private static ArrayList arrayList;

to read
private static ArrayList<String> arrayList;

This explicitly indicates to Java that your ArrayList should only hold Strings, so it can know that the return type of arrayList.get(i) is going to be a String rather than the catch-all Object.  Similarly, change
arrayList = new ArrayList();

to
arrayList = new ArrayList<String>();

For more information, read up on Java Generics.  They're a very powerful tool, but can easily be used improperly (as in your case).  One nice source is this article by Oracle.
Hope this helps!

A: ArrayList<String> arrayList= null;

ArrayList get call returns an Object unless you specify the type.

A: Diamond was added in Java 7 :
ArrayList<String> arrayList = new ArrayList<>();


text:
Q: How to aggregate bower assets by their absolute path in Mean IO Project is based on Mean IO stack. Installing bower dependencies installs them to /bower_components, how can I access those when aggregating assets? I know I can specify location where files should be installed to, but I need that folder to be accessible from every package.
Currently working solution is, which looks a bit odd to me:
Package.aggregateAsset('js', '../../../../../../bower_components/dep/file.js');

And another question, if I have to pages in package, and I want them to use different assets, what would be the best way to do it?

A: Package.aggregateAsset('js', '../../../../../../bower_components/dep/file.js', {global: true});

A: At the root of your theme's package, create a .bowerrc file with the following content:
{
  "directory": "public/assets/lib"
}

Bower will now install the libs in packages/custom/yourThemePackage/public/assets/lib and you can now aggregate your files from yourThemePackage/app.js like this:
YourThemePackage.aggregateAsset('css', '../lib/someLib/css/someStyle.min.css');
YourThemePackage.aggregateAsset('js', '../lib/someLib/js/someScript.min.js');


text:
Q: VB connection build and run on IIS express and local IIS compile , then run VB code in visual studio result in below error , compile is an IIS

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false"

A: There are many reasons for this error, you can try the following methods to solve the problem.

*

*in the search box, enter "Turn windows features on or off"

*in the features window, look for "Internet Information Services"

*Click: "World Wide Web Services"

*Click: "Application Development Features"

*Check (enable) the features. I checked all but CGI
If this method does not work, you can still try this:

*

*Open IIS Manager

*Click the server name in the tree on the left

*Right hand pane, Management section, double click Configuration Editor

*At the top, choose the section system.webServer/security/authentication/anonymousAuthentication

*Right hand pane, click Unlock Section

*At the top, choose the section system.webServer/security/authentication/windowsAuthentication

*Right hand pane, click Unlock Section


text:
Q: Rails validate_existence_of plugin I'm reading the book Learning Rails by O'Reilly and it recommends using the validate_existence_of plugin. When I run:
ruby script/plugin install http: //svn.hasmanythrough.com/public/plugins/validates_existence/
it says it's already installed, but when I use it, I get a message saying:
NoMethodError in AwardsController#index
undefined method `validates_existence_of' for #<Class:0xb5fde868>

When I say:
class Award < ActiveRecord::Base
  belongs_to :student
  validates_existence_of :student
end

Any ideas?

A: Have you checked that the plugin code is installed in the vendor/plugins directory ?
Also you may need to check that the environment.rb file has the config.gem section uncommented.


text:
Q: Magento 2 - API to sendAccountNewEmail I created an customer account using /V1/customers but it does not send the new account  email.
Is there any API to do so?

A:
Is there any API to do so?

/V1/customers or createAccount itself has email sending functionality, make sure double check your email configurations with proper mail id.
/V1/customers or createAccount email sending work flow will work as described.
<route url="/V1/customers" method="POST">
        <service class="Magento\Customer\Api\AccountManagementInterface" method="createAccount"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

\vendor\magento\module-customer\Model\AccountManagement.php

createAccount -> createAccountWithPasswordHash ->
  $this->sendEmailConfirmation($customer, $redirectUrl);

protected function sendEmailConfirmation(CustomerInterface $customer, $redirectUrl)
{
    try {
        $hash = $this->customerRegistry->retrieveSecureData($customer->getId())->getPasswordHash();
        $templateType = self::NEW_ACCOUNT_EMAIL_REGISTERED;
        if ($this->isConfirmationRequired($customer) && $hash != '') {
            $templateType = self::NEW_ACCOUNT_EMAIL_CONFIRMATION;
        } elseif ($hash == '') {
            $templateType = self::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD;
        }
        $this->getEmailNotification()->newAccount($customer, $templateType, $redirectUrl, $customer->getStoreId());
    } catch (MailException $e) {
        // If we are not able to send a new account email, this should be ignored
        $this->logger->critical($e);
    }
}


text:
Q: When to use T/N distribution? I have given 16 random heights of random people which I know is normally distributed with unknown mean and variance.
I have to decide whether or not to accept the null hypothesis when the significance level $\alpha = 0.1$. According to my book we accept $H_0$ if $|W| = |\frac{\bar{X}-\mu_0}{S\sqrt{n}}| \leq t_{\alpha/2,n-1}$.
However, according to my professor's calculations, he has used $qt(1-\alpha/2,n-1)$, commando in R, to calculate $t_{\alpha/2,n-1}$. Why can't I use qnorm as this is normally distributed?
I also had to calculate the confidence interval where my book also says to use $t_{\alpha/2,n-1}$ but if I use this commando and not qnorm in R I get the wrong result ..
Are you able to explain why I have to use qnorm in the confidence interval and qt in the acceptance range? I literally have no idea ..
The only thing I know is that when the amount of observations is considered large we can always use qnorm in R.
Thanks.

A: The statistic $W:=\frac{\bar X-\mu_0}{S/\sqrt n}$ is used when the population variance $\sigma^2$ is not known. It has a $t$ distribution with $n-1$ degrees of freedom, not a normal distribution. (This is a fact you should have covered in lecture.) And for confidence intervals you should continue to use critical values from the $t(n-1)$ distribution, and not switch to the normal distribution.
OTOH, if the variance $\sigma^2$ is known, then the statistic $Z:=\frac{\bar X-\mu_0}{\sigma/\sqrt n}$ has normal distribution because we get to replace $S$ with the known $\sigma$. The normal approximation justifies using $Z$ in place of $W$ when $n$ is large.


text:
Q: Why do we divide by the standard deviation and not some other standardizing factor before doing PCA? I was reading the following justification (from cs229 course notes) on why we divide the raw data by its standard deviate:

even though I understand what the explanation is saying, it is not clear to me why dividing by the standard deviation would achieve such a goal. It says so that everyone is more on the same "scale". However, its not entirely clear why dividing by the standard deviation achieves that. Like, whats wrong with dividing by the variance? Why not some other quantity? Like...the sum of absolute values? or some other norm... Is there a mathematical justification for choose the STD?
Are the claims in this extract a theoretical statement that can be derived/proved through mathematics (and/or statistics) or is it more one of those statement that we do because it seems to work in "practice"?
Basically, can one provide either a rigorous mathematical explanation of why that intuition is true? Or if its just an empirical observation, why we think that works in general before doing PCA?
Also, in the context of PCA, is this the process of standardizing or normalizing?

Some other thoughts I had that might "explain" why the STD:
Since PCA can be derived from maximizing the variance, I guessed that dividing by a related quantity such as the STD, might be one of the reasons we divided by the STD. But then I considered that maybe if we defined maybe a "variance" with any other norm, $\frac{1}{n} \sum^{n}_{i=1} (x_i -\mu)^p$, then we would divide by the STD of that norm (by taking the pth root or something). Though, it was just a guess and I am not 100% about this, hence the question. I was wondering if anyone knew anything related to this.

I did see that there was maybe a related question:
PCA on correlation or covariance?
but it seemed talk more about when to use "correlation" or "covariance" but lacked rigorous or convincing or detailed justifications, which is what I am mainly interested in.
Same for:
Why do we need to normalize data before analysis
related:
"Normalizing" variables for SVD / PCA

A:
Why do we divide by the standard deviation
  whats wrong with dividing by the variance?

as @Silverfish already pointed out in a comment, the standard deviation has the same unit as the measurements. Thus, dividing by standard deviation as opposed to variance, you end up with a plain number that tells you where your case is relative to average and spread as measured by mean and standard deviation.
This is very close to the idea of $z$-values and the standard normal distribution: If the data are normally distributed, standardization will transform them to a standard normal distribution.
So: standardization (mean centering + scaling by standard deviation) makes sense if you consider the standard normal distribution  sensible for your data.

Why not some other quantity? Like...the sum of absolute values? or some other norm...

Other quantities are used to scale data, but the procedure is called standardization only if it uses mean centering and dividing by standard deviation. Scaling is the generic term.
E.g. I work with spectroscopic data and know that my detector has a wavelength-dependent sensitivity and an (electronic) bias. Thus I calibrate by subtracting the offset (blank) signal and multiplying (dividing) by a calibration factor.
Also, I may be centering not to the mean but instead to some other baseline value, such as the mean of a control group instead of the grand mean.  (Personally, I almost never standardize as my variates already have the same physical unit and are in the same order of magnitude)
See also: Variables are often adjusted (e.g. standardised) before making a model - when is this a good idea, and when is it a bad one?

A: This is in partial answer to "it is not clear to me why dividing by the standard deviation would achieve such a goal". In particular, why it puts the transformed (standardized) data on the "same scale". The question hints at deeper issues (what else might have "worked", which is linked to what "worked" might even mean, mathematically?), but it seemed sensible to at least address the more straightforward aspects of why this procedure "works" - that is, achieves the claims made for it in the text.
The entry on row $i$ and column $j$ of a covariance matrix is the covariance between the $i^{th}$ and $j^{th}$ variables. Note that on a diagonal, row $i$ and column $i$, this becomes the covariance between the $i^{th}$ variable and itself - which is just the variance of the $i^{th}$ variable.
Let's call the $i^{th}$ variable $X_i$ and the $j^{th}$ variable $X_j$; I'll assume these are already centered so that they have mean zero. Recall that $$Cov(X_i, X_j) =\sigma_{X_i} \, \sigma_{X_j} \, Cor(X_i, X_j)$$
We can standardize the variables so that they have variance one, simply by dividing by their standard deviations. When standardizing we would generally subtract the mean first, but I already assumed they are centered so we can skip that step. Let $Z_i = \frac{X_i}{\sigma_{X_i}}$ and to see why the variance is one, note that
$$Var(Z_i) = Var\left(\frac{X_i}{\sigma_{X_i}}\right) = \frac{1}{\sigma_{X_i}^2}Var(X_i) = \frac{1}{\sigma_{X_i}^2} \sigma_{X_i}^2 = 1$$
Similarly for $Z_j$. If we take the entry in row $i$ and column $j$ of the covariance matrix for the standardized variables, note that since they are standardized:
$$Cov(Z_i, Z_j) =\sigma_{Z_i} \, \sigma_{Z_j} \, Cor(Z_i, Z_j) = Cor(Z_i, Z_j)$$
Moreover when we rescale variables in this way, addition (equivalently: subtraction) does not change the correlation, while multiplication (equivalently: division) will simply reverse the sign of the correlation if the factor (divisor) is negative. In other words correlation is unchanged by translations or scaling but is reversed by reflection. (Here's a derivation of those correlation properties, as part of an otherwise unrelated answer.) Since we divided by standard deviations, which are positive, we see that $Cor(Z_i, Z_j)$ must equal $Cor(X_i, X_j)$ i.e. the correlation between the original data.
Along the diagonal of the new covariance matrix, note that we get $Cov(Z_i, Z_i) = Var(Z_i) = 1$ so the entire diagonal is filled with ones, as we would expect. It's in this sense that the data are now "on the same scale" - their marginal distributions should look very similar, at least if they were roughly normally distributed to start with, with mean zero and with variance (and standard deviation) one. It is no longer the case that one variable's variability swamps the others. You could have divided by a different measure of spread, of course. The variance would have been a particularly bad choice due to dimensional inconsistency (think about what would have happened if you'd changed the units one of your variables was in, e.g. from metres to kilometres). Something like median absolute deviation (or an appropriate multiple of the MAD if you are trying to use it as a kind of robust estimator of the standard deviation) may have been more appropriate. But it still won't turn that diagonal into a diagonal of ones.
The upshot is that a method that works on the covariance matrix of standardized data, is essentially using the correlation matrix of the original data. For which you'd prefer to use on PCA, see PCA on correlation or covariance?

A: This link answers your question clearly, I guess: http://sebastianraschka.com/Articles/2014_about_feature_scaling.html
I quote a small piece:

Z-score standardization or Min-Max scaling?
"Standardization or Min-Max scaling?" - There is no obvious answer to this question: it really depends on the application.
For example, in clustering analyses, standardization may be especially crucial in order to compare similarities between features based on certain distance measures. Another prominent example is the Principal Component Analysis, where we usually prefer standardization over Min-Max scaling, since we are interested in the components that maximize the variance (depending on the question and if the PCA computes the components via the correlation matrix instead of the covariance matrix; but more about PCA in my previous article).
However, this doesn't mean that Min-Max scaling is not useful at all! A popular application is image processing, where pixel intensities have to be normalized to fit within a certain range (i.e., 0 to 255 for the RGB color range). Also, typical neural network algorithm require data that on a 0-1 scale.


text:
Q: Crop the Image as a square in windows phone 7 for jigsaw Puzzle Game Please Help me, I want to Crop the Image as a Square by Square for Jigsaw Puzzle Game App. How Should I do That in Windows Phone 7

A: You should use photoshop instead or anyother image editing software.