text:
Q: Shuffling array based on seed to get always the same result? I need to shuffle an array based on a seed number so I can get the same shuffle if I need it.
For example:
1. print_r( shuffleIt( $array, 2 ) );
2. print_r( shuffleIt( $array, 6 ) );
3. print_r( shuffleIt( $array, 2 ) );

*

*and 3. would show the same shuffled array but different than 2.

I found this function googling:
function entropy( $array, $sort_seed ) {
    mt_srand( $sort_seed );
    $order = array_map( create_function( '$val', 'return mt_rand( );' ), range( 1, count( $array ) ) );
    array_multisort( $order, $array );
    return $array;
}

It works fine on my pc with php-cli, I always get the same array for each different sort_seed I use, but when I uploaded it to a server, I get different arrays every time even when I am using the same sort_seed.
How could I get always the same shuffled array when using the same sort_seed?
btw. I need to preserve keys or sort a multidimensional array so I can store the key there.

A: If you need it on any pc, you need a random number generator that works the same across computers. I looked up one pseudo-random-number generator that might be suitable for you from the Random Number Generation Wikipedia page and put it into a class so you can seed it.
I don't know for what you need it, but this just might suit your needs. It's independent to system configuration:
function shuffleIt($array, $seed)
{
    $mwc = new mwc($seed);
    $order = array();
    $count = count($array);
    while($count--)
        $order[] = $mwc->random()
    ;

    array_multisort($order, $array);
    return $array;
}

/**
 * Multiply-with-carry RNG
 *
 * method invented by George Marsaglia
 */
class mwc
{
    private static $def_m_w = 1712; /* must not be zero */
    private static $def_m_z = 23;   /* must not be zero */
    private $m_w, $m_z;
    public function __construct($seed = NULL)
    {
        $this->m_w = self::$def_m_w;
        $this->m_z = self::$def_m_z;
        if (NULL !== $seed)
            $this->seed($seed);
    }
    public function seed($seed)
    {
        $seed = (int) $seed;
        if (!$seed) throw new InvalidArgumentException('Must not be zero.');
        $this->m_z = $seed;
        $this->random();
    }
    public function random()
    {
        $this->m_z = 36969 * ($this->m_z & 65535) + ($this->m_z >> 16);
        $this->m_w = 18000 * ($this->m_w & 65535) + ($this->m_w >> 16);
        return ($this->m_z << 16) + $this->m_w;  /* 32-bit result */
    }
}

Note: This might behave differently between 32/64 bit systems, especially as PHP differs here for integers and overflows between windows and unix. You might want offset at the signed minimum for 32 bit integers in PHP instead of 0 as it is now, to switch the implementation to gmp or just reduce the size by one bit.

Usage Example 32 bit reported to work by ekke from netherlands
$shuffle = new GeorgeShuffle();
$seed    = $shuffle->seed();
$a       = array('A', 'B', 'C', 'D', 'E', 'F', 'G');
$shuffle->reOrder($a);
var_dump($a);
$shuffle->seed($seed);
$shuffle->reOrder($a);
var_dump($a);

/**
 * Array shuffle class using
 * the multiply-with-carry method
 * invented by George Marsaglia
 */
class GeorgeShuffle
{

    private static $def_m_w = 1959; /* must not be zero */
    private static $def_m_z = 2006; /* must not be zero */
    private $m_w, $m_z;
    const maxint = 2147483647;

    public function __construct($seed = null)
    {
        $this->m_w = self::$def_m_w;
        $this->m_z = self::$def_m_z;
        if ($seed) $this->seed($seed);
    }

    public function reOrder(&$array, $seed = null)
    {
        if (!empty($seed)) $this->seed($seed);
        $a = array();
        for ($i = 0, $j = count($array); $i < $j; $i++) {
            $a[$i] = $this->random();
        }
        array_multisort($a, $array);
        //- to return a copy, remove the &
        return $array;
    }

    public function seed($seed = false)
    {
        if (is_string($seed)) $seed = hexdec($seed);
        if (empty($seed)) $seed = round(mt_rand(1, self::maxint));
        $this->m_z = $seed;
        $this->random();
        //- return the seed used in hex (8 chars) for reproducing
        return str_pad(dechex($seed), 8, '0', STR_PAD_LEFT);
    }

    public function random()
    {
        $this->m_z = 36969 * (($this->m_z And 65535) + ($this->m_z >> 16));
        $this->m_w = 18000 * (($this->m_w And 65535) + ($this->m_w >> 16));
        return ($this->m_z << 16) + $this->m_w; /* 32-bit signed result */
    }
}

A: Does you host run by chance the Suhosin security extension? Apparently, it has a couple of directives that prevent scripts from setting a seed:
suhosin.srand.ignore = On
suhosin.mt_srand.ignore = On

Further reading:

*

*http://www.suspekt.org/2008/08/22/suhosin-0926-improved-randomness/

*http://www.adayinthelifeof.nl/2010/12/13/php-srand-problems-with-suhosin/
Here's a quick way to test whether this is the problem:
<?php

mt_srand(33);
var_dump(mt_rand(1, 10000));

mt_srand(33);
var_dump(mt_rand(1, 10000));

mt_srand(33);
var_dump(mt_rand(1, 10000));


text:
Q: How to make a lightbox with a scroll to top effect when opened? I'm using lightbox_me script which is based on jQuery. Since my lightbox link is at the bottom of my page, I would like to have a scroll to top effect when someone click on a link that opens the lightbox. So basically the lightbox would be shown at the top of the parent page.
I've have setup a clean demo which can be found here : http://lyesdehili.com/LightBox.html
$(function () {
    function launch() {
        $('#sign_up').lightbox_me({
            centered: true,
            onLoad: function () {
                $('#sign_up').find('input:first').focus()
            }
        });
    }

    $('#try-1').click(function (e) {
        $("#sign_up").lightbox_me({
            centered: true,
            preventScroll: true,
            onLoad: function () {
                $("#sign_up").find("input:first").focus();
            }
        });

        e.preventDefault();
    });

    $('table tr:nth-child(even)').addClass('stripe');
});

Scroll down the page to find the  lightbox link

Click to open lightbox

Can I see some ID?

    Please sign in using the form below

        Username: <input class="sprited"/>
        Password: <input class="sprited"/>

            Cancel
            Sign in

Feeling left out?

    Don't be sad, just click here to sign up!
    close

A: $('#try-1').click(function(e) {
    $('body').scrollTop(0);
    $("#sign_up").lightbox_me...; // continue with your code here
});

Add a scrollTop statement to scroll to the starting of the page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matplotlib Annotation Error I tried finding solution to solve this error, but I can't get it.
# example data
month_no_list_svc_log = ["Nov", "Dec", "Jan", "Feb", "March", "April"]
event_count_by_month_list_svc_log = [10, 20, 30, 40, 50, 60]

fig, ax = plt.subplots(1,2, figsize = (10,4))
ax[0].plot(np.arange(len(month_no_list_svc_log)),event_count_by_month_list_svc_log)

# I do this to sort the months name the way I want it to
ax[0].set_xticks(np.arange(len(month_no_list_svc_log)))
ax[0].set_xticklabels(month_no_list_svc_log)

for i, txt in enumerate(event_count_by_month_list_svc_log):
    # the code below generates an error
    ax[0].annotate(txt, (month_no_list_svc_log[i],event_count_by_month_list_svc_log[i]))

I get an error:

'NoneType' object has no attribute 'seq'

A: Your x-coordinate in annotate must be a value on the x-axis your provided to plot. There, you used the index of the months in month_no_list_svc_log, so this would match the value i in your for loop. Also you can reuse txt, here renamed to count, in the following way:
for i, count in enumerate(event_count_by_month_list_svc_log):
    ax[0].annotate(count, (i, count))

Btw: If you want your x-axis to be an arange of the same length as your y-axis data, you can just leave away the x-axis parameter in the call to plot:
ax[0].plot(event_count_by_month_list_svc_log)


text:
Q: When a webpage loads, what's the best way to auto-focus an HTML form input? Right now I use:
<body onLoad="document.getElementById('myinput').focus();">
but it doesn't seem to work on iPhone.

A: Autofocus will never work on iPhone. Apple decided it is not in the interest of the user, so that is that.
The best way is to add autofocus="" on the input in question. If you want to support older browsers to it is best to put the JS you've given at the end of the page instead of putting it in onload. If the page contains some images that take some time to load the onload will not fire directly and the user could already have selected another input and started typing, resulting in the text appearing in the wrong textbox once the onload fires, frustrating users.
So just put <script>document.getElementById('myinput').focus();</script> just before </body>

A: The following code works for me
 <input type="text" name="email" placeholder="E-Mail ID" autofocus></input>


text:
Q: How to fetch details with while loop and display with foreach[MySQL and PHP] How to fetch details with while loop and display with foreach?
Need to do this with bind....
$stmt= $db ->prepare("SELECT quote_autor, quote_text FROM quotes")or die($db->error);
if( $stmt !== FALSE ) {
$stmt->execute();
$stmt->bind_result($quote_autor,$qupte_text);
$records= array();
while($stmt ->fetch()){
$records[]=$stmt ->fetch();
///??????
}
foreach($records as $rec){
//???????
}

A: Using while to fetch the records:
while($records[] = $stmt ->fetch());

Using for-each to loop through after fetching
foreach($records[] as $record) {
    echo $record['COLUMN_NAME'];
    // use var_dump or print_r to know more
}

Edit:
If you want to print all the names, instead of using for-each you can do:
echo implode(", ", $array);

A: $stmt= $db ->prepare("SELECT quote_autor, quote_text FROM quotes")or die($db->error);
if( $stmt !== FALSE ) {
$stmt->execute();
$stmt->bind_result($quote_autor,$qupte_text);
$records= array();
while($dyna=$stmt->fetch()){
    array_push($records,$dyna);
}
echo "
";
foreach($records as $rec){
    echo "
Autor: ".$row[0]."
".$row[1]."
";
}
echo "
";


text:
Q: Reference for Frobenius's proof of Schur's finite version of the Rogers - Ramanujan identities In his paper "Ein Beitrag zur additiven Zahlentheorie und zur Theorie der Kettenbrüche" I. Schur has stated that Frobenius has communicated to him a simple direct proof of his finite version of the Rogers – Ramanujan identities. I could not find a reference to this proof. Does anyone know where this direct proof has been published?

A: Early history of the Rogers-Ramanujan identities is discussed by Hardy in "Ramanujan: Twelve lectures suggested by his life and work", Chelsea,
third edition, 1978. But Hardy doesn't mention Frobenius. Neither is Frobenius mentioned in Andrew V. Sills' comprehensive review http://www.combinatorics.org/ojs/index.php/eljc/article/view/v10i1r13 (Finite Rogers-Ramanujan Type Identities). Schur's biography http://link.springer.com/chapter/10.1007%2F978-81-322-0767-2_14 (Issai Schur: Ramanujan's German Contemporary) also doesn't mention Frobenius contribution, as I can judge. I suspect Frobenius proof was never published. I have no access to "Ferdinand Georg Frobenius, Gesammelte Abhandlungen, Band I - III, Springer, Berlin, 1968" (http://www.amazon.co.uk/Ferdinand-Georg-Frobenius-Gesammelte-Abhandlungen/dp/B00H7GKVR2 ) to check this proposition.


text:
Q: Generate the initial game board of a Candy-Crush-like game I need to implement a function,
which returns a 6 by 6 matrix that fulfills the following requirements:

*

*The 36 numbers on the board must be 9 ones, 9 twos, 9 threes and 9 fours

*Any row or column must not contain 3 or more direct neighbours that are the same number

*The function return value must not be a constant

*Obviously it's not allowed to use pre-calculated answers

correct answer:
    [[3, 2, 4, 1, 3, 2],
    [2, 2, 1, 1, 4, 4],
    [4, 4, 1, 3, 3, 2],
    [4, 1, 3, 2, 2, 4],
    [3, 1, 2, 4, 3, 1],
    [3, 3, 1, 1, 2, 4]]

   [[3, 3, 1, 2, 2, 4],
    [1, 1, 3, 3, 2, 4],
    [4, 4, 2, 1, 1, 3],
    [2, 2, 3, 4, 4, 1],
    [4, 4, 1, 1, 2, 2],
    [3, 1, 2, 3, 3, 4]]

wrong answer:
    [[3, 3, 3, 2, 2, 4],
    [1, 1, 1, 3, 2, 4],
    [4, 4, 2, 1, 1, 3],
    [2, 2, 3, 4, 4, 1],
    [4, 4, 1, 1, 2, 2],
    [3, 1, 2, 3, 3, 4]]

   [[3, 3, 1, 2, 2, 4],
    [1, 1, 2, 3, 2, 4],
    [4, 4, 1, 1, 2, 3],
    [2, 2, 3, 4, 4, 1],
    [4, 4, 1, 1, 2, 2],
    [3, 1, 2, 3, 3, 4]]

Don't need to worry too much about the academic time/space complexity. Focus more on the engineering point of view. Is there any good idea?

A: This should work. Note that this solution just generates a random board, checks if the conditions hold, and if not, generates another, so is not the most elegant solution.
Code:
from random import shuffle

def check_board(board):
    for row in board:
        if check_list(row):
            return False
    for i in range(len(board[0])):
        col = [row[i] for row in board]
        if check_list(col):
            return False
    return True

def check_list(lst):
    return any(lst[i]==lst[i+1] and lst[i]==lst[i+2] for i in range(len(lst)-2))

board = [[]]

while check_board(board):
    board = [1,2,3,4]*9
    shuffle(board)
    board = [board[i:i + 6] for i in range(0, len(board), 6)]

print(board)

Example boards generated:
[[3, 2, 4, 3, 3, 2],
 [1, 1, 2, 3, 1, 3],
 [1, 3, 3, 2, 2, 2],
 [4, 4, 1, 4, 1, 2],
 [1, 1, 4, 4, 2, 4],
 [2, 4, 4, 3, 3, 1]]

[[2, 3, 4, 1, 4, 1],
 [3, 4, 1, 1, 3, 4],
 [3, 1, 4, 1, 3, 4],
 [3, 4, 2, 4, 2, 1],
 [2, 1, 4, 2, 3, 2],
 [2, 2, 1, 3, 3, 2]]

A: *

*Create an array of size 36 and fill it with your desired values => [1,1,1....4,4,4]

*Apply Fisher-Yates shuffle to create a permutation of that array in O(n)

*Check for the "3 in a row" rule and swap a random value if nesseccary, check again until the grid is free of that.


text:
Q: Error inflating class android.support.design.widget.AppBarLayout on Samsung Galaxy Note Edge Only on Samsung Galaxy Note Edge(Android 5.0.1), I am getting android.view.InflateException: Binary XML file line #23: Error inflating class android.support.design.widget.AppBarLayout).
Currently I am using Support Library version 27.1.1
implementation "com.android.support:design:27.1.1"

Before I have used Support Library version 26 also, but no success.
I have used the following theme in the corresponding activity:
<style name="ToolbarTheme" parent="Theme.AppCompat"> <item name="windowNoTitle">true</item> <item name="windowActionBar">false</item> <item name="actionMenuTextColor">@android:color/white</item> <item name="android:actionMenuTextColor">@android:color/white</item> <item name="textAllCaps">false</item> </style>

StackTrace:
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11] SourceFile:1280: Uncaught exception in Thread[main,5,main]
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11] java.lang.RuntimeException: Unable to start activity ComponentInfo{com.messaging.vzmsgs/com.messaging.mqtt.group.ui.CreateGroupActivity}: android.view.InflateException: Binary XML file line #23: Error inflating class android.support.design.widget.AppBarLayout
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2712)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2777)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   android.app.ActivityThread.access$900(ActivityThread.java:179)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   android.os.Handler.dispatchMessage(Handler.java:102)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   android.os.Looper.loop(Looper.java:145)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   android.app.ActivityThread.main(ActivityThread.java:5972)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   java.lang.reflect.Method.invoke(Native Method)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   java.lang.reflect.Method.invoke(Method.java:372)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11]   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11] caused by:
09-13 09:56:43.378  3975  3975 FATAL [main,pri=-11] android.view.InflateException: Binary XML file line #23: Error inflating class android.support.design.widget.AppBarLayout

Layout code:
<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#e5e5e5">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            android:fitsSystemWindows="true">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            android:layout_margin="5dp"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:id="@+id/group_bg">

                <ImageView
                    android:id="@+id/group_icon"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center_horizontal"
                    android:src="@drawable/ico_add_group_img_white"
                    android:layout_marginBottom="20dp"
                    android:layout_marginTop="20dp"/>
                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:orientation="horizontal"
                    android:layout_gravity="center_horizontal">
                    <com.aniways.AniwaysEditText
                        android:id="@+id/group_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@android:color/transparent"
                        android:hint="@string/create_group_name_hint_txt"
                        android:maxWidth="@dimen/maxTextMessageWidth"
                        android:inputType="textCapSentences"
                        android:textColor="@android:color/black"
                        android:textColorHint="#a1a1a0"
                        android:textStyle="italic"
                        android:gravity="center"
                        android:cursorVisible="true"
                        android:textCursorDrawable="@null"
                        android:textSize="17dp"
                        android:theme="@android:style/Theme.Holo.Light.NoActionBar"
                        android:layout_centerVertical="true"
                        android:layout_centerHorizontal="true" />

                    <ImageView
                        android:id="@+id/btnEmoji"
                        android:layout_width="23dp"
                        android:layout_height="23dp"
                        android:contentDescription="@string/add_emoji"
                        android:src="@drawable/emoji_active_chooser"
                        android:layout_marginLeft="15dp"
                        android:layout_centerVertical="true"
                        android:visibility="gone"
                        android:layout_toRightOf="@+id/group_name" />
                </RelativeLayout>

                <View
                    android:id="@+id/divider"
                    android:layout_width="match_parent"
                    android:layout_height="0.7dp"
                    android:layout_below="@+id/group_name"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="50dp"
                    android:layout_marginRight="50dp"
                    android:background="#c3c3c3" />

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"
                    >
                    <com.verizon.messaging.mqtt.group.ui.GroupRightChooser
                        android:id="@+id/group_right_chooser"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                         />
                    <ImageView
                        android:id="@+id/admin_info"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/info"
                        android:padding="4dp"
                        android:layout_centerVertical="true"
                        android:layout_toRightOf="@id/group_right_chooser"
                        />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginBottom="10dp"
                    android:layout_marginTop="10dp"
                    >

                    <TextView
                        android:id="@+id/enhancedgroupInfoText"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_marginBottom="5dp"
                        android:text="@string/enhanced_group_info_bar"
                        android:textColor="@color/black"/>

                    <ImageView
                        android:id="@+id/enhancedgroupInfo"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_toRightOf="@id/enhancedgroupInfoText"
                        android:padding="4dp"
                        android:src="@drawable/info"
                        />
                </RelativeLayout>
            </LinearLayout>
            <ImageView
                android:id="@+id/select_group_bg"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:visibility="gone"
                android:layout_gravity="right|top"
                android:src="@drawable/ico_pencil"
                android:layout_margin="10dp"/>
        </FrameLayout>
    </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/emoji_footer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:orientation="vertical"
            android:visibility="invisible" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="1dp"
        android:id="@+id/contactsContainer"
        android:orientation="vertical"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:background="@android:color/white">
    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

Any help or guidance will be well appreciated.

A: Try changing this:
Theme.AppCompat

To:
Theme.AppCompat.Light.NoActionBar

Or you can try adding this in your AndroidManifest.xml:
android:theme="@style/Theme.AppCompat.Light.NoActionBar"


text:
Q: Multithreading not using full processor/memory/disk capacity My Python code is to exctract information from XML files and load it into a database.
These files named as numbers 11582.xml, 5300593.xml, etc.
and I have around 1 million files.
I have built the code and it is working fine.
I faced a problem that the code does not take full processor/memory/disk capacity.
My processor should 20% max used.
I asked here and other places and found that I have to use multithread to use full capacity.
So I have to change my script to adopt multithreading.
I did that but still not working to the max.
What I did wrong? and how to fix it?
My code:
import pymssql
import pyodbc
import pandas as pd
import thread
import glob
import xml.etree.ElementTree as ET

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=Server123;'
                      'Database=NLP;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()

def ExtractData(ThreadName):
    for file in glob.glob("H:\\datas_Output\\xmldata\\" & ThreadName & "*.xmi"):

        filename = file[24:-8]
        tree = ET.parse(file)
        root = tree.getroot()

        for Tag in ['Kitkat', 'Snickers', 'Bounty']:
            iTag = '{textsem.ecore}' + Tag
            for country in root.findall(iTag):
                XMIID = country.get('{XMI}id')
                sofa = country.get('sofa')
                cursor.execute("INSERT INTO Tags (filename,tag,xmiid,sofa) VALUES (?,?,?,?)", filename, Tag, XMIID, sofa)

try:
   thread.start_new_thread( ExtractData, ("1") )
   thread.start_new_thread( ExtractData, ("2") )
except:
   print("Error: unable to start thread")

conn.commit()

A: Why not generate the list of files and then process them with a pool?
import multiprocessing

def ExtractData(file):
    filename = file[24:-8]
    tree = ET.parse(file)
    root = tree.getroot()

    for Tag in ['Kitkat', 'Snickers', 'Bounty']:
        iTag = '{textsem.ecore}' + Tag
        for country in root.findall(iTag):
            XMIID = country.get('{XMI}id')
            sofa = country.get('sofa')
            cursor.execute("INSERT INTO Tags (filename,tag,xmiid,sofa) VALUES (?,?,?,?)", filename, Tag, XMIID, sofa)

# if there are millions of files, you might want an iterator
filename_iterator = glob.iglob("H:/datas_Output/xmldata/", recursive=True)

with multiprocessing.Pool(processes=multiprocessing.cpu_count()) as pool:
    results = pool.map(ExtractData, filename_iterator)

A: Python multithreading isn't "real". For one thing, there's a "Global Interpreter Lock" (GIL) that only allows one thread to run py at the same time. Also, python threads don't use independent real processor cores. The main benefit is one thread may be blocked on external I/O operations; the other threads can do something.
However, in other environments such as JVMs (Java, Kotlin etc.) real threads are supported.


text:
Q: For small string hashes, should I use a deprecated algorithm like MD5 or the prefix of an algorithm like SHA256? I have 16 bytes to hold a string hash. I understand that collisions are a fact of life when you reduce strings of arbitrary length to a fixed-length sequence of bytes, but I'd like to avoid them as much as possible. Am I better off using a deprecated algorithm like MD5 that has an output of 16 bytes, or the first 16 bytes of a yet-to-be-broken algorithm like SHA-256?

A: Given that NIST defines SHA-224 as a truncated SHA-256, that's as official 'seal of approval' as you're ever going to get on the question "is it a good idea to truncate SHA-256 to fit size requirements?".
And since MD5 is utterly demolished and soon to join MD4 on the "don't use even for internal testing" shelf, the answer is pretty clear - go with a truncated SHA-256.
That being said, the moment you reduce it - the number of collisions will naturally increase. SHA-256 is statistically well spread so shortening shouldn't increase collisions more than what you get inevitably with only 128 bits (well, a bit more as no hash is perfect). Shortening will even come with a bonus of increasing already solid SHA-256 resistance to length extension attacks.
I know a lot of systems in the industry using halved SHA-512 for increased resistance to LAE (well, theoretical at this time) instead of SHA-256 - an additional bonus is performance boost on 64-bit systems when it comes to calculating SHA-512 vs SHA-256.
The most common form of truncation I've encountered is XOR-ing the first half with the second half. I'm not sure if it provides any additional benefits but people feel more at ease when they see 'unrecognizable' output from a 'truncator' so they just go with it.
UPDATE
As per deceze's suggestion - when a hash is qualified as "don't use even for internal testing" it means that it does a bad job for what it was designed to do and it should be avoided at all costs for that particular application but not necessarily for other applications.
Both MD4 and MD5 can be used as solid hashing algorithms in non-cryptographic settings, and I've seen systems re-purposing MD4 specifically for that - it's very fast, has a solid spread and if you're not too picky with collisions (say you're building a backup program that needs to know which files changed since the last backup) it can go head-to-head with some of the non-cryptographic hashes designed for those specific purposes.
However, more often than not, it's better to use the right tool for the job. Non-cryptographic hashes are designed first and foremost for speed, but also for spread and low collision rate, and some of them outshine even cryptographic hashes with their profile with only downside of being more or less predictable.
If you need a non-cryptographic hash, instead of resorting to broken cryptographic hashes, I'd suggest you take a look at some of the overall better hashes for non-cryptographic purposes like FNV-1/FNV-1a, Murmur and even plain CRC32 (a bit on the slow side, but faster than most cryptographic hashes). There is a really great comparison on speed, spread and collisions on SE so be sure to check it out.


text:
Q: md-dialog size Material for Angular 2 troubleshooting When I open a Material dialog (MdDialog.open(MyDialogComponent)), the dialog that opens spans the entire height of my screen.
When I remove height:100% from .md-dialog-container in Chrome inspector, the height is adjusted to fit the contents perfectly.
But the source code of md-dialog makes it look like this is intentional:
md-dialog-container {
  ...
  // The dialog container should completely fill its parent overlay element.
  width: 100%;
  height: 100%;
  ...
}

I've already removed Material for Angular 1 from my project to avoid CSS conflicts with Material for Angular 2. (The old css was making the width overly large too.)
What could cause this or how do I troubleshoot it?
My dialog component is simple:
<h2 md-dialog-title>...</h2>

<md-dialog-content>
   ...
</md-dialog-content>

<md-dialog-actions align="end">
  <button... />
</md-dialog-actions>

A: My page was missing <!DOCTYPE html>
https://github.com/angular/material2/issues/2351
See this answer for more info about dialogs:
Angular2 Material Dialog css, dialog size


text:
Q: Question about scalar product of 2 four-vectors I'm looking for help to prove that $\mathbf{a\cdot b}=-ab\ cosh \ \theta$, where:
$a=\sqrt{\mathbf{-a\cdot a}}$,
$b=\sqrt{\mathbf{-b\cdot b}}$, and
$cosh \ \theta$ is $\gamma$, for a Lorentz boost that would move you from a frame where a is at rest to a frame where b is at rest.
I started by ignoring the y and z coordinates, and expanding a, b, and $\gamma$ in terms of time, length, and velocity.  That gave me:
$(\sqrt{(a^t)^2-(a^x)^2}) \ (\sqrt{(b^t)^2-(b^x)^2}) \ (\frac{1}{\sqrt{1-V^2}})$
That left me scratching my head about what V is and I got totally derailed.  I couldn't figure out if V is the velocity associated with a Lorentz Transformation that would transform a into b, or whether I was supposed to somehow get a velocity from $\frac{b^x}{b^t}-\frac{a^x}{a^t}$, and in any event, all of these approaches seemed to be leading off into thickets of horrendous algebra, instead of towards the answer I want:
$\mathbf{a\cdot b}=-a^tb^t+a^xb^x$
(Yes, I have reviewed the earlier discussion of this issue but I couldn't follow it)

A: The proof of this identity is entirely analogous to how one would go about proving the Euclidean formula $\vec{a}.\vec{b} = |a||b| \text{cos}(\theta)$.
What one has to do is as follows:

*

*Find a matrix $M(\theta)$ such that $\vec{b} = M(\theta)\vec{a}$.

*Use the definition of the inner product $\vec{a}.\vec{b}$.

*Relate the two equations above to solve for $\theta$.

Let me sketch how to do it for the Minkowski space spanned by $(t,x)$, namely $\mathbb{R}^{1,1}$. The inner product between two vectors $a,b \in \mathbb{R}^{1,1}$ is given by $a.b = -a^0 b^0 + a^1 b^1$.
Let $a$ and $b$ be members of $\mathbb{R}^{1,1}$ for which there exists a matrix $\Lambda(\alpha) \in SO(1,1)$ and a constant $c$ such that $$b = c\Lambda(\alpha) a.$$ The matrix $\Lambda(\alpha)$ takes the standard form
$$\begin{pmatrix}
\text{cosh}(\alpha) & -\text{sinh}(\alpha) \\
-\text{sinh}(\alpha) & \text{cosh}(\alpha)
\end{pmatrix}$$
and one can get that $$c = \frac{|b|}{|a|}$$ by taking the norm of both sides and noticing that $\Lambda(\gamma)$ preserves the norm.
Then doing the procedure above one can reduce it to the desired equation.


text:
Q: How to get results of subcategories also?(WP Rest Api v2) We can get posts from a category using below request
    `/wp/v2/posts?categories=1&search=somequery`

It only gives results from category(1) only. How can we get results from category(1) and from all subcategories of category(1) also? Than You.

A: This answer has what you want https://wordpress.stackexchange.com/a/314152/49962
WP already does this out of the box thanks to the include_children parameter of tax_query which is true by default.
So you do not need to tell it the sub-terms, just do something like this:
/wp/v2/posts?categories=1

Where categories=1 is the parent category ID

A: You'll need to do an additional call to find the IDs of the subcategories – there is no way to get posts from subcategories by only including the parent category in the search.
/wp/v2/categories?parent=ID&per_page=0&

This call will return an array of category objects, grab the IDs of those objects and pass them to your request for posts:
/wp/v2/posts?categories=1,A,B,C,D&search=somequery


text:
Q: setUserProperty() sometimes is not updating. React Native setUserProperty() sometimes is not updating. I have the following code:
async componentDidMount(){

    // Set screen event name.
    this.props.screenProps.firebase.analytics().setCurrentScreen('Grocery Screen.'); // <-- This is updated correctly all the times

    // Log out that the menu wasn't opened to Firebase
    if(!this.categoryMenuWasOpened){
      await this.props.screenProps.firebase.analytics().setUserProperty('Category_Menu_Opened', 'No'); // This is **never** updated correctly
      console.log('Updated category menu "No".');
    }

    // Log out that the search bar isn't being used to Firebase
    if(!this.searchBarUsed){
      await this.props.screenProps.firebase.analytics().setUserProperty('Search_Bar_Used', 'No'); // <-- This is sometimes updated correctly
      console.log('Updated Search Bar "No".');
    }
  }

Why does this work sometimes? Am I calling in an inappropriate way the functions?


text:
Q: Storybook UI with CSS modules and Less Is it possible to use Storybook UI with React, CSS modules and Less? Have anyone managed to configure this kind of setup?

A: I had same case. Resolved by adding webpackFinal to .storybook/main.js :
module.exports = {
    stories: ['../src/**/*.stories.[tj]s'],
    webpackFinal: async (config, { configType }) => {
        config.module.rules.push(
            {
                test: /\.less$/,
                use: [
                    require.resolve('style-loader'),
                    {
                        loader: require.resolve('css-loader'),
                        options: {
                            modules: true,
                            importLoaders: 1,
                            localIdentName: '[name]__[local]___[hash:base64:5]'
                        },
                    },
                    require.resolve('less-loader')
                ]
            },
        );
        return config;
    },
};

A: Adding  .storybook/webpack.config.js helped me fix the issue, with
module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: ['style-loader'],
            }, {
                test: /\.css$/,
                use: {
                    loader: "css-loader",
                    options: {
                        modules: true,
                    }
                }
            }
        ],
    },
}

A: With sass as example:
Step 1: configure webpack in main.js. You can find documentation here: https://storybook.js.org/docs/configurations/custom-webpack-config/
const path = require('path');

module.exports = {
    webpackFinal: async (config, { configType }) => {
        // `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
        // You can change the configuration based on that.
        // 'PRODUCTION' is used when building the static version of storybook.

        // Make whatever fine-grained changes you need
        config.module.rules.push({
            test: /\.scss$/,
            use: ['style-loader', 'css-loader', 'sass-loader'],
            include: path.resolve(__dirname, '../'),
        });

        // Return the altered config
        return config;
    },
    stories: ['../stories/**/*.stories.js'],
};

Step 2: Install sass-loader
https://webpack.js.org/loaders/sass-loader/
Step 3: Create your scss files
@import "../stories/main.scss";

h1{color:$mediumBlue}

A: Modify your .storybook.main.js
module.exports = {
  stories: ['../src/**/*.stories.js'],
  addons: [
    '@storybook/preset-create-react-app',
    '@storybook/addon-actions',
    '@storybook/addon-links',
  ],
  webpackFinal: async (webpackConfig, { configType }) => {
    // `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
    // You can change the configuration based on that.
    // 'PRODUCTION' is used when building the static version of storybook.
    const { loadCracoConfig } = require('@craco/craco/lib/config');
    const { getCraPaths } = require('@craco/craco/lib/cra');
    const context = {env: process.env.NODE_ENV};
    const cracoConfig = loadCracoConfig(context);
    context.paths = getCraPaths(cracoConfig);
    const {overrideWebpackConfig} = require('@semantic-ui-react/craco-less');
    overrideWebpackConfig({
      context,
      webpackConfig
    });

    // Return the altered config
    return webpackConfig;
  },
};

This is taken from node_modules/@craco/craco/scripts/start.js

A: localIdentName option moved in css-loader configuration so this is the new configuration.
source: https://github.com/rails/webpacker/issues/2197#issuecomment-517234086
module.exports = {
  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  webpackFinal: async (config) => {
    config.module.rules.push({
      test: /\.less$/,
      use: [
        require.resolve('style-loader'),
        {
          loader: require.resolve('css-loader'),
          options: {
            importLoaders: 1,
            modules: {
              localIdentName: '[name]__[local]___[hash:base64:5]',
            },
          },
        },
        require.resolve('less-loader'),
      ],
    });
    return config;
  },
};


text:
Q: scraping wikimedia category trees I want to use R to scrape the links contained within a wikimedia category tree and the structure of the tree from here. The code below can open up all the collapsible bullet points
library(RSelenium)

rD <- rsDriver(check = FALSE)
remDr <- rD[["client"]]
remDr$navigate("https://commons.wikimedia.org/wiki/Category:Sports")

n <- 1
# n <- 10 # takes a long time to expand all bullet points
for(i in 1:n){
  b <- remDr$findElements(using = "css selector", "[title='expand']")
  for(i in 1:length(b)){
    b[[i]]$clickElement()
  }
}

... but i am struggling to build a data base that would look like...

I can get the bullet href and names using the code below, but i am struggling to find a way to indicate which level each bullet points refers too (i.e. how deep in the category tree each bullet point is)? I am thinking there might be a clever xpath method to count how many CategoryTreeChildren deep each bullet is but that is reaching well beyond my capabilities.
# for testing I manually expand the bullets for the first couple of branches
# (fully for Bulgaria women badminton, basketball) and the last possible
# branch rather than let the for loop run and run through multiple cycles.
library(tidyverse)
library(rvest)
s <- remDr$getPageSource()
d <- read_html(s[[1]]) %>%
  html_nodes("div#mw-subcategories") %>%
  html_nodes("div.CategoryTreeItem") %>%
  html_nodes("a") %>%
  map(xml_attrs) %>%
  map_df(~as.list(.)) %>%
  as_tibble()
# > d
# # A tibble: 135 x 2
#    href                                     title
#    <chr>                                    <chr>
#  1 /wiki/Category:Categories_by_sport       Category:Categories by sport
#  2 /wiki/Category:Categories_by_sport_by_c~ Category:Categories by sport by co~
#  3 /wiki/Category:Categories_of_Bulgaria_b~ Category:Categories of Bulgaria by~
#  4 /wiki/Category:Female_sportspeople_from~ Category:Female sportspeople from ~
#  5 /wiki/Category:Female_badminton_players~ Category:Female badminton players ~
#  6 /wiki/Category:Maria_Delcheva            Category:Maria Delcheva
#  7 /wiki/Category:Petya_Nedelcheva          Category:Petya Nedelcheva
#  8 /wiki/Category:Gabriela_Stoeva           Category:Gabriela Stoeva
#  9 /wiki/Category:Stefani_Stoeva            Category:Stefani Stoeva
# 10 /wiki/Category:Women%27s_basketball_pla~ Category:Women's basketball player~

I have also played around with the WikipediR package - it says in the package description that it can be used to retrieve elements of category trees but i cannot find an example of how to implement it.


text:
Q: Is it possible to show how bash globbing works by doing? I am teaching someone how bash globbing works. I would like to show (via some bash debugging feature if possible) how bash expands the patterns prior to invoking the command. For instance I would like to do the following:
ls -l file*.txt

Then I would like bash to show what the file*.txt expanded to:
ls -l file1.txt file2.txt file3.txt file4.txt

I know how to do this using bash -x from within a script but I would prefer to do it in the interactive shell so that I don't have to introduce ideas about scripts. Is there a way to do this in interactive mode?

A: You can simply echo the whole command:
echo ls -l file*.txt

A: Ok, so it's basically what I usually set in my .inputrc to get zsh like behavior in bash:
set show-all-if-unmodified on
set show-all-if-ambiguous on

Place the above lines in ~.inputrc and you're good to go. When doing something like ls *.txt just tab and it should glob everything for you and output the matching files.
EDIT: quotes from man bash:

show-all-if-ambiguous (Off)
This  alters the default behavior of the completion functions.  If set to On, words which have more than one possible completion cause the matches to be listed  immediately  instead  of  ringing  the bell.
show-all-if-unmodified (Off)
This alters the default behavior of the completion functions in a fashion  similar to show-all-if-ambiguous. If set to On, words which have more than one  possible  completion  without any  possible  partial  completion (the possible completions don't share a common prefix) cause the matches to be listed immediately instead of ringing the bell.

EDIT2: example output
$ ls *
books    dev    music   templates
$ ls *

Though it won't work if the one would try to expand the following (as it would try to complete the later argument ~/some/other/folder:
$ cd * ~/some/other/folder


text:
Q: Springboot logback not deleting old logfiles Im using logback with SpringBoot but can't get it to delete old log files.
I defined the following appender in my logback-spring.xml file:
    <appender name="app" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOGS}/app.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily and when the file reaches 10 MegaBytes -->
            <fileNamePattern>${LOGS}/archived/app-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- keep 10 days worth of history -->
            <maxHistory>10</maxHistory>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
    </appender>

Even though I set "maxHistory" and "cleanHistoryOnStart", logfiles that are older than 10 days aren't being deleted. Neither on RollOver nor on StartUp.
Everything else seems to work fine. The logfiles are RolledOver and renamed according to the defined Rules.
Am I doing something wrong here?

A: maxHistory is not about days, it is about number of files.  See http://logback.qos.ch/manual/appenders.html
and logback deletes the logs before the MaxHistory during hourly rollback

A: Okay I found out what the problem was and it seems to be just a misunderstanding on my part.
I had an application running that produced logs for about 2 months already before I actually added the  tag in my logback file.
My assumption was, that logback will just delete all those older logs automatically too when I start it. That doesnt seem to be case however.


text:
Q: run oncomplete event in async Is there someway of letting an oncomplete event run in Async. The oncomplete event is called from an external dll. The external dll uses Async and I am creating a wrapper for it that hides multithreading.
I Have tried using AutoResetEvents but these get stuck on the WaitOne as the oncomplete event which resets the AutoResetEvent only runs after the function is completed.
From what I can pickup from the external Dll, the object tree needs to be synced to the main form in order to function. This forces everything on a single thread. GetTag is called as GetTag(this).
protected EventWaitHandle SyncEvent;
public string GetTag(object syncObject)
    {
        string lResult = "";
        SyncEvent = new AutoResetEvent(false);
        XiServer lOPCServer = new XiServer(OPCServer.ServerID, OPCServer.ApplicationName, syncObject); //create local instance of server synced to mainform
        lOPCServer.Initiate(OnInitiated2, null); //Connect server
        SyncEvent.WaitOne(); //Wait here for for connect to finish, Freezes here

        if  (ServerTree == null)
            ServerTree = new ObjectTree(lOPCServer, lOPCServer.ServerInfo.ServerName);
        DialogResult dlr = ServerTree.ShowDialog();
        if (dlr == DialogResult.OK)
        {
            lResult =  ServerTree.SelectedObject.InstanceId.FullyQualifiedId;
        }
        lOPCServer.Dispose();
        return lResult;
    }
private void OnInitiated2(Exception aError, object asyncState)
    {
        if (aError != null)
        {
            GlobalException = aError;
        }
        SyncEvent.Set();
    }

So in short, is there someway I can let the code wait till after the Initiate was finsihed? I dont have access to the initiate code.

A: Okay I found away around this.
I keep checking a field that should be set last on on the initiate function.
On the server object I am using the isConnected field
while ((lOPCServer.IsConnected == false) && (lTimeout < 60000)) //1 min timeout
{
    Thread.Sleep(10);
    lTimeout += 10;
}

if (lTimeout >= 60000)
{
    return ""; //Server initaite timed out
}


text:
Q: Why does my single threaded hello world app use 22 OS threads? Out of curiosity I wrote Hello World and set a break point on my print statement.
public class Program
{
    public static void main(String[] args)
    {
        System.out.println("Hello");
    }
}

When the break point was hit, I pulled up Task Manager in windows to see how many threads were allocated by that JVM process. I was shocked to see 22.  Why are there so many threads spawned for this simple program?

A: The JVM utilizes some daemon thread (e.g. garbage collector, finalizer, etc...). However, in this case, attaching a debugger has actually created a few more threads to handle the debuggers connection.

A: As above says, there are many Daemon Threads runs always by JVM. To watch all your current running threads, open Java VisualVM in your JDK-->bin folder and go to Threads. There you can see all running, sleeping, wait and Monitor Threads.
Currently in my VisualVM, I have 19 Live Threads in which 15 are Daemon Threads.

A: Also, FYI, just discovered that the JVM will allocate at least n threads to GC where n is the number of cores.  Source: http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html#par_gc.  That explains 8 of mine.


text:
Q: Why does my sjoin() return me an emtpy GeoDataFrame? I'm trying to make a join between two GeoDataFrame.
The first one gathers the coordinates of points associated with a name.
The second one is a set of polygons based on the French cadastre.
I would like to be able to join the two GeoDataFrame based on their geographical relationships.
Based on an inner join, the names Melynn and Gaspard should be returned because they are associated with coordinates included in the polygons.
NB :They have the same crs : "EPSG:2154"
The first GeoDataFrame :
data{'Noms (z)'['Melynn','Paul','David','Gaspard'],'lat'[49.46138,49.4404591,49.4404591, 49.46138], 'long':[1.07948,1.0939658,1.0939658, 1.07948]}

df=pd.DataFrame(data)

pts=gpd.GeoDataFrame(df,geometry=gpd.points_from_xy(df['lat'],df['long'],crs="EPSG:2154"))

The second GeoDataFrame :
shapes = gpd.read_file("..\Data sets\cadastre-76-sections-shp\sections.shp")

subshapes = shapes[shapes['commune']=='76451']

The joint :
gpd.sjoin(pts, subshapes, how="inner", op="within")

This inner joint only return me an empty GeoDataFrame...

A: After getting a good night's sleep, I realized that my points were WGS84 (EPSG:4326) based coordinates so I had set them wrong.
I changed the coordinates and everything worked fine.


text:
Q: Issue with method onPause() if i Change orientation of device I inserted into onPause() a call to logout the user; but when i change the orientation of android device the method onPause is invoked same.
WHY? I don't need to invoke the method logoutUser if i turn the device to horizontal/portrait.

A: When we change the orientation of activity for example horizontal to portrait that time activity is recreated so according to android activity life cycle OnPause() method will get called.
To avoid invoke of method logoutUser you have to save current status of user using  onSavedInstanceState() method.
Refer this link for more understanding https://developer.android.com/training/basics/activity-lifecycle/recreating.html

A: By default Activity is recreated whenever we change the orientation of the phone. Check Handling Runtime Changes.

Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate())

The reason behind recreation is that the app may want to change the layout based on the new orientation.
But in most cases you don't need to recreate your Activity each time the user changes phone orientation since you can get callback on your Activity's onConfigurationChanged() and make the required layout changes. You can disable them by adding following line in your Activity tag within your AndroidManifest.xml file.
      android:configChanges="orientation|keyboardHidden|screenSize"


text:
Q: Артефакты изображения после обработки Обрабатывается изображение.
Сначала берётся исходное изображение. Я добавляю к каждому саб-пикселю шум.
После восстанавливаю от шума, вычитанием из саб-пикселя шума.
Но что то происходит не так.
До обработки изображения оно выглядит нормально :

После обработки появляются артефакты в некоторых засвеченных местах.

Вообще не понимаю, куда и как думать, в каком направлении. До этого была похожая проблема, но решалась сменой формата изображения с JPG на PNG.
В формате BMP проблема остаётся такой же.
Код обработки изображения:
for (int x = 0; x < WIDTH; x++) {
        for (int y = 0; y < HEIGHT; y++) {
            for (int z = 0; z < DEPTH; z++) {
                Color cryptColor = new Color(img.getRGB(x, y));
                img.setRGB(x, y, new Color(
                        overflowControl(cryptColor.getBlue(), reconstructedNoise[x][y][2], OPERATION_MINUS),
                        overflowControl(cryptColor.getRed(), reconstructedNoise[x][y][0], OPERATION_MINUS),
                        overflowControl(cryptColor.getGreen(), reconstructedNoise[x][y][1], OPERATION_MINUS)
                ).getRGB());
            }
        }
    }

Код вызываемого метода :
private static final int HIGH = 255;

private int overflowControl(int color, int noiseNumber, int operation) {
        switch (operation) {
            case OPERATION_PLUS: {
                if (color + noiseNumber > HIGH) {
                    return color + noiseNumber - HIGH;
                }
                return color + noiseNumber;
            }
            case OPERATION_MINUS: {
                if (color - noiseNumber < 0) {
                    return HIGH + (color - noiseNumber);
                }
                return color - noiseNumber;
            }
        }
        return -1;
    }

P.S. Вы можете подумать, что проблема в несоответствии порядка извлечения и установки цветов. Возможно вы правы, но по факту [так и задумано] цвета остаются идентичными, кроме как некоторых участков.

A: Решилось всё математическим анализом того, что я написал.
Анализом функции нескольких переменных, а конкретно моей функции контроля переполнения числа, отвечающего за яркость сабпикселя - Z = f(X,Y), где X - значение цвета, а Y - значение шума на области определения X[0; 255], Y[0;255], Z[0;255].
Грубо говоря все ошибки были в расчётах метода overflowControl
При этом сначала возникали артефакты на ярких местах, то есть проблема была в неправильной коррекции числа на высоких яркостях.
После устранения точек прерывания функции возникла другая проблема..
После начали возникать артефакты на тёмных областях.
После устранения точек прерывания функции на низких яркостях всё прошло успешно.
Вот итоговый код:
private int overflowControl(int color, int noiseNumber, int operation) {
    switch (operation) {
        case OPERATION_PLUS: {
            if (color + noiseNumber > HIGH) {
                if(color == HIGH && noiseNumber != LOW) {
                    return noiseNumber - 1;
                }
                return color + noiseNumber - HIGH - 1;
            }
            return color + noiseNumber;
        }
        case OPERATION_MINUS: {
            if (color - noiseNumber < LOW) {
                if (color - noiseNumber == -1) {
                    return HIGH;
                }
                return HIGH + (color - noiseNumber) + 1;
            }
            return color - noiseNumber;
        }
    }
    System.out.println("-1 => error overflowControl");
    return -1;
}


text:
Q: How do I align one widget to the top of the screen and center another widget to the middle of the screen in Flutter? Within the same body I'm trying to align one widget to the top of the screen and another to the center of the screen. This is proving difficult.
Here is my code:
body: Column(children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              color: Colors.redAccent,
              width: screenWidth,
              height: 50.0,
              child: Center(
                child: Text(
                  "Hello World!",
                  style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              color: Colors.blueAccent,
              width: screenWidth,
              height: 50.0,
              child: Center(
                child: Text(
                  "Thanks for the help!",
                  style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ]),

When this code is run in my Xcode simulator this is the result:
https://i.imgur.com/JtPKyq0.png
So to be clear this result is wrong because I want the blue container to be at the center of the screen, not the top.
Thanks in advance for any help!

A: One option is to use an Expanded widget. This widget will expand fill all the space available in the parent, and then you center the child inside it. Note that this only works inside Flex widgets, like Row, Column etc.
In your case, I also recommend removing the screenWidth variable for the row width, and use the Expanded widget to make the container fill the screen horizontally.
This is the final code:
body: Column(children: <Widget>[
    Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Expanded( //makes the red row full width
          child: Container(
            color: Colors.redAccent,
            height: 50.0,
            child: Center(
              child: Text(
                "Hello World!",
                style: TextStyle(
                  fontSize: 18.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    ),
    // This expands the row element vertically because it's inside a column
    Expanded(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          // This makes the blue container full width.
          Expanded(
            child: Container(
              color: Colors.blueAccent,
              height: 50.0,
              child: Center(
                child: Text(
                  "Thanks for the help!",
                  style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  ]
),


text:
Q: Disable paste in uitextfield in iOS5 I'm attempting to disable paste in a textfield using the following code:
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {

  if ([UIMenuController sharedMenuController]) {

    [UIMenuController sharedMenuController].menuVisible = NO;

  }

  return NO;
}

I've this code in other projects and its worked, however in my current project it just gets called multiple times and then displays the paste menu item.
This only thing that I can see that is different is that in this project the viewcontroller where the above code lives is the child of a custom viewcontroller.
EDIT
It's not showing the menu option when I run it with in the simulator with iOS4.3 as opposed to iOS5

A: I got there in the end. Instead of placing the code into the viewcontroller, i subclassed UITextField and placed it in there and it works.
I based it on the example here:
How do you REALLY remove Copy from UIMenuController


text:
Q: How to show taxonomy meta on frontpage? For a website I am developing I have come across the following challenge.
I have made a custom taxonomy "blog" (associated with both the Post-post_type and the User-object_type). With the taxonomy meta plugin I have added a meta field image. On the taxonomy archive page I output the taxonomy term name, description and this image.
On the front_page of this site I want to list all Blogs and I would like to do that in such a way that it again shows that taxonomy meta image.
I already have managed to show the blogs with title (link) and description, using the last example on the Codex entry:
/* List all blogs, source example 2: http://codex.wordpress.org/Function_Reference/get_terms#Examples */
$args = array( 'taxonomy' => 'blog', 'orderby' => 'name', 'order' => 'ASC', 'fields' => 'all' );

$terms = get_terms('blog', $args);

$count = count($terms); $i=0;
if ($count > 0) {
    foreach ($terms as $term) {

        $i++;

        $term_list .= '

slug . '/" title="' . sprintf(__('View all articles in %s Blog', 'wys'), $term->name) . '">' . $term->name . '

' . $term->description . '
';
        if ($count != $i) $term_list .= '
'; else $term_list .= '';
    }
    echo '
' . $term_list . '
';
}

The code I used to show the image on the blog taxonomy archive comes straight from Rilwis' website (all the way at the bottom):
$queried_object = get_queried_object();
$term_id = $queried_object->term_id;

$meta = get_option('blog_image'); //meta_id
    if (empty($meta)) $meta = array();
    if (!is_array($meta)) $meta = (array) $meta;
        $meta = isset($meta[$term_id]) ? $meta[$term_id] : array(); //term_id
        $images = $meta['blogimg']; //field_id
            foreach ($images as $att) {
                // get image's source based on size, can be 'thumbnail', 'medium', 'large', 'full' or registed post thumbnails sizes
                $src = wp_get_attachment_image_src( $att, 'thumbnail' );
                $src = $src[0];
                // show image
                echo '

';
            }

echo '
';

    $description = term_description();
    if ( $description ) { // Show Blog taxonomy term description
        echo $description;
    } //endif

    $meta = get_option('blog_image'); //meta_id
        if (empty($meta)) $meta = array();
        if (!is_array($meta)) $meta = (array) $meta;
            $meta = isset($meta[$term_id]) ? $meta[$term_id] : array(); //term_id
            $value = $meta['blog_authors']; //field_id
            echo '
' . __( 'Author(s): ', 'wys' ) . $value . '
'; // if you want to show

echo '
';

The difficulty to do this on the homepage too is that I seem to have to combine two foreach calls and that is a little bit too complex territory for me.
For whomever want to have a visualization, I have made available on my staging server the homepage and one of the blog archives.
Any tips and/or nudges in the right direction are appreciated!
Thanks

A: Over at Google+ I posted the same question and credits go to Alexander Conroy for coding up the correct solution:
/* List all blogs, source example 2: http://codex.wordpress.org/Function_Reference/get_terms#Examples
 *
 * credits Alexander Conroy - https://plus.google.com/u/0/113053085239726972447
*/
$terms = get_terms('blog', $args);
$blog_image_meta = get_option('blog_image');

if (!empty($terms)) {
    foreach ($terms as $term) {
        $meta = isset($blog_image_meta[$term->term_id]) ? $blog_image_meta[$term->term_id] : array(); //term_id
        $image = array_shift(wp_get_attachment_image_src( array_shift($meta['blogimg']), 'thumbnail' ));

        $term_list .= '

slug . '/" title="' . sprintf(__('View all articles in %s Blog', 'wys'), $term->name) . '">' . $term->name . '

' . $term->description . '

';
        }
    echo '
' . $term_list . '
';
}


text:
Q: Can the parent class see a child classes protected variables? I'm very fuzzy on how inheritance works and just want to make sure that I'm looking in the right direction.
From my understanding I understand that

*

*public variables are accessible by all packages,

*default within the single package,

*private within only the class,

*and protected with sub-classes.

I know that child classes can see parent class's protected variables.
My question: Does it work the other way around?

A:
Does it work the other way around?

No, not if they're not in the same package. According to the table in the Java access control tutorial, protected exposes the member to subclasses and other classes in the same package, not superclasses:

                  Access Levels
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Modifier     Class  Package  Subclass  World |
| public         Y       Y        Y       Y    |
| protected      Y       Y        Y       N    |
| no modifier    Y       Y        N       N    |
| private        Y       N        N       N    |
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

And from the JLS:

6.6.2. Details on protected Access
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

The superclass isn't responsible for the implementation of the subclass object.
You can test it yourself:
b/Base.java:
package b;

import a.Example;

public class Base {
    public static void showAnswer(Example e) {
        System.out.println(e.answer); //
    }
}

a/Example.java:
package a;

import b.Base;

public class Example extends Base
{
    protected int answer = 42;

    public static void main(String[] args)
    {
        Example e = new Example();
        Base.showAnswer(e);
    }
}

Trying to compile that fails with:

./b/Base.java:7: error: answer has protected access in Example
        System.out.println(e.answer); //
                            ^
1 error

A: If you think about it, what you are asking does not make too much sense. Consider this:
public class A {
    public void doSomething() {
        // This is not actually possible!!!
        bField = 12;
    }
}

public class B extends A {
    protected int bField;
}

public class C extends A {
     // ... whatever except bField...
}

...
A aInstance = new C();
// What should happen here? a C does not have a bField!!!
aInstance.doSomething();

A:
As you see its possible from subclasses not superclasses
You can read offical documentation
  here

A: Does it work the other way around?
No unless they are in the same package


text:
Q: How to close the container  from the inner page? I have the following structure :
My page opened in a frame like this :

Title

//My Page opened here

....

Now i wanna from a linkbutton in my page to close the container (div id="ajaxbox")
How to do this ?

A: Write a javascript function that closes the div in your parent page.
jQuery example:
function CloseDiv()
{
    $("#ajaxbox").hide();
}

in on your link button call a client script:
<asp:linkbutton id="LinkButton1"
       text="Close Me"
       onclientclick="parent.CloseDiv()"
       runat="Server" />


text:
Q: Making a function that adds delayed callback to any function? I want to have a function that can add callback to any function with a delayed timing.
Lets say I have a function :
 function name(val) {
   document.write(val);
 };

Now, adding delayed callback to it ( I don't know what will be the script but I assume it to be called like this ) :
 addCallback( function() {
    name("Arc"); // The Main Function
 }, function() {
    alert("Done"); // The Callback Function
 }, 1000 // alert will execute only after 1000ms + execution time of the name() function
 );

I found many example in which adding a callback was explained but not delayed callback with timeout + execution time as the delayed time ! Can this be done ?
Thanks In Advance

A: I assume you're looking for something like this?

function name(val) {
  document.write(val);
}

function addCallback(main, callback, ms) {
  return function() {
    main();
    setTimeout(callback, ms);
  };
}

var nameWithCallback = addCallback(function() {
  name("Arc");
}, function() {
  console.log("Done");
}, 1000);

nameWithCallback();

It doesn't add the callback to the existing function (that's impossible), but it returns a new function which calls the existing function and sets a timeout if the existing function doesn't throw an error.


text:
Q: How to pass a jQuery selector using apply()? Using apply() is converting a jQuery selector into a DOM element by using the [0] item of the selector array.
I've created an invoke function to call multiple functions all using the same context:
function func1(){
    // do something with 'this'...
}

function func2(){
    // something else with 'this'...
}

function func3($msg){
    try{
        alert($msg.text());
    }catch(err){ alert(err); }
}

function invoke(context, funcs, params){
    funcs.forEach(function(func){ func.apply(this, params); }.bind(context));
}

invoke(this, [func1, func2, func3], $('#msg'));

here's the jsFiddle
Thanks in advance.

A: The apply method expects an array as a second parameter, so this:
func.apply(this, [params]);

should work as expected. Or you can simply use call() instead:
func.call(this, params);

function func1(){
    // do something with 'this'...
}

function func2(){
    // something else with 'this'...
}

function func3($msg){
    try{
        alert($msg.text());
    }catch(err){ alert(err); }
}

function invoke(context, funcs, params){
    funcs.forEach(function(func){ func.apply(this, [params]); }.bind(context));
}

invoke(this, [func1, func2, func3], $('#msg'));

Hello

https://jsfiddle.net/doqm4sf5/4/

Did you want to use call() instead?

function func1(){
    // do something with 'this'...
}

function func2(){
    // something else with 'this'...
}

function func3($msg){
    try{
        alert($msg.text());
    }catch(err){ alert(err); }
}

function invoke(context, funcs, params){
    funcs.forEach(function(func){ func.call(this, params); }.bind(context));
}

invoke(this, [func1, func2, func3], $('#msg'));

Hello


text:
Q: Extremely uneven cloud service load-balancing with Azure I'm utilizing Azure for hosting a cloud service, which I recently modified to be scalable across multiple instances, including a session caching worker role. My question is, why would I be seeing extreme load (upwards of 90%) on one instance, but not on other instances (15-20% across all other instances)? Should I be worried?
Before I set up load balancing and when my single instance hit upwards of 95% load, it would slow to a crawl --- becoming unusable. Is there any way to ensure that I don't have any users experiencing this because they're somehow round-robin'd onto the overloaded instance?

A: We found we had a similar type of situation when one load-balanced instance failed over; what we were seeing is that all the load transferred, but wouldn't balance out again. We found that turning off keep-alive for a couple of minutes let the load spread again, after which we could turn it back on.
http://technet.microsoft.com/en-us/library/cc772183(v=ws.10).aspx

A: Well... azure load balance is based on round robin... so the distribution should be almost equal (something like 60-40 or even 70-30 is still acceptable)... so just to be sure: Are you sure your not using IIS "redirect" (I forgot the name of the feature) that would set sticky session?
I must say that without further details about what your site actually "do and how" it's quite hard to advice... I must say that this behavior is strange, but it's not clear that it is the load balancer fault...
Edit1: I would suggest that you further exam what is the 90% guy is doing by tracing it's activities... maybe you're out-of-luck and the requests that will cause heavy load are falling into that machine and the ones that will be quickly worked are being worked by the other one... Another thing that might be happening is that something might be stucked (maybe a infinite-loop)... if you implemented a scalable architecture I would recommend that you provision another machine and kill the one that is suffering...
Edit2: A simple way to verify that the load balancer is working is: Log remotely to the service machines and replace something like a image that is displayed on the main page (something that you can easily spot just by looking to the page). On server 1 put lets say a yellow image and on server 2 a red image (ok... maybe something not this drastic but you get the point...). Then keep loading the page again and again...


text:
Q: raise custom exception in python I could not get what is wrong with the code ? when I execute nothing happens. I am expecting my custom error message.
def testing():
  try:
    raise Exception('My error!')
  except:
    pass

testing()

A: You are raising an exception successfully. But you are catching that with try/except block. So nothing happens unless you describe it in except block.

A: You are successfully raising an error. And the try/catch statements sees it, and goes to catch as you have raised an error.
To fully customize errors you can declare them as so:
class CustomError(Exception):
    pass
raise CustomError("An error occurred")

results in
__main__.CustomError: An error occurred


text:
Q: Export your data with VEEML How to export data from a VEEML story? Basically, I would like to export some dimensions and metrics on my universe to load it in Excel.

A: VEEML embeds a query module in every story. With this module, you can query the Dataview without any IT knowledge, in a few clicks.
1/ Click on the "QUERY" button at the top of the story. The Query window opens.
2/ Click on each dimension and metric you want to export. You can also choose to pivot the time dimension in columns and even add evolutions.
3/ Validate by clicking on "APPLY"
4/ Once the grid is displayed, just click on the CSV Export button above the grid.
Results can be downloaded in CSV.


text:
Q: JQuery (only about CSS ) DataTable plugin's layout positioning
At the picture above there's a 'search' box on the upper-right, which part of the following codes that manage it ? :
https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css
https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js
I try it again and again , but i couldn't find it, i tried to inspect the elements but have no idea what' i'm doing. I really appreciate your help, thanks.

A: If you want to change where the search box is rendered you can use the "dom" option to define a template of what and where things render. See here for an explanation (f is the character used for the search box).
If you want to target the search box in your CSS you can use the .dataTables_filter selector. This is the wrapping element for the search box and contains the actual search input.


text:
Q: Is it safe to keep all of our php functions in 1 files and then include it in all the other files? I am creating a PHP website and it contains several sections, I was wondering is it safe to keep all of my functions in 1 file and then include it in every other file?
It would certainly make things easier for me but do you think it's a good idea? In both security aspects and speed. Because if I keep all my functions in a single page it would definitely become quite big, and I wouldn't be needing a lot of them in a lot of pages, so, wouldn't it affect my script's speed?
And do you think it's wise to keep all of them together? Aren't I just making it easier for hackers to find the core of my script? What do you suggest I should do?

A: Security-wise, it is safe as long as the file is kept under the right permissions.
It is not the best practice, and I guess you should take a look at php's autoload

A: Big, long functions files were (and still are, to an extent) pretty common in PHP projects.
Security of all files should certainly be a consideration, but a single functions file is no different from any other, really. Best practice is to keep it outside of your web root so that if PHP fails (it happens), your file still won't be accessible. If the server gets hacked, the location and format of your files is unlikely to make any difference.
Modern frameworks typically include hundreds of different files on every page load. The extra time this takes is barely measurable and probably not worth thinking about.
For maintainability, it's rarely a good idea to have one massive file. You should look at separating these into utility classes and autoload them as needed.

A: Security has nothing to do with the size of file.
You just need to make it inaccessible (which you can do it by .htaccess) and hidden by public (keep it outside of the web root)
And, what about the speed ?
I think it's nicer to get the files organized as specific as possible.
If there are many of tiny functions, you can organized it by its shared characteristics (maybe string functions, array functions, etc)
The time overhead is very very small and can be negligible.
And, I think maintainability is much more important than that negligible performance difference.


text:
Q: What is the proper way to remove a reference using the .NET 4 Entity Framework? I have an instance of TPM_PROJECTVERSION called projectVersion, which has a property called TPM_USER5 which is of type TPM_USER.  A TPM_PROJECTVERSION can have zero or one TPM_USER5 references (Sorry, I didn't come up with these names.)
When the user clicks a Delete button, I want to remove this reference, thus setting the column in the database to null.  I've tried the following:
projectVersion.TPM_USER5 = null;

However, when I call context.SaveChanges(), the column is not updated and nothing happens.  Under the debugger, I can see that projectVersion.TPM_USER5 is indeed null, and I also see that projectVersion.TPM_USER5Reference.IsLoaded is true.  I've also tried:
context.DeleteObject(projectVersion.TPM_USER5);

If I do this, when I call context.SaveChanges(), I get the exception:

{"ORA-02292: integrity constraint
  (TPMDBO.TPM_PROJECTCHANGES_TPM_US_FK1) violated - child record found"}

I'd be happy to post more information about the entity mappings, but not sure exactly what's relevant.  Any ideas?

A: If I understand correctly thus you removing only navigation property (TPM_USER5). Try set primitive property (TPM_USER5ID? - probably your db column name) to null.
Each navigation property must have relevant primitive property (not POCO entities) and you can use both to associate user to TPM_USER5 (primitive property - set id, navigation property - set reference).


text:
Q: Cannot find module 'gulp-sass ionic2 Framework When i Try to add Android platform in my first ionic Project
this error occurs What is the problem here
Looks like you're missing a module in your gulpfile:
Cannot find module 'gulp-sass


text:
Q: Sonata Media Bundle : How to set the default value of a media field? I'm currently Sonata Media Bundle for my project.
In one of my Entity Form Type that has some Media fields, I added these fields :
<?php
$builder
    ->add('image', 'sonata_media_type', array(
        'provider' => 'sonata.media.provider.image',
        'context' => 'projects',
        'label' => 'Project image',
        'required' => true

    ))
    ->add('video', 'sonata_media_type', array(
        'provider' => 'sonata.media.provider.vimeo',
        'context' => 'projects',
        'label' => 'Vimeo video',
        'required' => true
    ));
?>

As you can see, my two fields are required. However, when I add a media and save the entity, and then when I want to edit it, I don't have the related media as the "default" value as it should be set, generating my HTML5 required warning when trying to saving my edited entity with no new values in my media fields.

*

*Is it the expected behavior? I tried to use a workaround with a PRE_SET_DATA FormEvent that would set the media fields as unrequired when there is existing data, but I don't think it's a good way to handle this

*How to set the existing value of the media fields in entity edit forms?

Thank you for your help.


text:
Q: combine rows into one row in tsql let's say I have:
User     Email
 1       abc@email.com
 1       efg@email.com
 1       xyz@email.com
 2       aaa@email.com
 2       bbb@email.com
 3       ccc@email.com

and I want the output:
 User     Eamil1            Email2          Email3
 1        abc@email.com     efg@email.com   xyz@email.com
 2        aaa@email.com     bbb@email.com
 3        ccc@email.com

I found other answers about using FOR XML Path, but that's not what I want. it combines rows into one column, and separate the values with ';'
I also tried JOIN the table with itself, and it's also not the result I want.
Any help is appreciated.

A: Try something like this. Pivot is not a good solution in this case. Pivot is not efficient for non numeric values.
WITH C AS(
    SELECT
    RANK() OVER (PARTITION BY [User] ORDER BY Email) AS [Rank]
    ,[User], Email
    FROM Emails
)
SELECT [User]
    ,MIN(CASE C.[Rank] WHEN 1 THEN Email END) AS [Email1]
    ,MIN(CASE C.[Rank] WHEN 2 THEN Email END) AS [Email2]
    ,MIN(CASE C.[Rank] WHEN 3 THEN Email END) AS [Email3]
FROM C
GROUP BY [User]

A: You should look into the PIVOT command.
http://www.oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php


text:
Q: Download with URLSession and Operation queue does not start next operation when application is in background Use case : Download file from a server via one API which will give the download server url(download server url vality is for 10 secs only).
I have enabled the background capabilities.
Then created one Download Manager which holds the OperationQueue for download data task.
In Operation class when main() function calls, I have makes the API call which will return the download server URL and started a download.
Works fine in debug mode but does not work in release mode.
Download Manager :
final class SCDownloadManager: NSObject {

    @objc static var shared = SCDownloadManager()
    private override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(SCDownloadManager.networkDidChange(_:)), name: NSNotification.Name.init(NetworkConnectionChanged), object: nil)
    }

    /// Dictionary of operations, keyed by the `Download URL` of the `URLSessionTask`
    fileprivate var operations = [URL: SCDownloadOperation]()
    fileprivate var serverURLRequestMap = [URL: SCDownloadOperation]()

    /// Serial NSOperationQueue for downloads
    private let queue: OperationQueue = {
        let _queue = OperationQueue()
        _queue.name = "SCDownloadManagerQueue"
        _queue.maxConcurrentOperationCount = 3
        return _queue
    }()

    /// Delegate-based NSURLSession for DownloadManager
    lazy var downloadSession: URLSession = {
        let configuration = URLSessionConfiguration.background(withIdentifier: "com.xyz.background.download")
        let sessionQueue = OperationQueue()
        return URLSession(configuration: configuration, delegate: self, delegateQueue: sessionQueue)
    }()

    lazy var dataSession: URLSession = {
        let configuration = URLSessionConfiguration.background(withIdentifier: "com.xyz.background.url")
        let sessionQueue = OperationQueue()
        return URLSession(configuration: configuration, delegate: self, delegateQueue: sessionQueue)
    }()

    @discardableResult
    @objc func addDownload(_ downloadRecord: DownloadRecord) -> SCDownloadOperation {
        let operation = SCDownloadOperation(withDownloadRecord: downloadRecord)
        operation.delegate = self
        operations[downloadRecord.downloadUrl] = operation
        queue.addOperation(operation)
        return operation
    }

    /// Cancel all queued operations
    @objc func cancelAll() {
        queue.cancelAllOperations()
    }

    @objc func networkDidChange(_ notification: Notification) {
        if let reachability = notification.object as? Reachability {
            if reachability.currentReachabilityStatus() == NotReachable {
                cancelAll()
            }
        }
    }

}

//MARK:- Download operation delegate

extension SCDownloadManager: SCDownloadOperationDelegate {
    func getServerDownloadUrl(forRequest request: URLRequest, ofOperation operation: SCDownloadOperation) {
        if let url = request.url {
            serverURLRequestMap[url] = operation
        }
        self.dataSession.downloadTask(with: request).resume()
    }
}

// MARK: URLSessionDownloadDelegate methods

extension SCDownloadManager: URLSessionDownloadDelegate {

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

        guard let sourceURL = downloadTask.originalRequest?.url else { return }
        if session == dataSession {
            if FileManager.default.isReadableFile(atPath: location.path) {
                if let data = FileManager.default.contents(atPath: location.path) {

                    if let downloadOperation = serverURLRequestMap[sourceURL] {

                        if let serverUrl = String(data: data, encoding: .utf8), let downloadServerUrl = URL(string: serverUrl) {
                            self.operations.changeKey(from: downloadOperation.downloadRecord.downloadUrl, to: downloadServerUrl)
                            downloadOperation.downloadRecord.downloadUrl = downloadServerUrl
                            if let url = downloadOperation.downloadRecord.downloadUrl {
                                downloadOperation.downloadRecord.downloadTask = downloadSession.downloadTask(with: url)
                                downloadOperation.downloadRecord.downloadTask.resume()
                            }
                        }
                    }
                    do {
                        try FileManager.default.removeItem(at: location)
                    } catch {
                        print("error while removing file from default location")
                    }
                }
            }
        } else {
            operations[sourceURL]?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
        }

    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        if session == self.downloadSession {
            guard let sourceURL = downloadTask.originalRequest?.url else { return }
            operations[sourceURL]?.urlSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
        }
    }
}

// MARK: URLSessionTaskDelegate methods

extension SCDownloadManager: URLSessionTaskDelegate {

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        if downloadSession == session {
            DispatchQueue.main.async {
                if let completionHandler = Constants.appDelegate.backgroundTransferCompletionHandler {
                    Constants.appDelegate.backgroundTransferCompletionHandler = nil
                    completionHandler()
                }
            }
        }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)  {
        guard let sourceURL = task.originalRequest?.url else { return }
        if session == dataSession {
            if error == nil {

            } else {
                print("got error while doing API on download task")
            }
        } else {
            operations[sourceURL]?.urlSession(session, task: task, didCompleteWithError: error)
            operations.removeValue(forKey: sourceURL)
        }
    }
}

Operation Class :
class SCDownloadOperation: SCAsynchronousOperation {

    let downloadRecord: DownloadRecord
    var getServerDownloadUrl: ((URLRequest)->Void)?
    weak var delegate: SCDownloadOperationDelegate?

    init(withDownloadRecord dr: DownloadRecord) {
        downloadRecord = dr
        super.init()
    }

    override func cancel() {
        if let task = downloadRecord.downloadTask{
            task.cancel()
        }
        super.cancel()
    }

    override func main() {
        switch downloadRecord.downloadDataType {
        case DOWNLOAD_DATA_TYPE_CONTENT:

            let configuration = RequestConfiguration(withMethodType: .GET, urlString: downloadRecord.downloadUrl.absoluteString)
            if let request = NetworkManager.sharedInstance.urlRequest(forRequestConfiguration: configuration) {
                delegate?.getServerDownloadUrl(forRequest: request, ofOperation: self)
            }

        default: break
        }

    }
}

// MARK: NSURLSessionDownloadDelegate methods

extension SCDownloadOperation: URLSessionDownloadDelegate {

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        downloadRecord.progress = 1

        switch downloadRecord.downloadDataType {

        case DOWNLOAD_DATA_TYPE_CONTENT:
            processDownloadFinish(atLocation: location)

        default: break
        }
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

        downloadRecord.isExecuting = true
        downloadRecord.isDownloadProgressAvailable = true

        let downloadProgress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        downloadRecord.progress = downloadProgress
        downloadRecord.percentComplete = ((Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))*100)
        downloadRecord.downloadProgress = downloadProgress

        switch downloadRecord.downloadDataType {

        case DOWNLOAD_DATA_TYPE_CONTENT:
            updateWrittenData()

        default: break
        }
    }
}

// MARK: NSURLSessionTaskDelegate methods

extension SCDownloadOperation: URLSessionTaskDelegate {

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)  {
        completeOperation()
        if error != nil {
            print("\(String(describing: error))")

            switch downloadRecord.downloadDataType {

            case DOWNLOAD_DATA_TYPE_CONTENT:
                contentDownloadFail()

            default: break
            }
        }
    }
}


text:
Q: Сделать код на Python Итак, мне нужно сделать код, но у меня не получается если что Python.
Есть такой вариант:
n = int(input('Введите кол-во цифр ' ))
print(*sorted(int(input()) for _ in range(n)))

он впринципе рабочий но мне надо сделать подругому, а именно:
Мы задаём N тоесть количество чисел которое мы можем ввести,
далее мы вводим в строку тоесть цифры не как цифры а как слова и вводим эти цифры и потом эти числа сортируем. Не используя списки. Помогите ;)

A: ну как вариант:
print(*sorted(input().split()))

правда split() скрыто создаёт список, но в явном виде - нет :)
можно так:
text = '1 4 2 6 -2'
print(*sorted(map(int, text.split())))

результат map - это не список, а просто итерируемый объект
P.S.
вместо text просто используйте input(), я статические данные использовал просто чтобы не вводить каждый раз текст

A: Мы задаём N
N = int(input())

каждое число создавалась отдельная переменная и числа как слова
for i in range(N):
  globals()['num'+str(i)] = input()

в итоге будут переменные num0...numN. сортировать их конечно можно, но только пузырьком скорее...
movs = True
while movs:
  movs = False
  for i in range(N-1):
    if globals()['num'+str(i)] > globals()['num'+str(i+1)]:
       movs = True
       globals()['num'+str(i)], globals()['num'+str(i+1)] = globals()['num'+str(i+1)], globals()['num'+str(i)]

вывод итога также как ввод
for i in range(N):
  print(globals()['num'+str(i)])


text:
Q: Question on finite Vector Spaces, injective, surjective and if $V$ is not finite Let $V$ be a vector space and $\alpha \in \operatorname{End}(V)$
(i) If $V$ is finite dimensional, then $\alpha$ is injective iff $\alpha$ is surjective.
(ii) Give example showing (i) is false if $V$ is not finite dimensional.
So on (i), since $V$ is finite dimensional, then $V$ has a basis with finite cardinality and hence $\dim(V)=n$. Also, the following holds, $\dim(V)=\dim(\ker(\alpha) + \dim(\operatorname{im}(\alpha))$ Since $\alpha$ is injective, then the $\ker(\alpha)$ is $0$ which implies that the $\dim(\ker(\alpha)$ is $0$ which implies that $\dim(\operatorname{im}(\alpha))=\dim(V)$ and that shows that $\alpha$ is surjective. (Is that right?)
On the second one, (ii), I just have no idea. I mean shouldn't Axiom of Choice be able to work here?

A: The statements (i) and (ii) illustrate that finite-dimensional vector spaces behave in a way similar to finite sets, for a map $X \to X$ on a finite set is injective iff it is surjective. However, if $X$ is an infinite set there are maps that are injective but not surjective (e.g. $\mathbb N \to \mathbb N, x \mapsto x+1$) and vice versa (e.g. $\mathbb N \to \mathbb N, x \mapsto \max\{1,x-1\}$). You can turn this into a counterexample for the corresponding statement for vector spaces: let $V$ be the vector space freely generated by $\mathbb N$, i.e. the vector space of sequences $(a_1,a_2,\ldots) \in k^{\mathbb N}$ where $a_i =0$ for all but finitely many $i$ and consider the linear maps induced by the above maps, i.e.
$$(a_1,a_2,\ldots) \mapsto (0,a_1,a_2,\ldots)$$
and
$$(a_1,a_2,\ldots) \mapsto (a_1+a_2,a_3,a_4\ldots)$$
respectively. The first map is injective but not surjective, and vice versa for the second map.

A: The second one does not fail because the axiom of choise,
you used the fact the the dimension of the space is finite.
A counter example: $V$ is the space of the the polynomials with coefficients
in $\mathbb{R}$ and $T$ is defined by $$T(x^{i})=x^{i+1}$$ (that
is $1\mapsto x,x\mapsto x^{2}$ etc' ).
In this case $T$ is clearly $1-1$ but not onto since $1$ is not
in the image of $T$
Note $1$: We have that $$dim(Im(T))+1=dim(V)$$ but still $dim(Im(T))=dim(V)$
because both are not not finite, this is what fails.
Note $2$: we defined $T$ on a basis for $V$ so it's well defined.

A: We don't need AC here. Take the following vector space
$$ V:=\left\{\,\{a_n\}_{n=1}^\infty\subset \Bbb R\,\right\} $$
of all the real sequences, with coordinatewise operations (addition and multiplication by scalar), and define
$$\phi:V\to V\,\,,\,\,\phi(\{a_n\}):=\{0,a_1,a_2,...\}$$
Then, it is easy to check that $\,\phi\,$ is a $\,1-1\,$ linear transformation, yet it clearly is not surjective.


text:
Q: Java Factory pattern - How to prevent anonymous subclasses I'm doing a school assignment where I have to implement the Factory pattern. I have come a long way, but there is one last thing I have not been able to get working.
I have the following classes:
//Human.java
package human;
public abstract class Human{
    public static Human create(String namn, String pnr){
        char nastsist_char = pnr.charAt(9); // takes second last char in pnr
        String nastsist_string = Character.toString(nastsist_char);
        float siffra = Float.parseFloat(nastsist_string);   //Converts to float
        if ((siffra % 2) == 0){                 //Checks if even
            return new Woman(namn, pnr);
        }
        else{
            return new Man(namn, pnr);
        }

    }

}

//Man.java
package human;
class Man extends Human{
    private final String pnr;
    private final String namn;

    protected Man(String n, String p){
        namn = n;
        pnr = p;
    }
    public String toString(){
        return "My name is "+namn+" and I am a man.";
    }
}

//Woman.java
package human;
class Woman extends Human{
    private final String pnr;
    private final String namn;

    protected Woman(String n, String p){
        namn = n;
        pnr = p;
    }
    public String toString(){
        return "My name is "+namn+" and I am a woman.";
    }

}

I also have a class called Test.java. Here comes my problem: In Test.java, I want to make it impossible to do the following:
Human h = new Human(){};

i.e., to create an anonymous subclass of Human. Unfortunately, this line of code runs just fine, and an anonymous subclass is created. How can I make this line of code unexecutable/uncompilable?
PS. I have already tried making Human final. It was not allowed to combine final with abstract in a class.
EDIT:
So I got the tip to make the Human constructor protected. Here's what it looks like after the change:
//Human.java
package human;
public abstract class Human{
    protected Human(){}

    public static Human create(String name, String idNumber){
        char secondlast_char = idNumber.charAt(9); // takes second last char in pnr
        String secondlast_string = Character.toString(secondlast_char);
        float siffra = Float.parseFloat(secondlast_string); //Converts to float
        if ((siffra % 2) == 0){                 //Checks if even
            return new Woman(name, idNumber);
        }
        else{
            return new Man(name, idNumber);
        }
    }
}

Unfortunately, I still do not get an error neither when running or compiling the code of Test.java, which by the way looks like this:
import human.*;
public class Test{
    public static void main(String[] args){
        Human h = new Human(){};
    }
}

A: Add a constructor with the default visibility:
public abstract class Human {
    Human(){}
}

By default this only allows access to classes within the same package so it is known as "package private".

A: Use the default modifier for constructors:
Human(){}

A: Please note that making it impossible to create anonymous classes from your base class is not the main problem with your implementation of the Factory Pattern. The pattern's intention is to encapsulate object creation logic, so that it can be changed easily without affecting the classes that are being instantiated nor the clients that use those instances.
Putting a static factory method into a base class that creates concrete instances of its sub classes defeats the objective of class separation thanks to inheritance as well as the purpose of the factory pattern.
I would seriously consider sticking your factory method into a separate class, e.g. HumanFactoryImpl and provide a corresponding interface.