text:
Q: Object not updating when performing the switch statement in java Not sure what I'm doing wrong here. But I want to change the card to the correct format.
For example given the card 1c change it to AC.
Here's some code I've been playing with:
public static void main(String[] args) {

    String[] cards = {"1c", "13s"};

    for (String card : cards) {

        switch (card.toUpperCase()) {
            case "1C":
                card = card.toUpperCase().replace("1C", "AC");
                break;
            case "13S":
                card = card.toUpperCase().replace("13S", "KS");
                break;
            default:
                System.out.println(Arrays.toString(cards));
        }
    }
    System.out.println(Arrays.toString(cards));

}

Any help would be great cheers.

A: Within the loop, card is just a local variable, and reassigning it doesn't modify the array cards. An immediate fix would be to index over the array so you can reference each element directly:
for (int i = 0; i < cards.length; i++) {
    switch (cards[i].toUpperCase()) {
        case "1C":
            cards[i] = cards[i].toUpperCase().replace("1C", "AC");
            break;
        case "13S":
            cards[i] = cards[i].toUpperCase().replace("13S", "KS");
            break;
        default:
            System.out.println(Arrays.toString(cards));
    }
}

Edit: to answer edhedges' comment, one would need to keep a counter variable outside the loop in order to keep using the enhanced-for syntax:
int i = 0;
for (String card : cards) {
    switch (card.toUpperCase()) {
        case "1C":
            cards[i] = card.toUpperCase().replace("1C", "AC");
            break;
        case "13S":
            cards[i] = card.toUpperCase().replace("13S", "KS");
            break;
        default:
            System.out.println(Arrays.toString(cards));
    }
    i++;
}

A: Are you using Java 7? If you are not, you can't use Strings in cases.
See this problem and here(scroll down to Using Strings in switch Statements)

A: You can do this by the following code
public static void main(String[] args) {

    String[] cards = {"1c", "13s"};

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

        switch (card[i].toUpperCase()) {
            case "1C":
                cards[i] = cards[i].toUpperCase().replace("1C", "AC");
                break;
            case "13S":
                cards[i] = cards[i].toUpperCase().replace("13S", "KS");
                break;
            default:
                System.out.println(Arrays.toString(cards));
        }
    }
    System.out.println(Arrays.toString(cards));

}

A: In addition to @Paul Borella's answer I would say that this is only possible with Java 7. As Switch statement does not allow String as an expression. So you should get compilation error at line
switch(card.toUpperCase())

If you want to acheive the same functionality then you can go for Enum.
public enum Cards {
 1C, 13S;

   public String replacedString(){
     case 1C : return "AC";
               break;

     case 13S : return "KS";
                break;

     default : return "";
   }
}


text:
Q: Dynamics of electrons on a sphere Suppose one place $n$ electrons closely surrounding the north pole of a sphere, forming
a perfect planar regular $n$-gon:

Q1.
  What will happen if the electrons repel one another via Coulomb's law, but are
  confined to the surface?
  Will they maintain a planar regular $n$-gon configuration?
  With damping will they settle on the equator?

I believe the answer to the latter two questions is Yes, but I did not attempt
a formal proof. Here is my primary interest:

Q2.
  Suppose small random errors are introduced so that the initial configuration
  is not an exact planar regular $n$-gon.
  Will the electrons on average head toward the expected minimum energy configuration?

For $n{=}7$ illustrated above, that min configuration is conjectured to be an equatorial
regular pentagon with electrons occupying the two poles.
Perhaps especially with larger $n$,
there are many local minima rendering it unlikely to settle in the min-energy configuration?

redpajama_set_name: RedPajamaStackExchange


text:
Q: add local users to GPP managed groups I (hopefully:) understand the usage of GPP management of restricted groups. I do it with Item-Level targetting but have one problem which I have no clue why it is not working.
When using Local Group Member dialog box I can link any domain user I want. Also, pressing F3 shows a list of possible variables, using which I want to point to local user on the server to be included in local Administrators group.
Tried %computername%\%username% and %computername%\%SID of user% - also starting with %domainname% - but with no effect.
Is there something I am doing wrong?
Local Group Member dialog box


text:
Q: Why gcc duplicates rodata string for memcpy? How to avoid it? For some reason, GCC duplicates content of const char string into separate rodata area, which I don't understand.
I compile provided code:
static const char pattern[] = "[SOME TEST PATTERN TO CALCULATE SUM FROM] ";

static char tmpbuf[sizeof(pattern) + 1];

uint16_t sum(char *buf, int size)
{
    uint16_t ret = 0;

    for(int i = 0; i < size; ++i)
        ret += buf[i];

    return ret;
}

void getPattern(char **retbuf)
{
    memcpy(tmpbuf, pattern, sizeof(tmpbuf) -1);
    *retbuf = tmpbuf;
}

int main(int argc, char *argv[])
{
    getPattern(&argv[0]);

    return sum((char *)pattern, sizeof(pattern) - 2) > 0;
}

void _exit(int status)
{
    while(1)
    {
        asm("nop");
    }
}

with arm gcc compiler, using command:
arm-none-eabi-gcc -Os dbstr.c -o dbstr -Wl,-Map,"dbstr.map" -fdata-sections

In resulting binary, even if it is stripped, I find string:
"[SOME TEST PATTERN TO CALCULATE SUM FROM] "

duplicated.
Looking into symbol map, i find:
.rodata.pattern
                0x000087d8       0x2b ... ccumYoyx.o
.rodata.str1.1
                0x00008803       0x2b ... ccumYoyx.o
and
.bss.tmpbuf    0x00018ca0       0x2c ... ccumYoyx.o

symbol "pattern" is original array
symbol "str1" is duplicate
and symbol "tmpbuf" is target buffer, into which I want to copy "pattern".
Looking into generated assembly, I found that memcpy uses duplicate created by compiler:
getPattern:
    @ Function supports interworking.
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 0, uses_anonymous_args = 0
->  ldr r3, .L6
    push    {r4, lr}
    mov r2, #43
    mov r4, r0
    ldr r1, .L6+4
    mov r0, r3
    bl  memcpy
...

.L6:
    .word   .LANCHOR0
->  .word   .LC0
...
pattern:
    .ascii  "[SOME TEST PATTERN TO CALCULATE SUM FROM] \000"
    .section    .rodata.str1.1,"aMS",%progbits,1
.LC0: /*duplicate string*/
    .ascii  "[SOME TEST PATTERN TO CALCULATE SUM FROM] \000"
    .ident  "GCC: (GNU Tools for Arm Embedded Processors 8-2018-q4-major) 8.2.1 20181213 (release) [gcc-8-branch revision 267074]"

I checked that it happens with arm-none-eabi-gcc versions from 6-2017-q1-update to 8-2018-q4-major (latest available on developer.arm.com).
I also tried using various optimizations. Duplicate does not occur only when using -O0. For others it does.
In bigger application, that this problem occured, it turned out that memcpy copied duplicate string instead of original - it was determined by substitution of original string in binary. I need memcpy to use original string.

A: The behavior you observe is specified explicitly by the standard.  In

static const char pattern[] = "[SOME TEST PATTERN TO CALCULATE SUM FROM] ";

you have a declaration of variable pattern and an initializer in the form of a string literal.  Paragraph 6.4.5/6 of the standard specifies that

In translation phase 7, a byte or code of value zero is appended to
  each multibyte character sequence that results from a string literal
  or literals. The multibyte character sequence is then used to
  initialize an array of static storage duration and length just
  sufficient to contain the sequence.

(Emphasis added.) That the resulting array has static storage duration means that, at least in principle, memory must be reserved for it in the program.  This is what you are seeing in the form of str1.1.  But you are also using that string to initialize an array, so that array gets the same character sequence, and that also occupies memory in the binary because it, too, has static storage duration as a result of being declared at file scope.
In principle, GCC ought to be able to optimize away the extra array.  In particular, option -fmerge-constants should do this, but this is included at all optimization levels other than -O0, so it's surprising that you're not seeing such merging, but it's possible that the merging will be performed at link time, so that what you're seeing is a meaningless artifact of looking at the object file before linking.
You should also be able to avoid the copy by declaring pattern as a pointer instead of an array:
static const char * const pattern = "[SOME TEST PATTERN TO CALCULATE SUM FROM] ";

but NOTE WELL that although the result can be used in many of the same ways as the array version, it is not semantically identical.  You will see differences if you apply the sizeof, *, or &, or _Alignof operator to pattern.

Update:
Another, much uglier, workaround would be to avoid a string literal altogether, like so:
static const char pattern[] = {
        '[', 'S', 'O', 'M', 'E', ' ', 'T', 'E', 'S', 'T', ' ', 'P', 'A', 'T',
        'T', 'E', 'R', 'N', ' ', 'T', 'O', ' ', 'C', 'A', 'L', 'C', 'U', 'L',
        'A', 'T', 'E', ' ', 'S', 'U', 'M', ' ', 'F', 'R', 'O', 'M', ']', ' ', '\0' };

That leaves you with pattern as an array, not a pointer, and no separate array for a string literal.  It's ugly and more difficult to maintain, but converting from string literal form to that isn't hard -- it took me about 30 seconds to do that one.  If you do it, though, don't forget to add an explicit string terminator, as above.


text:
Q: Google Map polylines with JavaScript API I want to add polylines between multiple coordinates which will be added dynamically using SELECT element. I have managed to add multiple markers on google map but not polylines. My code is as follows.
var map;

function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: 7.8731, lng: 80.7718 },
        zoom: 7.9,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        backgroundColor: '#FFF',
        disableDefaultUI: true,
        draggable: false,
        scaleControl:false,
        scrollwheel:false,

        styles:[
        {
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [
                { "visibility": "on" }
            ]
        },
        {
            "featureType": "landscape",
            "stylers": [
                { "visibility": "off" }
            ]
        },
        {
            "featureType": "road",
            "stylers": [
                { "visibility": "off" }
            ]
        }
        ]
    });

    //new marker locations
    let markers = [];

    const cities = {
        'Ambewela': {
            name: 'Ambewela',
            lat: 6.8787,
            lng: 80.8136
        },
        'Anuradhapura': {
            name: 'Anuradhapura',
            lat: 8.3114,
            lng: 80.4037
        },
        'Colombo': {
            name: 'Colombo',
            lat: 6.9271,
            lng: 79.8612
        },
        'Dambulla': {
            name: 'Dambulla',
            lat: 7.8742,
            lng: 80.6511
        }
    };

    const addmarker = (lat, lng, name ) => {
        return new google.maps.Marker({
            title: name,
            name: name,
            position: {
                lat: lat,
                lng: LNG
            },
            map: map
        });
    };

    document.querySelector('#location-1').addEventListener('change', function(e) {
        e.preventDefault();
        if( this.value != '' && cities.hasOwnProperty( this.value ) ) {
            let obj = cities[ this.value ];

            markers.push( addmarker( obj.lat, obj.lng, obj.name ) );
            console.log("The city is "+this.value);

            return true;
        }
        alert(this.value + ' not found')
    });

}

window.initMap = initMap;

I tried this fiddle but no go. It may be a lack of knowledge in this area. So I need some help with adding polylines to this code. Any help would be appreciated.


text:
Q: what is the best practice of changing base object properties from inherited class I want to set "person" properties of student1 to person1. Is this possible doing it with assigning or any way without setting properties one by one ?
static void Main(string[] args)
{
  var student1 = new Student {Id = 1, Name = "kaya", Class = "3b", Number = "156"};
            var person1 = new Person { Id = 2, Name = "hasan" };

        }

    public class Person
    {
        public int Id { get; set; }
        public String Name { get; set; }
    }

    public class Student : Person
    {
        public int Number { get; set; }
        public String Class { get; set; }
    }

A: Well you could do it with reflection - but I personally wouldn't. You could add a CopyTo method in Person:
public class Person
{
    public int Id { get; set; }
    public String Name { get; set; }

    public void CopyTo(Person other)
    {
        other.Id = Id;
        other.Name = Name;
    }
}

Another option would be to use composition instead of inheritance, such that a Student had a Person property instead of deriving from Person. It really depends on the bigger picture though - do you actually want a Student to be a specialized Person, or was it just a simple way of getting the data in there?
This sort of question comes up every so often, but I rarely find myself wanting to do it in my own code... I'd be interested to see the design of code which requires this, to work out how I'd have designed it instead. It's not clear to me whether this is just a matter of me not doing the kind of work which encourages this pattern, or whether I use alternative designs to solve the same problem.

A: Have you looked at AutoMapper?  If you used half way decent conventions you end up writing almost zero code -
http://automapper.codeplex.com/
I recently used AutoMapper to map my POCOs with Subsonic.


text:
Q: Testing for an empty iterator in a Python for... loop The code below is based on this recipe. However, the key point of the recipe - that it provides a way to break out of the iteration on an iterator if the iterator is empty - doesn't seem to work here, instead behaving in the following undesired ways:

*

*If get_yes_no_answer() == False and there are two or more items left in the iterator, next_choice is skipped, rather than being selected on the next iteration.

*If get_yes_no_answer() == False and there are less than two items left in the iterator, my_func() returns None.

How can I ensure that:

*

*If get_yes_no_answer() == False and there are two or more items left in the iterator, next_choice is not skipped?

*If get_yes_no_answer() == False and there is one item left in the iterator, my_func() prints it and calls get_yes_no_answer()?

*If get_yes_no_answer() == False and there are no items left in the iterator, the except StopIteration clause is triggered?

Here's the code:
def my_func(choice_pattern, input):
# Search in input for some things to choose from.
choice_iterator = choice_pattern.finditer(input, re.M)
if not choice_iterator:
    print "No choices. Exiting..."
    sys.exit()
else:
    # Show choices to the user. For each one, ask user for a yes/no response. If
    # choice accepted, return a result. Otherwise show user next choice. If no
    # choices accepted by user, quit.
    for choice in choice_iterator:
        print choice.group()
        # get_yes_no_answer() returns True or False depending on user response.
        if get_yes_no_answer():
            return choice
        else:
            # Check if iterator is empty. If so, quit; if not, do something else.
            try:
                next_choice = choice_iterator.next()
            except StopIteration:
                print "No matches. Exiting..."
                sys.exit()
            else:
                choice_iterator = itertools.chain([next_choice], choice_iterator)

A: why are you doing it this way at all? why not just:
def get_choice(pattern, inpt):
    choices = pattern.finditer(inpt, re.M)
    if not choices:
        sys.exit('No choices')
    for choice in choices:
        print(choice.group(0))
        if get_yes_no_answer():
            return choice
    sys.exit('No matches')

I don't know what your is the length of your input but I doubt it's worth the trouble.

A: You don't need to check if the iterator is empty. The for loop will do that for you, and stop when the iterator is empty. It's as simple as that.
Also, you don't need the else after the sys.exit() or the return.
That done, your code looks like this:
def my_func(choice_pattern, input):
    # Search in input for some things to choose from.
    choice_iterator = choice_pattern.finditer(input, re.M)
    if not choice_iterator:
        print "No choices. Exiting..."
        sys.exit()

    # Show choices to the user. For each one, ask user for a yes/no response. If
    # choice accepted, return a result. Otherwise show user next choice. If no
    # choices accepted by user, quit.
    for choice in choice_iterator:
        print choice
        # get_yes_no_answer() returns True or False depending on user response.
        if get_yes_no_answer():
            return choice
    # Loop exited without matches.
    print "No matches. Exiting..."
    sys.exit()

That's it!
What happens is that you in the loop, also gets the next item. The result is that you in fact only show every second answer.
In fact, you can simplify it even more:
def my_func(choice_pattern, input):
    choice_iterator = choice_pattern.finditer(input, re.M)
    if choice_iterator:
        for choice in choice_iterator:
            print choice
            if get_yes_no_answer():
                return choice
    # If there is no choices or no matches, you end up here:
    print "No matches. Exiting..."
    sys.exit()

Iterators are used pretty much as any sequence type. You don't need to treat it differently from a list.

A: See the pairwise iterator from this question. You can then check for last item like this:
MISSING = object()
for choice, next_choice in pairwise(chain(choice_iterator, [MISSING])):
    print(choice.group())
    if get_yes_no_answer():
        return choice.group()
    if next_choice is MISSING:
        print("No matches. Exiting...")
        sys.exit()

In the example you showed this doesn't seem to be necessary. You don't need to check if finditer returned an iterator because it always does. And you can just fall through the for loop if you don't find what you want:
def my_func(choice_pattern, input):
    """Search in input for some things to choose from."""
    for choice in choice_pattern.finditer(input, re.M):
        print(choice.group())
        if get_yes_no_answer():
            return choice.group()
    else:
        print("No choices. Exiting...")
        sys.exit()

A: Why so complex approach?
I think this should do pretty much the same:
def my_func(pattern, data):
  choices = pattern.findall(data, re.M)
  while(len(choices)>1):
    choice = choices.pop(0)
    if get_yes_no_answer():
      return choice
    else:
      choices.pop(0)
  else:
    return None


text:
Q: Java Mock Framework that supports Actual Results, and Static Methods This question may have been asked before but I have very specific things that I am looking for.  I would like to integrate unit testing into a legacy web application but to do this and make sure that my unit tests are truly repeatable and decoupled from data access code I need a good Mock Framework that supports the following conditions.
I would prefer to just use a single framework that has all of the following features although if no such framework exists then so be it.  My frustration stems not from lack of choices but from too many it seems.

*

*Mock Instance methods

*Mock Static methods

*Mock return value of method

*Mock exception thrown

*Order of mocked method calls (Nice to have)

*Expected results vs. Actual Results (Nice to have)

Does anybody have any suggestions for Java mock frameworks that fit this criteria?

A: Try jmockit. In my opinion it currently supports the most features compared to others. Also it's an active project, and you'll probably get some very fast responses on their user group.

A: PowerMock framework can be used for doing the above features.


text:
Q: Find all arrays that includes certain id Postgres I store adjacency tree in table. I wrote a recursive Common Table expression to find all ascendants for each node in the tree.
So when I write SELECT * FROM TREE;
I get this:
 id |   ancestors
----+---------------
  0 | {} <- ROOT
  1 | {0}
  2 | {0}
  4 | {0}
 19 | {0}
 45 | {0}
  3 | {0,1}
  5 | {0,4}
  6 | {0,4}
  8 | {0,4}
 11 | {0,1}
 22 | {0,2}
  7 | {0,4,5}
  9 | {0,4,6}

I want to get the amount of all descendants for each node in the tree, so for each unique id I want to find number of arrays in ancestors column that contains such id.
I can do it manually, but only for one id:
SELECT count(*) from tree
WHERE 0 = any(tree.ancestors);

For this query, if node with id = 0 is the root, it should give me amount of all nodes minus 1 in the tree.
I tried to write something like this:
SELECT count(*) from tree
WHERE id = any(tree.ancestors)
group by id;

But it actually returns 0 rows.

A: You want to search the whole tree for each id, it's a self-join with a condition:
with tree(id, ancestors) as (
values
    (0, '{}'::int[]),
    (1, '{0}'),
    (2, '{0}'),
    (4, '{0}'),
    (19, '{0}'),
    (45, '{0}'),
    (3, '{0,1}'),
    (5, '{0,4}'),
    (6, '{0,4}'),
    (8, '{0,4}'),
    (11, '{0,1}'),
    (22, '{0,2}'),
    (7, '{0,4,5}'),
    (9, '{0,4,6}')
)

select t1.id, count(t2.*)
from tree t1
join tree t2 on t1.id = any(t2.ancestors)
group by 1
order by 1

 id | count
----+-------
  0 |    13
  1 |     2
  2 |     1
  4 |     5
  5 |     1
  6 |     1
(6 rows)

Note that you should use left join if you want to get all ids (with those that don't  appear in ancestors).


text:
Q: Python subprocess.call issue When I run the following in Python 3.2.3 in Linux it does nothing...
subprocess.call("export TZ=Australia/Adelaide", shell=True)

However if I run it in the terminal it works...
export TZ=Australia/Adelaide

I haven't had an issue with using subprocess.call before. Just seems to be this one. I'm running as a superuser so it's not a sudo thing, and I've also tried putting an r in front of the string to make it a raw string.
Any ideas? Thanks.

A: Export modifies the environment of the shell.
When you run it through subprocess, a new shell is created, the environment modified and then immediately destroyed.
When you run it in a shell, it modifies the environment of that shell so you can see the effect.

A: A subprocess (shell in this case) can't (normally) modify its parent environment.
To set the local timezone for the script and its children in Python (on Unix):
#!/usr/bin/env python3
import os
import time
from datetime import datetime, timezone

os.environ['TZ'] = 'Australia/Adelaide'
time.tzset()
print(datetime.now(timezone.utc).astimezone())
# -> 2015-09-25 05:02:52.784404+09:30

If you want to modify the environment for a single command then you could pass env parameter:
#!/usr/bin/env python
import os
import subprocess

subprocess.check_call('date', env=dict(os.environ, TZ='Australia/Adelaide'))
# -> Fri Sep 25 05:02:34 ACST 2015


text:
Q: MAVEN: How to create executable jar file for groovy classes I have a project where all files are Groovy classes and they are solely for test automation like below:
import geb.Browser
....
....

@Stepwise
class HomePage extends GebReportingSpec
{

def "Open Homepage"()
{
    cleanReportGroupDir()
    when: "Opening browser"
    to TopPage;
    and:
    report "HomePage opened"

    then: "Click Login Button"
    loginButton.click()
    and:
    report "Login Button Clicked"
}

def "Enter credentials and log in to xxx.co.jp"()
{
    when: "Log in page opened"
    at LoginPage
    and:
    report "Log in page opened"

    then: "Enter User Name and Password"
    username.value("xxx@gmail.com")
    password.value("password")
    and:
    signin.click()
    and:
    at TopPage
    report "Entered credentials and logged in"
}

def "Signin completed and top page opened. Now go to mypage"()
{
    when: "Signed in and top page is opened"
        myPage.click()

    then: "Waiting for loading mypage"
        waitFor{at MyPage}
        report "MyPage opened"
}

def "Click log Out button and log out from mypage"()
{
    when: "Logged into mypage"
        logout.click()

    then: "Waiting for loading mypage"
        waitFor{at BackToTopPage}
        report "Clicked logout button"
}

def "After logged out , go back to homepage"()
{
    when: "Click \"Go To Top\" Button"
        goBackToTopPage.click()

    then: "Check if logged out"
        report "At homepage after logout"
}

}

I have the folder structure like below:

When I create package with
    mvn clean package
command, and try to execute the created jar file, the following error occurs:
C:\Users\GebSpockBuildTest\target>java -jar Geb-0.0.1-SNAPSHOT.jar
Geb-0.0.1-SNAPSHOT.jarにメイン・マニフェスト属性がありません

Translation:
It is saying that, it does not find the main class in the manifest
Does someone know how to create runnable jar in this case?


text:
Q: why my If statment dont work with or in my Case -python date validation from automate the boringstuff with python import re
ausgabe =[]
Datum = re.compile(r"([0-2][1-9]|[3][0|1])(\/)([0-1][0-9])(\/)([0-2][0-9]{3})")     #filter
Daten =(" 31/12/2000 blub 31.02.2000 und 32/01/2099 blub 28/02/2000 29/09/2009 29/39/2009 ") #Datenstr
ausgabe =Datum.findall(Daten)     #durchsuchen

month = None
day = None
year = None

for Datum in ausgabe:
    allright = True
    day = int(Datum[0])
    month =int(Datum[2])
    year = int(Datum[4])
 #   print(day + "/" + month + "/" + year + "\n", end="")

    if month == 4 or 6 or 11: #if the month is 4, 6,11
        print(month)
        if day > 30:    #check the days of the month
            allright= False

    elif month == 2:
        if day > 28:
            print("feb hat nur 28 tage")
            allright = False
    elif day > 31:
            print("größer als 31")
            allright = False

if allright == True:
    print(str(day) + "/" + str(month) + "/" + str(year) + "\n", end="")

Problem is in the following line.
The month is 12 and it jumps into the next if statement inside and checks this
but also if isnt 4 6 and 11. This is out of automate the boring stuff with python.
i just started coding some weeks ago so maybee its super easy to see...
i rewatched some videos and thougth about it but i dont understand this
if month == 4 or 6 or 11: #if the month is 4, 6,11
        print(month)
        if day > 30:    #check the days of the month
            allright= False

A: Instead of
if month == 4 or 6 or 11: #if the month is 4, 6,11

you should use
if month == 4 or month == 6 or month == 11: #if the month is 4, 6,11

The
if month == 4 or 6 or 11:

Is interpreted by Python as
if (month == 4) or (6) or (11):

while 6 and 11 are positive integers interpreted by Python as True
As described here


text:
Q: Factor Clojure code setting many different fields in a Java object How do I factor code setting many different fields in a Java object?  I would like to factor
(set! (. employee name) "Chris")
(set! (. employee age) 100)
(set! (. employee salary) 5000)

to
(doseq [field '((name "Chris") (age 100) (salary 5000))]
  (set! (. employee (first field)) (second field)))

However this won't work because the period is a macro, and tries to evaluate (first field) literally.  By the way, I understand that setting fields is not good practice.  I need to inter-operate with legacy code.

A: Try to use setters - but if you have no choice and really need to factor this out, a macro like this would do:
(defmacro set-all [object & fields-and-values]
  (let [obj-sym (gensym)]
    `(let [~obj-sym ~object]
        ~@(for [[field value] (partition 2 fields-and-values)]
           `(set! (. ~obj-sym ~field)
                  ~value)))))

The gensym is needed in case the expression yielding object has any side effects.
Example usage:
user> (def p (java.awt.Point.))
#'user/p
user> (set-all p x 4 y 5)
5
user> p
#<Point java.awt.Point[x=4,y=5]>

A: You might try:
(defmacro set-all! [obj m]
    `(do ~@(map (fn [e] `(set! (. ~obj ~(key e)) ~(val e))) m) ~obj))

Example:
(def a (java.awt.Point.))
(set-all! a {x 300 y 100})

Macroexpand-all:
(do (set! (. a x) 9)
    (set! (. a y) 7)
    a)


text:
Q: Required sample size in internal audit In applied literature about the required sample size such as "Sampling for effective internal auditing" we find formulas for the required sample size to detect a proportion of a feature or an error rate as (I cite and use the same variable names)
$$
n = \frac{C^2 \rho q}{P^2},
$$
where $n$ is the required sample size, $C$ is the confidence level, $P$ is some measure of precision, $\rho = 1-q$ is the expected error rate.
Where do these formulas from auditing come from? I understand that their origin must be some Binomial distribution consideration with normal approximation.
Is there a publication where these sample size requirements are derived in a rigorous mathematical way?
I find quite a few publications citing formulae as the above but what is a good source for at the same time a rigorous mathematical treatment and applications in audit?

A: I am not familiar with the literature for interal auditing, but this looks quite similar to Normal approximation/Wald confidence interval (see wikipedia) and was published in   Laplace, Pierre Simon (1812). Théorie analytique des probabilités (in French). p. 283.
For a newer article about some of its problems:
Brown, Lawrence D.; Cai, T. Tony; DasGupta, Anirban. Interval Estimation for a Binomial Proportion. Statist. Sci. 16 (2001), no. 2, 101--133. doi:10.1214/ss/1009213286. https://projecteuclid.org/euclid.ss/1009213286
For a specific citation for Audits somebody else might be able to help.
The formula of the Normal approximation interval is as follows :
$$p=\hat{p}\pm z*\sqrt{\dfrac{p(1-p)}n} $$
if we subtract $\hat{p}$ and square afterwards we get:
$$(p-\hat{p})²=\dfrac{z^2 *p(1-p)}n $$
Now we solve for n:
$$n= \dfrac{z^2 *p(1-p)}{(p-\hat{p})²}  $$
This is exactly your formula. $z^2$ is $C^2$ and $(p-\hat{p})^2$ is $P^2$ in your equation


text:
Q: If $KerT$ is a subset of $Sp\{(1,0,1), (0,1,0)\}$ then $T(1,0,1)=0$? Is it correct that if $Ker(T) \subseteq Sp\{(1,0,1), (0,1,0)\}$
Then $T(1,0,1) = 0$
and $T(0,1,0)=0$?
Or is the only thing that one can be sure of is that $T(\lambda_1(1,0,1) + \lambda_2(0,1,0))=0$ for some $\lambda_1, \lambda_2 \in F$


text:
Q: Generating random image url in javascript I am generating random numbers and appending with the previous variable and trying to get the value of images. but also the random number only generated. How can I do this ?
Here's my code
var img1 = 'http://i.imgur.com/8olCb1Qb.jpg';
var img2= 'http://i.imgur.com/usJWgL7b.jpg';
var img3 = 'http://i.imgur.com/kxsLXb8b.jpg';
var img4 = 'http://i.imgur.com/XQbcjvUb.jpg';
var img5 = 'http://i.imgur.com/j3CVSSMb.jpg';
var img6 = 'http://i.imgur.com/BQNvBVib.jpg';
var img7 = 'http://i.imgur.com/DZq0ORlb.jpg';
var img8 = 'http://i.imgur.com/t73Tvlqb.jpg';
var img9 = 'http://i.imgur.com/Y8iFltdb.jpg';
var img10 = 'http://i.imgur.com/u3sBUMjb.jpg';
var no = Math.floor(Math.random() * 6) + 1
var img = 'img'+no;
console.log(img)

I prefer only javascript.

A: I think you want to select random images
var images = [
    'http://i.imgur.com/8olCb1Qb.jpg',
    'http://i.imgur.com/usJWgL7b.jpg',
    'http://i.imgur.com/kxsLXb8b.jpg',
    'http://i.imgur.com/XQbcjvUb.jpg',
    'http://i.imgur.com/j3CVSSMb.jpg',
    'http://i.imgur.com/BQNvBVib.jpg',
    'http://i.imgur.com/DZq0ORlb.jpg',
    'http://i.imgur.com/t73Tvlqb.jpg',
    'http://i.imgur.com/Y8iFltdb.jpg',
    'http://i.imgur.com/u3sBUMjb.jpg'
];
var random = images[Math.floor(Math.random() * images.length)];

A: well. arrays are fun. you should use them.

var images = ["8olCb1Qb", "usJWgL7b", "kxsLXb8b", "XQbcjvUb", "j3CVSSMb", "BQNvBVib", "DZq0ORlb", "t73Tvlqb", "Y8iFltdb", "u3sBUMjb"];
var randomPick = images[Math.random() * images.length | 0];
var url = "http://i.imgur.com/" + randomPick + ".jpg";
document.body.appendChild(new Image()).src = url;

A: As suggested by others, dynamic variable names are kind of ugly. You should use an array.
var imgs = ['a', 'b', 'c'];
var randomImg = imgs[Math.floor(Math.random() * imgs.length);

If you really want to use dynamic names, you should attach them to an object, not just free standing variables.
var imgs = {img1: 'a', img2: 'b', img3: 'c'};
var no = Math.floor(Math.random() * 3) + 1:
var img = imgs['img' + no];

A: Put your images in a div named div divImages.
var img=$('#divImages').children().eq(no);

And if you don't want using jquery the javascript is:
var img = document.getElementById('#divImages').children[no];

A: if you don't want to put your images in an array, you can call them like this:
var img1 = 'http://i.imgur.com/8olCb1Qb.jpg';
var img2= 'http://i.imgur.com/usJWgL7b.jpg';
var img3 = 'http://i.imgur.com/kxsLXb8b.jpg';
var img4 = 'http://i.imgur.com/XQbcjvUb.jpg';
var img5 = 'http://i.imgur.com/j3CVSSMb.jpg';
var img6 = 'http://i.imgur.com/BQNvBVib.jpg';
var img7 = 'http://i.imgur.com/DZq0ORlb.jpg';
var img8 = 'http://i.imgur.com/t73Tvlqb.jpg';
var img9 = 'http://i.imgur.com/Y8iFltdb.jpg';
var img10 = 'http://i.imgur.com/u3sBUMjb.jpg';
var no = Math.floor(Math.random() * 6) + 1
var img = 'img'+no;
console.log(window[img])
// or
console.log(this[img])


text:
Q: Regex error? - Is not deleting? Finally I found my last error in my code but this time it is very confusing... As you can see in the code, the Output should be   (Nothing). But I still get Mitgliedschaft Card (Weltweit).
Why isn't it deleting this phrase? - It should only get deleted if the case \b is active.
$deletewords = ["Mitgliedschaft Card (Weltweit)", "(Xbox 360/Xbox One/weltweit)", "Origins", "Guthaben Code - nur DE", "Guthaben Code für EA ORIGIN", "PC - nur DE"];

$myArra = ["Mitgliedschaft Card (Weltweit)", "Guthaben Code - nur DE", "Guthaben Code für EA ORIGIN", "PC - nur DE"];

foreach ($myArra as $string){
    $string = mb_eregi_replace('\b' . implode('|', $deletewords) . '\b', '', $string);
    echo $string;
}

It is confusing that all other words get deleted but Mitgliedschaft Card (Weltweit) is still there...

A: There're no word boundaries between ) and end of string in Mitgliedschaft Card (Weltweit). A word boundary exists only between a word character and a NON word character.
Moreover, parenthesis are special character in a regex, you have to escape them, here is a way to go using preg_quote:
$deletewords = ["Mitgliedschaft Card (Weltweit)", "(Xbox 360/Xbox One/weltweit)", "Origins", "Guthaben Code - nur DE", "Guthaben Code für EA ORIGIN", "PC - nur DE"];

$myArra = ["Mitgliedschaft Card (Weltweit)", "Guthaben Code - nur DE", "Guthaben Code für EA ORIGIN", "PC - nur DE"];

function quote($x) { return preg_quote($x);}
$deletewords = array_map('quote', $deletewords);
$allwords =  implode('|', $deletewords)
foreach ($myArra as $string) {
    $string = mb_eregi_replace('(?:' . $allwords . ')', '', $string);
    echo $string,"\n";
}


text:
Q: Navigation Bar tint opacity doesn't change the color I'm trying to make my navigation bar transparent in my app, so I tried to change the bar tint's opacity down to 0 so it's completely clear. However, this has absolutely no effect on the color of the background.
I've also tried programmatic solutions, putting the following code in viewDidLoad:
    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
    navigationController?.navigationBar.isTranslucent = true
    navigationController?.view.backgroundColor = .clear

However, I've gotten nothing to work. Is there a way that I'm missing to make my navigation bar completely transparent (but keep the bar buttons not transparent)

A:     self.navigationController?.navigationBar .setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = .clear
    self.navigationController?.navigationBar.backgroundColor = .clear
    self.navigationController?.navigationBar.tintColor = UIColor.white

A: You must walk through the view hierarchy and find the views that you need to hide. Click on the "Debug View Hierarchy" button to see a list of views and their names.
Here's a function that works for me:
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    transparentBackgrounds(navigationController?.navigationBar)
}
func transparentBackgrounds(_ view: UIView?) {
    guard let view = view else { return }

    let className = String(describing: type(of: view))
    print(className)
    if ["_UIBarBackground","UIImageView","UIVisualEffectView"].contains(className) {
        view.isHidden = true
    }

    view.backgroundColor = UIColor.clear
    for v in view.subviews {
        transparentBackgrounds(v)
    }
}


text:
Q: How to configure Postgres on Amazon Linux Most tutorials were installing both postgresql and postgresql-server:
$ sudo yum install postgresql postgresql-server

Installed:
  postgresql.x86_64 0:9.2.24-1.amzn2.0.1
  postgresql-server.x86_64 0:9.2.24-1.amzn2.0.1

Dependency Installed:
  postgresql-libs.x86_64 0:9.2.24-1.amzn2.0.1

The programs are installed here:
$ which psql
/usr/bin/psql

$ which postgres
/usr/bin/postgres

At this point, most tutorials go into initdb and pg_ctl <path> start
$ cd '/usr/lib'

$ service postgresql initdb
Hint: the preferred way to do this is now "postgresql-setup initdb"

$ sudo postgresql-setup initdb
[sudo] password for CORP\layne.sadler:
Initializing database ... OK

$ systemctl enable postgresql
Created symlink from /etc/systemd/system/multi-user.target.wants/postgresql.service to usr/lib/systemd/system/postgresql.service.

$ systemctl start postgresql
[18:47:32]  /usr/bin ☯  systemctl status postgresql
● postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2020-03-05 18:47:32 EST; 7s ago
  Process: 25559 ExecStart=/usr/bin/pg_ctl start -D ${PGDATA} -s -o -p ${PGPORT} -w -t 300 (code=exited, status=0/SUCCESS)
  Process: 25553 ExecStartPre=/usr/bin/postgresql-check-db-dir ${PGDATA} (code=exited, status=0/SUCCESS)
 Main PID: 25562 (postgres)
   CGroup: /system.slice/postgresql.service
           ├─25562 /usr/bin/postgres -D /var/lib/pgsql/data -p 5432
           ├─25564 postgres: logger process
           ├─25566 postgres: checkpointer process
           ├─25567 postgres: writer process
           ├─25568 postgres: wal writer process
           ├─25569 postgres: autovacuum launcher process
           └─25570 postgres: stats collector process

$ passwd postgres

note: /usr/bin/postgres -D /var/lib/pgsql/data -p 5432
STUCK
$postgres
postgres does not know where to find the server configuration file.
You must specify the --config-file or -D invocation option or set the PGDATA environment variable.

$ psql
psql: FATAL:  role "CORP\layne.sadler" does not exist

$ sudo pg_ctl -D postgresql-setup initdb
pg_ctl: cannot be run as root
Please log in (using, e.g., "su") as the (unprivileged) user that will
own the server process.

# can't seem to login as su despite other sudo commands working

Notes:

*

*The OS claims to be rhel fedora centos but doesn't have the rhel-release libraries.

*It seems like epel-release and dnf are blocked from install.

*^^^ postgres installation instructions want the above tools.

A: CentOS (Community ENTerprise Operating System) is a community (re)build of RHEL (Red Hat Enterprise Linux), with changed branding and some other details. It strives at being binary fully compatible, down to bug-for-bug. It doesn't have access to the RHEL package repositories, it uses their own.  EPEL (Extra Packages for Enterprise Linux) is a Fedora project that offers packages for RHEL/CentOS that RHEL doesn't carry.
I don't know where the "dnf is blocked from install" comes from. Note that in RHEL/CentOS dnf is relatively new (I believe an alternative starting with version 7), perhaps only the (legacy) yum is available? You could try yum install dnf if you need it. Depending on your exact version of CentOS, it might not be there at all.
The last error message you cite is quite clear: Postgres can't find/read it's configuration. Check carefully that the setup is done correctly. A wrong file name somewhere can derail everything.


text:
Q: Iptables to UFW before.rules not working I've got the follwing working iptables commands:
iptables -t nat -i ppp0 -A PREROUTING -p tcp --dport 81 -j DNAT --to-destination 192.168.16.8:80
iptables -t nat -A POSTROUTING -p tcp --dport 80 -j MASQUERADE

iptables -t nat -i ppp0 -A PREROUTING -p tcp --dport 5000 -j DNAT --to-destination 192.168.16.8:5000
iptables -t nat -A POSTROUTING -p tcp --dport 5000 -j MASQUERADE

I tried to add the following code to /etc/ufw/before.rules at the top and then at the bottom of the file, and did not work:
# NAT table rules
*nat
:PREROUTING ACCEPT [0:0]

-A PREROUTING -i ppp0  -p tcp --dport 81 -j DNAT --to-destination 192.168.16.8:80
-A PREROUTING -i ppp0  -p tcp --dport 5000 -j DNAT --to-destination 192.168.16.8:5000

:POSTROUTING ACCEPT [0:0]

-A POSTROUTING -p tcp --dport 80 -j MASQUERADE
-A POSTROUTING -p tcp --dport 5000 -j MASQUERADE

COMMIT

Any idea?
Thanks!

A: Did you try to write it like this?
# NAT table rules
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]

-A PREROUTING -i ppp0  -p tcp --dport 81 -j DNAT --to-destination 192.168.16.8:80
-A PREROUTING -i ppp0  -p tcp --dport 5000 -j DNAT --to-destination 192.168.16.8:5000

-A POSTROUTING -p tcp --dport 80 -j MASQUERADE
-A POSTROUTING -p tcp --dport 5000 -j MASQUERADE

COMMIT

The :PREROUTING and  :POSTROUTING policies seems to need to be declared just after the *nat line. At least it is how it looks like in my personal iptables rules file.


text:
Q: How can I change in Python the return/input type of a list that is implemented as an class attribute? EDIT (complete rephrase of the problem as the original version (see "original version", later) is misleading):
Here is the setting: I have a object which has a list of objects of type
<class 'One'>. I would like to access this list but rather work with objects
of type <class 'Two'> which is an enriched version of <class 'One'>.
Background (1):

*

*One could be an object that can be stored easily via a ORM. The ORM would handle the list depending on the data model

*Two would be an object like One but enriched by many features or the way it can be accessed

Background (2):

*

*I try to solve a SQLAlchemy related question that I asked here. So, the answer to the present question could be also a solution to that question changing return/input type of SQLAlchemy-lists.

Here is some code for illustration:
import numpy as np

class One(object):
  """
  Data Transfere Object (DTO)
  """
  def __init__(self, name, data):
    assert type(name) == str
    assert type(data) == str
    self.name = name
    self.data = data

  def __repr__(self):
    return "%s(%r, %r)" %(self.__class__.__name__, self.name, self.data)

class Two(np.ndarray):
  _DTO = One
  def __new__(cls, name, data):
    dto = cls._DTO(name, data)
    return cls.newByDTO(dto)

  @classmethod
  def newByDTO(cls, dto):
    obj = np.fromstring(dto.data, dtype="float", sep=',').view(cls)
    obj.setflags(write=False) # Immutable
    obj._dto = dto
    return obj

  @property
  def name(self):
    return self._dto.name

class DataUI(object):
  def __init__(self, list_of_ones):
    for one in list_of_ones:
      assert type(one) == One
    self.list_of_ones = list_of_ones

if __name__ == '__main__':
  o1 = One('first object', "1, 3.0, 7, 8,1")
  o2 = One('second object', "3.7, 8, 10")
  my_data = DataUI ([o1, o2])

How to implement a list_of_twos which operates on list_of_ones but provides the user a list with elements of type Two:
type (my_data.list_of_twos[1]) == Two
>>> True
my_data.list_of_twos.append(Two("test", "1, 7, 4.5"))
print my_data.list_of_ones[-1]
>>> One('test', '1, 7, 4.5')

Original version of the question:
Here is an illustration of the problem:
class Data(object):
    def __init__(self, name, data_list):
        self.name = name
        self.data_list = data_list

if __name__ == '__main__':
    my_data = Data ("first data set", [0, 1, 1.4, 5])

I would like to access my_data.data_list via another list (e.g. my_data.data_np_list) that handles list-elements as a different type (e.g. as numpy.ndarray):
>>> my_data.data_np_list[1]
array(1)
>>> my_data.data_np_list.append(np.array(7))
>>> print my_data.data_list
[0, 1, 1.4, 5, 7]

A: You should use a property
class Data(object):
    def __init__(self, name, data_list):
        self.name = name
        self.data_list = data_list

    @property
    def data_np_list(self):
        return numpy.array(self.data_list)

if __name__ == '__main__':
    my_data = Data ("first data set", [0, 1, 1.4, 5])
    print my_data.data_np_list

edit: numpy use a continous memory area. python list are linked list. You can't have both at the same time without paying a performance cost which will make the whole thing useless. They are different data structures.

A: No, you can't do it easily (or at all without losing any performance gain you might get in using numpy.array). You're wanting two fundamentally different structures mirroring one another, this will mean storing the two and transferring any modifications between the two; subclassing both list and numpy.array to observe modifications will be the only way to do that.

A: Not sure whether your approach is correct.
A property getter would help achieve what you're doing. Here's something similar using arrays instead of numpy.
I've made the array (or in your case numpy data type) the internal representation, with the conversion to list only done on demand with a temporary object returned.
import unittest
import array

class GotAGetter(object):
  """Gets something.
  """
  def __init__(self, name, data_list):
    super(GotAGetter, self).__init__()
    self.name = name
    self.data_array = array.array('i', data_list)

  @property
  def data_list(self):
    return list(self.data_array)

class TestProperties(unittest.TestCase):
  def testProperties(self):
    data = [1,3,5]
    test = GotAGetter('fred', data)
    aString = str(test.data_array)
    lString = str(test.data_list) #Here you go.
    try:
      test.data_list = 'oops'
      self.fail('Should have had an attribute error by now')
    except AttributeError as exAttr:
      self.assertEqual(exAttr.message, "can't set attribute")
    self.assertEqual(aString, "array('i', [1, 3, 5])",
                     "The array doesn't look right")
    self.assertEqual(lString, '[1, 3, 5]',
                     "The list property doesn't look right")

if __name__ == "__main__":
  unittest.main()

A: One solution I just came up with would be to implement a View of the list via class ListView which takes the following arguments:

*

*raw_list: a list of One-objects

*raw2new: a function that converts One-objects to Two-objects

*new2raw: a function that converts Two-objects to One-objects

Here is a the code:
class ListView(list):
  def __init__(self, raw_list, raw2new, new2raw):
    self._data = raw_list
    self.converters = {'raw2new': raw2new,
        'new2raw': new2raw}

  def __repr__(self):
    repr_list = [self.converters['raw2new'](item) for item in self._data]
    repr_str = "["
    for element in repr_list:
      repr_str += element.__repr__() + ",\n "
    repr_str = repr_str[:-3] + "]"
    return repr_str

  def append(self, item):
    self._data.append(self.converters['new2raw'](item))

  def pop(self, index):
    self._data.pop(index)

  def __getitem__(self, index):
    return self.converters['raw2new'](self._data[index])

  def __setitem__(self, key, value):
    self._data.__setitem__(key, self.converters['new2raw'](value))

  def __delitem__(self, key):
    return self._data.__delitem__(key)

  def __getslice__(self, i, j):
    return ListView(self._data.__getslice__(i,j), **self.converters)

  def __contains__(self, item):
    return self._data.__contains__(self.converters['new2raw'](item))

  def __add__(self, other_list_view):
    assert self.converters == other_list_view.converters
    return ListView(
        self._data + other_list_view._data,
        **self.converters
        )

  def __len__(self):
    return len(self._data)

  def __eq__(self, other):
    return self._data == other._data

  def __iter__(self):
    return iter([self.converters['raw2new'](item) for item in self._data])

Now, DataUI has to look something like this:
class DataUI(object):
  def __init__(self, list_of_ones):
    for one in list_of_ones:
      assert type(one) == One
    self.list_of_ones = list_of_ones
    self.list_of_twos = ListView(
        self.list_of_ones,
        Two.newByDTO,
        Two.getDTO
        )

With that, Two needs the following method:
def getDTO(self):
  return self._dto

The entire example would now look like the following:
import unittest
import numpy as np

class ListView(list):
  def __init__(self, raw_list, raw2new, new2raw):
    self._data = raw_list
    self.converters = {'raw2new': raw2new,
        'new2raw': new2raw}

  def __repr__(self):
    repr_list = [self.converters['raw2new'](item) for item in self._data]
    repr_str = "["
    for element in repr_list:
      repr_str += element.__repr__() + ",\n "
    repr_str = repr_str[:-3] + "]"
    return repr_str

  def append(self, item):
    self._data.append(self.converters['new2raw'](item))

  def pop(self, index):
    self._data.pop(index)

  def __getitem__(self, index):
    return self.converters['raw2new'](self._data[index])

  def __setitem__(self, key, value):
    self._data.__setitem__(key, self.converters['new2raw'](value))

  def __delitem__(self, key):
    return self._data.__delitem__(key)

  def __getslice__(self, i, j):
    return ListView(self._data.__getslice__(i,j), **self.converters)

  def __contains__(self, item):
    return self._data.__contains__(self.converters['new2raw'](item))

  def __add__(self, other_list_view):
    assert self.converters == other_list_view.converters
    return ListView(
        self._data + other_list_view._data,
        **self.converters
        )

  def __len__(self):
    return len(self._data)

  def __iter__(self):
    return iter([self.converters['raw2new'](item) for item in self._data])

  def __eq__(self, other):
    return self._data == other._data

class One(object):
  """
  Data Transfere Object (DTO)
  """
  def __init__(self, name, data):
    assert type(name) == str
    assert type(data) == str
    self.name = name
    self.data = data

  def __repr__(self):
    return "%s(%r, %r)" %(self.__class__.__name__, self.name, self.data)

class Two(np.ndarray):
  _DTO = One
  def __new__(cls, name, data):
    dto = cls._DTO(name, data)
    return cls.newByDTO(dto)

  @classmethod
  def newByDTO(cls, dto):
    obj = np.fromstring(dto.data, dtype="float", sep=',').view(cls)
    obj.setflags(write=False) # Immutable
    obj._dto = dto
    return obj

  @property
  def name(self):
    return self._dto.name

  def getDTO(self):
    return self._dto

class DataUI(object):
  def __init__(self, list_of_ones):
    for one in list_of_ones:
      assert type(one) == One
    self.list_of_ones = list_of_ones
    self.list_of_twos = ListView(
        self.list_of_ones,
        Two.newByDTO,
        Two.getDTO
        )

class TestListView(unittest.TestCase):
  def testProperties(self):
    o1 = One('first object', "1, 3.0, 7, 8,1")
    o2 = One('second object', "3.7, 8, 10")
    my_data = DataUI ([o1, o2])

    t1 = Two('third object', "4.8, 8.2, 10.3")
    t2 = Two('forth object', "33, 1.8, 1.0")
    # append:
    my_data.list_of_twos.append(t1)
    # __getitem__:
    np.testing.assert_array_equal(my_data.list_of_twos[2], t1)
    # __add__:
    np.testing.assert_array_equal(
        (my_data.list_of_twos + my_data.list_of_twos)[5], t1)
    # __getslice__:
    np.testing.assert_array_equal(
        my_data.list_of_twos[1:],
        my_data.list_of_twos[1:2] + my_data.list_of_twos[2:]
        )
    # __contains__:
    self.assertEqual(my_data.list_of_twos.__contains__(t1), True)
    # __setitem__:
    my_data.list_of_twos.__setitem__(1, t1),
    np.testing.assert_array_equal(my_data.list_of_twos[1], t1)
    # __delitem__:
    l1 = len(my_data.list_of_twos)
    my_data.list_of_twos.__delitem__(1)
    l2 = len(my_data.list_of_twos)
    self.assertEqual(l1 - 1, l2)
    # __iter__:
    my_data_2 = DataUI ([])
    for two in my_data.list_of_twos:
      my_data_2.list_of_twos.append(two)

if __name__ == '__main__':
  unittest.main()


text:
Q: How come I got two different calendar type of creationDate in PHAsset? I have this code, which try to fetch all the images sorting by the creationDate
PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[
        [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES],
    ];

    switch (type) {
        case MMAssetsPhoto:{
            fetch = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:options];
            break;
        }
        case MMAssetsVideo:{
            options.includeAssetSourceTypes = PHAssetSourceTypeiTunesSynced | PHAssetSourceTypeCloudShared | PHAssetSourceTypeUserLibrary | PHAssetSourceTypeNone;
            fetch = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:options];
            break;
        }
        default:{
            options.includeAssetSourceTypes = PHAssetSourceTypeUserLibrary;
            fetch  = [PHAsset fetchAssetsWithOptions:options];
            break;
        }
    }
    [fetch enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        EkoLog(@"=======");
        EkoLog(@"asset %@", obj);
        EkoLog(@"create date %@", obj.creationDate);
        EkoLog(@"modification date %@", obj.modificationDate);
    }];

but this is the log I got for some images
=======
asset <PHAsset: 0x10d075bd0> D27FB9E1-53F0-4884-A0EA-C6E839A6A0FB/L0/001 mediaType=1/0, sourceType=1, (4032x3024), creationDate=2017-01-05 11:54:50 +0000, location=0, hidden=0, favorite=0
create date 2017-01-05 11:54:50 +0000
modification date 2017-01-05 11:54:50 +0000
=======
asset <PHAsset: 0x10d075d20> 18EA7D99-9FB7-4941-9E7A-E0C68F5F791B/L0/001 mediaType=1/0, sourceType=1, (4032x3024), creationDate=2560-01-05 14:03:59 +0000, location=0, hidden=0, favorite=0
create date 2560-01-05 14:03:59 +0000
modification date 2017-01-05 14:04:00 +0000
=======
asset <PHAsset: 0x10d075e70> 41871302-553F-4BF0-AA8C-E6AC177E0068/L0/001 mediaType=1/0, sourceType=1, (3024x4032), creationDate=2560-01-05 14:15:57 +0000, location=0, hidden=0, favorite=0
create date 2560-01-05 14:15:57 +0000
modification date 2017-02-04 21:08:48 +0000

As you notice there are some image which got creationDate to 2560 which is year 2017 in buddhist calendar. This cause the sorting to arrange images with buddhist calendar to be at the end which is wrong.
I don't why it is right this because when I see it from modificationDate I got the correct 2017 year
Anyway to solve this?
UPDATE
Look like Apple bug to me because in Photos app those images are in 3103 year ...

A: There is no Apple bug. Incorrect date information is stored in the images.  An NSDate is unconnected to a calendar.  You can think of it as a simple wrapper for a count of seconds since 1970.  The log is not printing using different calendars - a date does not have a calendar.  The date for those image is in the Gregorian year 2560 - 543 years in the future.
I think that there was a programmer that did not understand the difference between a calendar and a date and stored incorrect date information in meta data of the images.  What is the source of these images?


text:
Q: How to return boolean value if sub-query returns any result I am attempting to write a query to audit a table of IP addresses against a table of overlapping net blocks.  Individual net blocks can be marked active or inactive via a BOOLEAN.  The audit query should return a BOOLEAN as active depending upon the active column in the netblock table.  If any net block has the active column set to FALSE, then the IP addresses contained within the netblock should report as active set to FALSE.
The following is the definition of the ip table:
CREATE TABLE IF NOT EXISTS ip
(
   address          INET            NOT NULL UNIQUE,
   modified         timestamp       WITH TIME ZONE NOT NULL
                                    DEFAULT TIMESTAMP 'epoch',
   username         VARCHAR(64),
   acctSession      VARCHAR(32),
   nasId            INTEGER,
   PRIMARY KEY      ( address ),
   FOREIGN KEY      ( nasId )
      REFERENCES    nas
                    ( id )
);

The following are example entries in ip:
radius_ippool=> SELECT * FROM ip ORDER BY address;
   address    |           modified            |      username      |       acctsession       | nasid
--------------+-------------------------------+--------------------+-------------------------+-------
 209.193.4.0  | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.1  | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.2  | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.3  | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.4  | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.5  | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.6  | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.7  | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.8  | 2019-05-09 11:55:20.456856-08 | jdoe8@example.net  | aqaqqaasdqweaasdqa8     |     3
 209.193.4.9  | 2019-05-09 11:55:20.638136-08 | jdoe9@aexample.net | qweadszcxqweasdzcx9     |     3
 209.193.4.10 | 2019-05-09 11:55:20.85176-08  | jdoe10@example.net | user:jdoe10@example.net |     3
 209.193.4.11 | 2019-05-09 11:55:20.872469-08 | jdoe11@example.net | user:jdoe11@example.net |     3
 209.193.4.12 | 2019-05-09 11:55:20.894765-08 | jdoe12@example.net | user:jdoe12@example.net |     3
 209.193.4.13 | 2019-05-09 11:55:21.02472-08  | jdoe13@example.net | user:jdoe13@example.net |     3
 209.193.4.14 | 1970-01-01 00:00:00-10        |                    |                         |
 209.193.4.15 | 1970-01-01 00:00:00-10        |                    |                         |
(16 rows)

The following is the definition of the netblock table:
CREATE TABLE IF NOT EXISTS netblock
(
   id               SERIAL,
   network          CIDR            NOT NULL UNIQUE,
   poolId           INTEGER         NOT NULL,
   regionId         INTEGER,
   active           BOOLEAN         NOT NULL DEFAULT TRUE,
   description      VARCHAR(256),
   PRIMARY KEY      ( id ),
   FOREIGN KEY      ( poolId )
      REFERENCES    pool
                    ( id ),
   FOREIGN KEY      ( regionId )
      REFERENCES    region
                    ( id )
);

The following are example entries in the netblock table:
radius_ippool=> SELECT * FROM netblock ORDER BY network;
 id |    network     | poolid | regionid | active |              description
----+----------------+--------+----------+--------+----------------------------------------
  1 | 209.193.4.0/28 |      1 |        2 | t      |
  2 | 209.193.4.0/29 |      1 |        2 | f      | Reserved for engineering test accounts
  4 | 209.193.4.4/30 |      1 |        2 | t      |
(3 rows)

I have figure out a query to list all "active"  and "inactive" IP addresses in separate queries:
-- query to return "inactive" IP addresses
SELECT DISTINCT      netblock.regionId AS  regionId,
                     ip.address        AS  ipAddress,
                     netblock.active   AS  active
   FROM              ip
   INNER JOIN        netblock
      ON             ip.address        <<= netblock.network
   WHERE             netblock.active   =   FALSE
   ORDER BY          ipAddress;

-- query to return "active" IP addresses
SELECT DISTINCT      netblock.regionId AS  regionId,
                     ip.address        AS  ipAddress,
                     netblock.active   AS  active
   FROM              ip
   INNER JOIN        netblock
      ON             ip.address        <<= netblock.network
   WHERE             netblock.active   =   TRUE
      AND            ip.address             NOT IN
                     (
                       SELECT          address AS ipAddress
                          FROM         ip
                          INNER JOIN   netblock
                             ON        ip.address          <<= netblock.network
                                AND    netblock.active     =   FALSE
                     )
   ORDER BY          ipAddress;

Results of above query:
 regionid |  ipaddress  | active
----------+-------------+--------
        2 | 209.193.4.0 | f
        2 | 209.193.4.1 | f
        2 | 209.193.4.2 | f
        2 | 209.193.4.3 | f
        2 | 209.193.4.4 | f
        2 | 209.193.4.5 | f
        2 | 209.193.4.6 | f
        2 | 209.193.4.7 | f
(8 rows)

 regionid |  ipaddress   | active
----------+--------------+--------
        2 | 209.193.4.8  | t
        2 | 209.193.4.9  | t
        2 | 209.193.4.10 | t
        2 | 209.193.4.11 | t
        2 | 209.193.4.12 | t
        2 | 209.193.4.13 | t
        2 | 209.193.4.14 | t
        2 | 209.193.4.15 | t
(8 rows)

How do I replace the static value of unknown for the active column in the following table by queuing the netblock table for inactvie/active net blocks?
SELECT DISTINCT      netblock.regionId AS regionId,
                     ip.address        AS address,
                     'unknown'         AS active,
                     (
                       nasId           IS NOT NULL
                       OR
                       acctSession     IS NOT NULL
                     )                 AS assigned,
                     ip.modified       AS modified,
                     ip.nasid          AS nasId,
                     ip.username       AS username,
                     ip.acctSession    AS acctSession
   FROM              ip
   INNER JOIN        netblock
      ON             ip.address        <<= netblock.network
   ORDER BY          address;

Results from above query:
 regionid |   address    | active  | assigned |           modified            | nasid |      username      |       acctsession
----------+--------------+---------+----------+-------------------------------+-------+--------------------+-------------------------
        2 | 209.193.4.0  | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.1  | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.2  | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.3  | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.4  | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.5  | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.6  | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.7  | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.8  | unknown | t        | 2019-05-09 11:55:20.456856-08 |     3 | jdoe8@example.net  | aqaqqaasdqweaasdqa8
        2 | 209.193.4.9  | unknown | t        | 2019-05-09 11:55:20.638136-08 |     3 | jdoe9@aexample.net | qweadszcxqweasdzcx9
        2 | 209.193.4.10 | unknown | t        | 2019-05-09 11:55:20.85176-08  |     3 | jdoe10@example.net | user:jdoe10@example.net
        2 | 209.193.4.11 | unknown | t        | 2019-05-09 11:55:20.872469-08 |     3 | jdoe11@example.net | user:jdoe11@example.net
        2 | 209.193.4.12 | unknown | t        | 2019-05-09 11:55:20.894765-08 |     3 | jdoe12@example.net | user:jdoe12@example.net
        2 | 209.193.4.13 | unknown | t        | 2019-05-09 11:55:21.02472-08  |     3 | jdoe13@example.net | user:jdoe13@example.net
        2 | 209.193.4.14 | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
        2 | 209.193.4.15 | unknown | f        | 1970-01-01 00:00:00-10        |       |                    |
(16 rows)

A: You can use ALL and a subquery to check if all the net blocks the IP is in are active.
SELECT ...
       true = ALL (SELECT nb2.active
                          FROM netblock nb2
                          WHERE ip.address <<= nb2.network) active,
       ...

Alternatively you can use NOT EXISTS:
SELECT ...
       NOT EXISTS (SELECT *
                          FROM netblock nb2
                          WHERE ip.address <<= nb2.network
                                AND NOT nb2.active) active,
       ...


text:
Q: How to parse:HERA was passed into law in 2008 and it governs FHFA
HERA was passed into law in 2008 and it governs FHFA

source:http://seekingalpha.com/article/4028577-mechanics-decoupling-gses-net-worth-sweep
HERA : the sister and consort of Zeus  in the dictionary.
it governs FHFA, the word it means HERA?
What does the sentence mean?

A: In this context, HERA doesn't mean the sister of Zeus, but rather refers to the Housing and Economic Recovery Act.
HERA is used as an acronym here, and not as a person's name. You can guess this from the fact that HERA is written in uppercase, and not as Hera.
Further, FHFA refers to Federal Housing Finance Agency. This context serves as a further hint to "verify" our interpretation of HERA.
Now it should be clear what your sentence means:

The Housing and Economic Recovery Act was passed in the year 2008. This Act governs the Federal Housing Finance Agency.


text:
Q: DarkSky API - Unhandled rejection Error - ReactJS / Axios / Node.js Wondering if you can help out, I'm a but stumped on this one...
I have a travel app in React, where users can locate other users online, (once the logged in users lat and lng has been located).
Once located, on my web app page - I use the lng/lng, to pull through Zomato api local info/restaurants.  This used to work, but now I get the following error in my console...   (This used to work, but the code hasn't changed...)
I'm trying to do the same with DarkSky api, to pull through local weather data. And I've structured my axios request exactly the same. However, this doesn't work either.
Failed to load resource: the server responded with a status of 400 ()
app.js:55642 Unhandled rejection Error: Request failed with status code
400
at createError (http://localhost:8000/app.js:9175:15)
at settle (http://localhost:8000/app.js:53028:12)
at XMLHttpRequest.handleLoad (http://localhost:8000/app.js:9048:7)
From previous event:
at Hub._this.getPlaces (http://localhost:8000/app.js:53788:26)
at commitCallbacks (http://localhost:8000/app.js:38450:15)
at commitLifeCycles (http://localhost:8000/app.js:41688:13)
at commitAllLifeCycles (http://localhost:8000/app.js:43345:9)
at HTMLUnknownElement.callCallback
(http://localhost:8000/app.js:32010:14)
at Object.invokeGuardedCallbackDev
(http://localhost:8000/app.js:32048:16)
at invokeGuardedCallback (http://localhost:8000/app.js:32097:29)
at commitRoot (http://localhost:8000/app.js:43484:9)
at completeRoot (http://localhost:8000/app.js:44381:36)
at performWorkOnRoot (http://localhost:8000/app.js:44331:11)
at performWork (http://localhost:8000/app.js:44249:9)
at performSyncWork (http://localhost:8000/app.js:44226:5)
at requestWork (http://localhost:8000/app.js:44126:7)
at scheduleWorkImpl (http://localhost:8000/app.js:44001:13)
printWarning @ app.js:55642
formatAndLogError @ app.js:55358
fireRejectionEvent @ app.js:55383
Promise._notifyUnhandledRejection @ app.js:54829
(anonymous) @ app.js:54808
setTimeout (async)
Promise._ensurePossibleRejectionHandled @ app.js:54807
Promise._reject @ app.js:57521
Promise._settlePromise @ app.js:57447
Promise._settlePromise0 @ app.js:57477
Promise._settlePromises @ app.js:57552
(anonymous) @ app.js:54272
Promise.then (async)
schedule @ app.js:58581
Async.settlePromises @ app.js:54271
Promise._reject @ app.js:57519
Promise._rejectCallback @ app.js:57337
PromiseArray._reject @ app.js:57777
PromiseArray._promiseRejected @ app.js:57797
Promise._settlePromise @ app.js:57439
Promise._settlePromise0 @ app.js:57477
Promise._settlePromises @ app.js:57552
(anonymous) @ app.js:54272
Promise.then (async)
schedule @ app.js:58581
Async.settlePromises @ app.js:54271
Promise._reject @ app.js:57519
Promise._rejectCallback @ app.js:57337
reject @ app.js:59005
geocode:1 Failed to load resource: the server responded with a status
of 404 ()

I can access the data/api call via Invision, or other tools, when I plug in the lat lng manually. So I know the api is working.  Here's an example:
https://api.darksky.net/forecast/MY_API_KEY/50.830133,-0.137434
However, there is something wrong in how I'm trying to make my Axios request working in my react JSX.
Here's the relevantcode of my page, (api keys hidden).
Any help would be great - I'm not sure why I can't console.log the weather data as a starting point.
And why my zomato data isn't changing, based on the users lat lng coordinates.
"class Hub extends React.Component {

state =  {
 places: null,
 articles: null,
 user: null,
 lat: null,
 lng: null,
 weather: null
}

setLocation = (lat, lng) => {
 console.log('location set...', lat, lng);
 this.setState({ lat: lat, lng: lng }, this.getPlaces);
}

getWeather = () => {
const params = {lat: this.state.lat, lng: this.state.lng};

//restaurants
Promise.props({
  weather: axios({
    url: 'https://api.darksky.net/forecast',
    params: params,
    json: true,
    method: 'GET',
    headers: {'user-key': 'MY_API_KEY'}
  }).then(res => console.log(res.data))
    .catch(err => console.log(err))
})
  .then(data => {
    this.setState({
      weather: data.weather
    });
  });

 }

 getPlaces = () => {
   const params = { count: 3, lat: 34.019864, lon: -118.490541 };
   if(this.state.lat && this.state.lng) {
   Object.assign(params, { lat: this.state.lat, lon: this.state.lng });
 }

 //restaurants
 Promise.props({
  restaurants: axios({
    url: 'https://developers.zomato.com/api/v2.1/geocode',
    params: params,
    json: true,
    method: 'GET',
    headers: {'user-key': 'MY_API_KEY'}
  }).then(res => res.data),
  articles: axios({
    url: 'https://developers.zomato.com/api/v2.1/collections',
    params: params,
    json: true,
    method: 'GET',
    headers: {'user-key': 'MY_API_KEY'}
  }).then(res => res.data)
 })
  .then(data => {
    this.setState({
      places: data.restaurants.nearby_restaurants.slice(0, 6),
      articles: data.articles.collections
    });
  });
 }

 componentDidMount() {
  this.getPlaces();
  this.getWeather();
 }

 render() {
  etc etc etc
 }

A: Looks like the API key and coordinates should be part of the path. try:
  weather: axios({
    url: `https://api.darksky.net/forecast/${MY_API_KEY}/${params.lat},${params.lng}`, // add api key to the path
    json: true,
    method: 'GET',
    headers: {'user-key': 'MY_API_KEY'}
  })


text:
Q: Mongoose pre-save binding/this keyword is not working Schema Definition
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var person = new Schema({
    name: {type : String}
})

person.pre('save', (next) => {
    console.log('in pre function and')
    console.log("this.name ",this.name);
    if (this.name == ' ') {
       // throw new console.error(' in valid name');
        console.log(err);
    }

    if (this.isNew == 'true') {
        console.log(this);
    } else {
        console.log(' false ' , this)
    }
    next();
})

const personModel = mongoose.model('personTable', person);
module.exports = {
    personModel
}

DataBase
const mongoose = require ('mongoose');
const {personModel} = require('./schema');

mongoose.connect('mongodb://localhost/dataBase',{useNewUrlParser : true});
const db = mongoose.connection;

db.once('open',()=>{
    console.log(' Connection successful ');

    const prakash = new personModel({
        name : 'prakash'
    })

    prakash.save((err,data)=>{
        if(err)console.error(err);
        else console.log('data saved ',data);
    })
})

In the Schema definition file, when I am logging out this.name and it is giving undefined
I could not understand this behavior, I have gone through this site and followed it but still couldn't find the way to recognize the error.

A: It's nothing wrong with mongo or mongoose, it's arrow function declaration.
Check the link that you have already posted. There is function keyword everywhere in examples.
Just follow the examples that you have provided via this code:
Schema.pre('save', function (next) {...

and you will get the following
You might wanna take a look at this questions on StackOverflow:

*

*Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?

*How does the "this" keyword work?
Also, MDN this MDN link about arrow functions.


text:
Q: QML how to get the position of Loader I want generate a binary tree like flow to show organization relationship info with QML.enter image description here
My way:

*

*Create tree node like flow example.

*Line the tree nodes with Canvas like above picture. I want get the
point and draw line after Loader.onLoaded.

My question:
After the first step has been done. In the second step, I can't get the right position point of the tree node.
Details:
According to Qt document, if I don't set the width and height of Loader explicitly, it will automatically set by its item size. However, I can't get the node position point in Loader.onloaded()
import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    id: appWindow

    visible: true
    width: 1066
    height: 600

    property var jsonData: [{"id":1,"pid":0},{"id":2,"pid":1},{"id":3,"pid":1},
        {"id":4,"pid":2},{"id":5,"pid":2},{"id":6,"pid":3},
        {"id":7,"pid":3},{"id":8,"pid":4},{"id":9,"pid":4},{"id":10,"pid":6}]
    property int maxRectangles: 5
    Component.onCompleted: {
        var color = Qt.lighter("red", maxRectangles / 7)
        pLoader.sourceComponent = rectangleComponent;
        var currItem = pLoader.item;
        currItem.color = "blue"
        currItem.text = 0

        var tmp = {};
        tmp[jsonData[0]["id"]] = currItem ;

        for(var index = 1; index < jsonData.length; index++) {
            color = Qt.lighter("red", index / 7)
            var sItem = jsonData[index]["pid"];
            if(tmp[sItem].rComponent.sourceComponent === null){
                tmp[sItem].rComponent.sourceComponent = rectangleComponent
                attachData(tmp[sItem].rComponent.item,index, color);
                tmp[jsonData[index]["id"]] = tmp[sItem].rComponent.item ;
            }
            else {
                tmp[sItem].lComponent.sourceComponent = rectangleComponent
                attachData(tmp[sItem].lComponent.item,index, color);
                tmp[jsonData[index]["id"]] = tmp[sItem].lComponent.item ;
            }
        }
    }
    function attachData(item, text, color){
        item.text = text;
        item.color = color
    }

    Component {
        id: rectangleComponent
        Column{
            property alias rComponent: rightLoader
            property alias lComponent: leftLoader
            property alias color: rect.color
            property alias text: myText.text
            spacing: 40
            //anchors.horizontalCenter: parent.horizontalCenter
            Rectangle {
                anchors.horizontalCenter: parent.horizontalCenter
                id:rect
                width: 100
                height: 100
                Text{
                    id:myText
                    font.pixelSize: 18
                    anchors.centerIn: parent
                    color:"white"
                }
                Component.onCompleted: {
                    console.log("Component.onCompleted", mapToItem(canvas, 0, 0))
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        updateDotPosition(parent)
                        //here, printed coordinate is my expected
                        //but i want line them after tree node loaded antomate
                        console.log("updateDotPosition", mapToItem(canvas, 0, 0))
                    }
                }
            }

            Row{
                spacing: 40
                anchors.horizontalCenter: parent.horizontalCenter
                Loader {
                    id:leftLoader
                    onLoaded: {
                        console.log("leftLoader", mapToItem(canvas, 0, 0))
                    }
                }
                Loader {
                    id:rightLoader
                    onLoaded: {
                        console.log("rightLoader", mapToItem(canvas, 0, 0))
                    }
                }
            }
        }
    }

    Canvas{
        anchors.fill: parent
        id:canvas
        Loader {
            id:pLoader
            anchors.horizontalCenter: parent.horizontalCenter
            //sourceComponent: rectangleComponent
        }
    }

    Rectangle {
        id: testMapToItemDot
        width: 20
        height: width
        radius: width / 2
        z: 1
        color: "darkblue"
    }

    function updateDotPosition(itemToMap) {
        var pos = testMapToItemDot.mapFromItem(
                    itemToMap,
                    (itemToMap.width - testMapToItemDot.width) / 2,   // these parameters are optional - I want to move the dot to
                    (itemToMap.height - testMapToItemDot.height) / 2) // the center of the object, not upper left corner
        testMapToItemDot.x += pos.x
        testMapToItemDot.y += pos.y
    }
}

A: Position and size of the loaded item can be accessed like this: Loader.item.x, Loader.item.y, Loader.item.width, Loader.item.height.
If this is not what your are looking for please describe the question more precisely.

Please have a look at this example application. I think it is what you are looking for - have a look at function updateDotPosition(itemToMap). Please note that if you will be "mapping" to an object that is not moving (dot in the example is moving) and this object will be a sibling of the Canvas with the same x, y values then the result of the function will give you exact points where from and where to draw a line. You will not need to use += as I used.
import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    id: appWindow

    visible: true
    width: 1066
    height: 600

    property int maxRectangles: 5

    Component {
        id: rectangleComponent
        Rectangle {
            x: 110
            y: 30
            width: 100
            height: 100
            property var loaderSource
            Component.onCompleted: {
                color = Qt.lighter("red", maxRectangles / 7)
                if (maxRectangles-- > 0)
                    loaderSource = rectangleComponent
                else
                    loaderSource = undefined
            }
            Loader {
                sourceComponent: loaderSource
            }
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    updateDotPosition(parent)
                }
            }
        }
    }

    Loader {
        sourceComponent: rectangleComponent
    }

    Rectangle {
        id: testMapToItemDot
        width: 20
        height: width
        radius: width / 2
        z: 1
        color: "darkblue"
    }

    function updateDotPosition(itemToMap) {
        var pos = testMapToItemDot.mapFromItem(
                    itemToMap,
                    (itemToMap.width - testMapToItemDot.width) / 2,   // these parameters are optional - I want to move the dot to
                    (itemToMap.height - testMapToItemDot.height) / 2) // the center of the object, not upper left corner
        testMapToItemDot.x += pos.x
        testMapToItemDot.y += pos.y
    }
}

Here is working version of your example. This is just an example. Dirty one unfortunately. This is because it was a little hard for me to understand what is going on in the code - I am sure you will not have this problem. Also I have used Timer because the Rectangle objects on creation have x,y equal to 0. I needed to wait a bit. Please do not use this in release code - it is bad design :)
import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    id: appWindow

    visible: true
    width: 1066
    height: 600

    property var jsonData: [{"id":1,"pid":0},{"id":2,"pid":1},{"id":3,"pid":1},
        {"id":4,"pid":2},{"id":5,"pid":2},{"id":6,"pid":3},
        {"id":7,"pid":3},{"id":8,"pid":4},{"id":9,"pid":4},{"id":10,"pid":6}]
    property int maxRectangles: 5
    Component.onCompleted: {
        var color = Qt.lighter("red", maxRectangles / 7)
        pLoader.sourceComponent = rectangleComponent;
        var currItem = pLoader.item;
        currItem.color = "blue"
        currItem.text = 0
        connectedItems.push([currItem, null])

        var tmp = {};
        tmp[jsonData[0]["id"]] = currItem ;

        for(var index = 1; index < jsonData.length; index++) {
            color = Qt.lighter("red", index / 7)
            var sItem = jsonData[index]["pid"];
            if(tmp[sItem].rComponent.sourceComponent === null){
                tmp[sItem].rComponent.sourceComponent = rectangleComponent
                attachData(tmp[sItem].rComponent.item,index, color);
                tmp[jsonData[index]["id"]] = tmp[sItem].rComponent.item ;
                connectedItems.push([tmp[sItem].rComponent.item, null])
            }
            else {
                tmp[sItem].lComponent.sourceComponent = rectangleComponent
                attachData(tmp[sItem].lComponent.item,index, color);
                tmp[jsonData[index]["id"]] = tmp[sItem].lComponent.item ;
                connectedItems.push([tmp[sItem].lComponent.item, null])
            }
            if ( jsonData[index]["pid"] !== 0) {
                connectedItems[connectedItems.length - 1][1] = connectedItems[jsonData[index]["pid"] - 1][0]
            }
        }
    }
    function attachData(item, text, color){
        item.text = text;
        item.color = color
    }

    property var connectedItems: [];

    function paintConnection(objectFrom, objectTo) {
        var vectorStart = canvas.mapFromItem(
                    objectFrom, objectFrom.width / 2, objectFrom.height)

        var vectorEnd = canvas.mapFromItem(
                    objectTo, objectTo.width / 2,0)

        var ctx = canvas.getContext("2d");
        ctx.beginPath();
        ctx.moveTo(vectorStart.x, vectorStart.y);
        ctx.lineTo(vectorEnd.x,vectorEnd.y);
        ctx.stroke();

        canvas.requestPaint()
    }

    Timer {
        id: paintLines
        interval: 100
        running: true
        onTriggered: {
            for (var i = 1 ; i < connectedItems.length ; i++) {
                paintConnection(connectedItems[i][1].rect, connectedItems[i][0].rect)
            }
        }
    }

    Component {
        id: rectangleComponent
        Column{
            property alias rComponent: rightLoader
            property alias lComponent: leftLoader
            property alias color: rect.color
            property alias text: myText.text
            property alias rect: rect
            spacing: 40
            //anchors.horizontalCenter: parent.horizontalCenter
            Rectangle {
                anchors.horizontalCenter: parent.horizontalCenter
                id:rect
                width: 100
                height: 100
                Text{
                    id:myText
                    font.pixelSize: 18
                    anchors.centerIn: parent
                    color:"white"
                }
                Component.onCompleted: {
                    console.log("Component.onCompleted", mapToItem(canvas, 0, 0))
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        updateDotPosition(parent)
                        //here, printed coordinate is my expected
                        //but i want line them after tree node loaded antomate
                        console.log("updateDotPosition", mapToItem(canvas, 0, 0))
                    }
                }
            }

            Row{
                spacing: 40
                anchors.horizontalCenter: parent.horizontalCenter
                Loader {
                    id:leftLoader
                    onLoaded: {
                        console.log("leftLoader", mapToItem(canvas, 0, 0))
                    }
                }
                Loader {
                    id:rightLoader
                    onLoaded: {
                        console.log("rightLoader", mapToItem(canvas, 0, 0))
                    }
                }
            }
        }
    }

    Canvas{
        anchors.fill: parent
        id:canvas
        Loader {
            id:pLoader
            anchors.horizontalCenter: parent.horizontalCenter
            //sourceComponent: rectangleComponent
        }
    }

    Rectangle {
        id: testMapToItemDot
        width: 20
        height: width
        radius: width / 2
        z: 1
        color: "darkblue"
    }

    function updateDotPosition(itemToMap) {
        var pos = testMapToItemDot.mapFromItem(
                    itemToMap,
                    (itemToMap.width - testMapToItemDot.width) / 2,   // these parameters are optional - I want to move the dot to
                    (itemToMap.height - testMapToItemDot.height) / 2) // the center of the object, not upper left corner
        testMapToItemDot.x += pos.x
        testMapToItemDot.y += pos.y
    }
}


text:
Q: Is this correct if I initialize a map attribute in bean class in Java public class ClassName implements Serializable {
    private static final long serialVersionUID = 1L;

    private Map<String, Integer> property= new HashMap<String, Integer>();

    // getters and setters
}

For this above example I want to now whether it is the correct approach? Or every time while setting the value I need to check and Initialize there?
Thanks!

A: Yes, this is perfectly fine. Adding the check in setter method to check if hashmap is initialized would be overhead.
If you are concern about the memory allocation of hashmap, then you can set the initial capacity while initializing this hashmap.


text:
Q: MDX - Storybook + React + Typescript I try to use MDX markup in building live docs for my storybook. When I run the storybook I get this error:
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:/Users/User/Desktop/priority-style-react/src/stories/Button1.stories.mdx: Unexpected token (12:9)

  10 | const makeShortcode = name => function MDXDefaultShortcode(props) {
  11 |   console.warn("Component " + name + " was not imported, exported, or provided by MDXProvider as global scope")
> 12 |   return <div {...props}/>
     |          ^
  13 | };
  14 | const Preview = makeShortcode("Preview");
  15 | const layoutProps = {

my webpack config to load .mdx is:
config.module.rules.push({
    test: /\.mdx?$/,
    use: [{loader: "babel-loader"}, {loader: '@mdx-js/loader'}],
    exclude: /node_modules/,
    include: [/src/]
});

storybook config.js:
import { configure, addDecorator } from '@storybook/react';
import { withKnobs } from '@storybook/addon-knobs';

import '../style/index.scss';

const req = require.context('../src/stories', true, /.stories.(tsx|mdx)/);

addDecorator(withKnobs);
configure(req, module);

looks like loader works incorrectly.
Can anyone help me to understand what I missed?

A: Okay there is something very silly in MDX files
It does not accept blank lines as we speak.
const makeShortcode = name => function MDXDefaultShortcode(props) {
console.warn("Component " + name + " was not imported, exported, or provided by MDXProvider as global scope")
return <div {...props}/>
 // remove this blank line here.
};

to
const makeShortcode = name => function MDXDefaultShortcode(props) {
console.warn("Component " + name + " was not imported, exported, or provided by MDXProvider as global scope")
return <div {...props}/>
};

And it should work as i scratched my head around this for hours.

A: So, guys, maybe this answer will be helpful for someone and save a lot of precious time.
I fixed this issue just with deleting configuration for .mdx extension in webpack.config.js. I just left my storybook config.js as it is. And the issue disappeared.
Also, you will faced this issue if you have blank lines between the JSX code in your .mdx file, as Zunaib Imtiaz answered.
Good luck, guys!


text:
Q: setting up Strapi on AWS - the docs don't seem to show everything I am trying to setup Strapi on AWS and am have been following the Strapi documentation here. But when I get to starting the EC2 instance, I have run into a few errors that were not addressed in in the docs. App keys, jwt secrets, and other env config variables. Has anyone else tried this and run into similar issues? And how did you get around things? I have been running pm2 log in my EC2 instance to get the errors.
I would post my config and everything but I have followed the strapi docs to the letter, and have run through every single step a dozen times now, and I don't want to basically copy and paste the docs in here again. My last step is to get Strapi to run on the EC2 instance, but I keep running into errors like this
error: Missing jwtSecret. Please, set configuration variable "jwtSecret" for the users-permissions plugin in config/plugins.js (ex: you can generate one using Node with `crypto.randomBytes(16).toString('base64')`).

which don't seem to be addressed in the docs anywhere.

A: This is because you need to expose the JWT_SECRET (and ADMIN_JWT_SECRET) environment variable. You can do it by adding (you can add a line like this: JWT_SECRET=A_RANDOM_STRING_HERE) it to the .env file located at the root of your Strapi project.
You can find more details here: https://docs.strapi.io/developer-docs/latest/plugins/users-permissions.html#jwt-configuration

A: You can generate jwt
node -e "console.log(require('crypto').randomBytes(256).toString('base64'));"


text:
Q: how to differentiate between 2 input tags in a form I am having an issue with 2 input tags in a form.
What i want to achieve is that when one certain input is choosen, an echo must be generated.
My form:
<form method="post" id="quickpoll">
......
<input class="quickpollsubmit" type="submit" name="quickpollsubmit" value="View">
<input class="quickpollsubmit" type="submit" name="quickpollsubmit" value="Vote">

The js:
$(document).on('submit', '#quickpoll', function()
{
var data = $(this).serialize();
    $.ajax({

    type : 'POST',
    url  : 'quickpoll_vote.php',
    data : data,
    success :  function(data)
               {
                    $("#quickpoll").fadeOut(500).hide(function()
                    {
                        $(".quickpollwrapper").fadeIn(500).show(function()
                        {
                            $(".quickpollwrapper").html(data);

                        });

                    });

               }
    });
    return false;
});

quickpoll_vote.php:
if($_POST)
{
   if($_POST['quickpollsubmit'] == 'View') {
   echo 'you choose View';
   }
}

The echo does not appear at all, whether i choose View input or Vote input.
The echo should only appear when i choose View input
What i am doing wrong?

A: You can use the following to see if a button was selected in PHP. However, in this case you have two HTML form elements with the same name, so those need to be unique as shown below.
<form method="post" id="quickpoll">
......
<input class="quickpollsubmit" type="submit" name="quickpollView" value="View">
<input class="quickpollsubmit" type="submit" name="quickpollVote" value="Vote">

if($_POST)
{
   if(isset($_POST['quickpollView']) {
       echo 'you choose View';
   } else if(isset($_POST['quickpollVote']) {
       echo 'you choose Vote';
   }
}

A: citation of stephen nielsen :
"The serialize method will NEVER return a value from the submit button. It does not return the submit button in the post. You will do best to just use a hidden form field and adding a click event to the button"
To check this point, add a :
print_r($_POST);

in the begin of quickpoll_vote.php
You will see that the argument "quickpollsubmit" has no value, whatever button you click.
Here's a way of solving this.

 $(document).on('click', '.quickpollsubmit', function()
    {
    $('#quickpollsubmit').val($(this).val());
    var data = $("#quickpoll").serialize();

        $.ajax({

        type : 'POST',
        url  : 'quickpoll_vote.php',
        data : data,
        success :  function(data)
                   {
                        $("#quickpoll").fadeOut(500).hide(function()
                        {
                            $(".quickpollwrapper").fadeIn(500).show(function()
                            {
                                $(".quickpollwrapper").html(data);

                            });

                        });

                   }
        });
        return false;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" name="quickpollsubmit" id="quickpollsubmit" readonly>
<input class="quickpollsubmit" type="submit" value="View">
<input class="quickpollsubmit" type="submit" value="Vote">

I edited the code so it will be compatible with your PHP part, but this way some element are really bad named, sorry about this.
In your script, use a hidden input instead of the text one, here for demonstration.

A: Try
if ($_POST['quickpollsubmit'] == 'View') {
    //action for view
} else if ($_POST['quickpollsubmit'] == 'Vote') {
    //action for vore
} else {
    //invalid action!
}