text:
Q: How to make Eigensystem in version 10 produce the same results as version 9 The Eigensystem in version 10 seems to give slightly different results as in version 9:
Hmtx={{12.375, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I, -4.6634340043469916*^-18 - 1.1043592643970545*^-18*I, 5.9846202809437726*^-18 - 1.8774107494749925*^-17*I, -5.0917886236526596*^-17 - 3.6443855725102797*^-17*I, -1.7364763179227213*^-17 + 5.2457065058860084*^-17*I}, {-0.06250000000000006 + 8.834874115176436*^-18*I, 7.875, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I, -4.6634340043469916*^-18 - 1.1043592643970545*^-18*I, 5.9846202809437726*^-18 - 1.8774107494749925*^-17*I, -5.0917886236526596*^-17 - 3.6443855725102797*^-17*I}, {-1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 4.375, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I, -4.6634340043469916*^-18 - 1.1043592643970545*^-18*I, 5.9846202809437726*^-18 - 1.8774107494749925*^-17*I}, {7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 1.8749999999999998, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I, -4.6634340043469916*^-18 - 1.1043592643970545*^-18*I}, {3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 0.3749999999999999, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I}, {6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, -0.12500000000000014, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I}, {-1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 0.3749999999999999, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I}, {-4.6634340043469916*^-18 + 1.1043592643970545*^-18*I, -1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 1.8749999999999998, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I}, {5.9846202809437726*^-18 + 1.8774107494749925*^-17*I, -4.6634340043469916*^-18 + 1.1043592643970545*^-18*I, -1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 4.375, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I}, {-5.0917886236526596*^-17 + 3.6443855725102797*^-17*I, 5.9846202809437726*^-18 + 1.8774107494749925*^-17*I, -4.6634340043469916*^-18 + 1.1043592643970545*^-18*I, -1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 7.875, -0.06250000000000006 - 8.834874115176436*^-18*I}, {-1.7364763179227213*^-17 - 5.2457065058860084*^-17*I, -5.0917886236526596*^-17 + 3.6443855725102797*^-17*I, 5.9846202809437726*^-18 + 1.8774107494749925*^-17*I, -4.6634340043469916*^-18 + 1.1043592643970545*^-18*I, -1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 12.375}};

{vals, vecs} = Eigensystem[Hmtx];
vals
vecs[[1]]

in version 9 I get:
eigenvalue
(*
{12.3759, 12.3759, 7.87525, 7.87525, 4.37545, 4.37545, 1.87605, 1.87604, 0.387613, 0.372399, -0.140221}
*)

first eigenvector
(*
{-0.000534641 + 0.00179264 I, 7.42495*10^-6 - 0.0000248957 I, -5.80038*10^-8 + 1.94486*10^-7 I,  3.45242*10^-10 - 1.15759*10^-9 I, -1.71049*10^-12 +  6.02886*10^-12 I, -1.68042*10^-11 - 3.01451*10^-14 I,  3.36278*10^-9 + 1.56589*10^-16 I, -6.45683*10^-7 + 1.38957*10^-18 I, 0.00010848 - 5.32021*10^-19 I, -0.0138864 -  1.97975*10^-18 I, 0.999902}
*)

in version 10 I get:
eigenvalue
(*
{12.3759 - 1.02031*10^-15 I, 12.3759 - 9.91618*10^-29 I, 7.87525 - 8.85813*10^-16 I, 7.87525 - 4.21836*10^-20 I,  4.37545 + 8.4819*10^-17 I, 4.37545 + 8.48193*10^-17 I, 1.87605 - 9.81335*10^-20 I, 1.87604 - 9.81346*10^-20 I,  0.387613 - 1.396*10^-22 I,  0.372399 - 1.40297*10^-22 I, -0.140221 - 1.24838*10^-24 I}
*)

first eigenvector
(*
{-0.00639256 + 0.0131895 I,  0.0000887781 - 0.000183172 I, -6.93536*10^-7 + 1.43094*10^-6 I,  4.12798*10^-9 - 8.51706*10^-9 I, -2.14113*10^-11 +   4.43576*10^-11 I, -1.67039*10^-11 - 2.21781*10^-13 I,  3.36242*10^-9 + 1.15472*10^-15 I, -6.45615*10^-7 + 1.42743*10^-17 I,  0.000108469 - 7.67751*10^-17 I, -0.0138849 - 4.92661*10^-16 I,  0.999796 + 0. I}
*)

How can I make version 10 produce the same results as version 9? How can I know which method is used in version 9? I tried to set the Method options in version 10 but still unable to get an agreement.
Edit
I agree that the comments are all right, that they are both correct results. I'm curious what's the change in the "internal mechanism", method, etc, so that it produce different correct results. I use this Eigensystem in calculating some quantum mechanic problem called high harmonic generation, which is very sensitive to small errors in the results. In theory , an overall phase change should not effect my results, but after upgrading to version 10, the noise floor in my results increase more then one order of magnitude. I'm trying to see why that happens, and this is my first stop.
Mathematica is now a language, I guess I would expect to have exactly the same results if I update the "compiler", or at least I should know why the results are different.


text:
Q: HTML form validation - filtering unicode (Persian) characters in PHP without using preg_match() I have HTML form input to be validated. The input should only use Unicode (Persian) letters and numeric nothing else. I used the preg_match like this:
preg_match('/^[آإأابپتثجچحخدذرزژسشصضطظعغفقکگلمنهۀةوؤیيئءًٌٍَُِّ\s]+$/u',$input);

and it works fine on localhost, but as my hosting does not have PCRE with Unicode support installed and I am not going to ask them to install it for me, I am looking for another working way to accomplish this.
Are there any ways in which I can validate unicode input, without using preg_match() function?
Duplicate Flag
Accrding to the duplicate flag, I am not after a PCRE, 'preg_match' way. The linked question is a PCRE 'preg_match' way.

A: There are some specific multi-byte functions that you may benefit from when PCRE is not compiled with PCRE_UTF8 flag:
mb_regex_encoding('UTF-8');
var_dump(mb_ereg('^[آ-یء\s]+$', "سلام پارسی تست می کنیم آإأابپتثجچحخدذرزژسشصضطظعغفقکگلمنهۀةوؤیيئًٌٍَُِّ"));
// int(1)

Here آ-ی character range includes more characters than Persian has (actually U+0622 - U+06CC, look at corresponding Unicode table) also note that no delimiters are specified.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I render two transparent objects as one continuous object? I'm struggling with transparency right now to get two objects to overlap and work as one layer. Ideally I'd just have one big red field over the skybox but instead I have moments where the transparency adds up. Is there an effective way around this?
What I want it to look like (from all angles): http://imgur.com/sN8SOtZ
What it looks like (from the angle where you see them intersect): http://imgur.com/Q7an21V
Current shader code:
Shader "Mobile/Particles/BallShader" {
Properties {
    _Color("Main Color", Color) = (1,1,1,.1)
}

Category {
    Tags { "Queue"="Transparent" "RenderType"="Transparent" }
    Blend OneMinusDstColor One // Soft Additive
    Lighting Off ZWrite On
    ZTest LEqual

    SubShader {
        Color [_Color]
        Pass {
        }
    }
}
}

edit: Just got closer to solving things but without a real understanding of how. Unity's built in particles/additive already deals with this problem.


text:
Q: Dissolve using ogr2ogr gives 'no such function: ST_union' I am trying to dissolve a shapefile using ogr2ogr but I am getting error no such function: ST_union:
Command:

C:\ms4w>ogr2ogr "C:\output\test-dissolved.sh p" "C:\input\test.shp"
  -dialect sqlite -sql "SELECT ST_union(geometry) FROM test "

Error:

ERROR 1: In ExecuteSQL(): sqlite3_prepare(SELECT ST_union(geometry) FROM test ):   no such function: ST_union

A: I should use GUnion instead of ST_Union, I tried it and it worked.
below is a list of all spatialite functions where it shows the ST & GEOS functions:
https://www.gaia-gis.it/gaia-sins/spatialite-sql-4.3.0.html


text:
Q: Custom ListView click issue on items in Android So I have a custom ListView object. The list items have two textviews stacked on top of each other, plus a horizontal progress bar that I want to remain hidden until I actually do something. To the far right is a checkbox that I only want to display when the user needs to download updates to their database(s). When I disable the checkbox by setting the visibility to Visibility.GONE, I am able to click on the list items. When the checkbox is visible, I am unable to click on anything in the list except the checkboxes. I've done some searching but haven't found anything relevant to my current situation. I found this question but I'm using an overridden ArrayAdapter since I'm using ArrayLists to contain the list of databases internally. Do I just need to get the LinearLayout view and add an onClickListener like Tom did? I'm not sure.
Here's the listview row layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:padding="6dip">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="fill_parent">
        <TextView
            android:id="@+id/UpdateNameText"
            android:layout_width="wrap_content"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:textSize="18sp"
            android:gravity="center_vertical"
            />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:id="@+id/UpdateStatusText"
            android:singleLine="true"
            android:ellipsize="marquee"
            />
        <ProgressBar android:id="@+id/UpdateProgress"
                     android:layout_width="fill_parent"
                     android:layout_height="wrap_content"
                     android:indeterminateOnly="false"
                     android:progressDrawable="@android:drawable/progress_horizontal"
                     android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"
                     android:minHeight="10dip"
                     android:maxHeight="10dip"
                     />
    </LinearLayout>
    <CheckBox android:text=""
              android:id="@+id/UpdateCheckBox"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              />
</LinearLayout>

And here's the class that extends the ListActivity. Obviously it's still in development so forgive the things that are missing or might be left laying around:
public class UpdateActivity extends ListActivity {

    AccountManager lookupDb;
    boolean allSelected;
    UpdateListAdapter list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        lookupDb = new AccountManager(this);
        lookupDb.loadUpdates();

        setContentView(R.layout.update);
        allSelected = false;

        list = new UpdateListAdapter(this, R.layout.update_row, lookupDb.getUpdateItems());
        setListAdapter(list);

        Button btnEnterRegCode = (Button)findViewById(R.id.btnUpdateRegister);
        btnEnterRegCode.setVisibility(View.GONE);

        Button btnSelectAll = (Button)findViewById(R.id.btnSelectAll);
        btnSelectAll.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                allSelected = !allSelected;

                for(int i=0; i < lookupDb.getUpdateItems().size(); i++) {
                    lookupDb.getUpdateItem(i).setSelected(!lookupDb.getUpdateItem(i).isSelected());
                }

                list.notifyDataSetChanged();
                // loop through each UpdateItem and set the selected attribute to the inverse

            } // end onClick
        }); // end setOnClickListener

        Button btnUpdate = (Button)findViewById(R.id.btnUpdate);
        btnUpdate.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
            } // end onClick
        }); // end setOnClickListener

        lookupDb.close();
    } // end onCreate

    @Override
    protected void onDestroy() {
        super.onDestroy();

        for (UpdateItem item : lookupDb.getUpdateItems()) {
            item.getDatabase().close();
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        UpdateItem item = lookupDb.getUpdateItem(position);

        if (item != null) {
            item.setSelected(!item.isSelected());
            list.notifyDataSetChanged();
        }
    }

    private class UpdateListAdapter extends ArrayAdapter<UpdateItem> {
        private List<UpdateItem> items;

        public UpdateListAdapter(Context context, int textViewResourceId, List<UpdateItem> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = null;

            if (convertView == null) {
                LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = li.inflate(R.layout.update_row, null);
            } else {
                row = convertView;
            }

            UpdateItem item = items.get(position);

            if (item != null) {
                TextView upper = (TextView)row.findViewById(R.id.UpdateNameText);
                TextView lower = (TextView)row.findViewById(R.id.UpdateStatusText);
                CheckBox cb = (CheckBox)row.findViewById(R.id.UpdateCheckBox);

                upper.setText(item.getName());
                lower.setText(item.getStatusText());

                if (item.getStatusCode() == UpdateItem.UP_TO_DATE) {
                    cb.setVisibility(View.GONE);
                } else {
                    cb.setVisibility(View.VISIBLE);
                    cb.setChecked(item.isSelected());
                }

                ProgressBar pb = (ProgressBar)row.findViewById(R.id.UpdateProgress);
                pb.setVisibility(View.GONE);
            }
            return row;
        }

    } // end inner class UpdateListAdapter
}

edit: I'm still having this problem. I'm cheating and adding onClick handlers to the textviews but it seems extremely stupid that my onListItemClick() function is not being called at all when I am not clicking on my checkbox.

A: use this line in the root view of the list item
android:descendantFocusability="blocksDescendants"

A: In case you have ImageButton inside the list item you should set the descendantFocusability value to 'blocksDescendants' in the root list item element.
android:descendantFocusability="blocksDescendants"

And the focusableInTouchMode flag to true in the ImageButton view.
android:focusableInTouchMode="true"

A: The issue is that Android doesn't allow you to select list items that have elements on them that are focusable. I modified the checkbox on the list item to have an attribute like so:
android:focusable="false"

Now my list items that contain checkboxes (works for buttons too) are "selectable" in the traditional sense (they light up, you can click anywhere in the list item and the "onListItemClick" handler will fire, etc).
EDIT: As an update, a commenter mentioned "Just a note, after changing the visibility of the button I had to programmatically disable the focus again."

A: I've had a similar issue occur and found that the CheckBox is rather finicky in a ListView.  What happens is it imposes it's will on the entire ListItem, and sort of overrides the onListItemClick. You may want to implement a click handler for that, and set the text property for the CheckBox as well, instead of using the TextViews.
I'd say look into this View object as well, it may work better than the CheckBox
Checked Text View


text:
Q: Issue Parsing Php With file_get_contents I'm loading my nav-bar from one php file, so I can just edit one file to update the whole site.
Code:
function getRsc($url){
    return file_get_contents($url.'.php');
}

That was working file until I tried to add actual php to the file.
  <?php
      if(isLoggedIn()){
        echo(" My Account ");
      }else {
        echo(" Login/Signup ");
      }
  ?>

It just displays the PHP as text, not parsing it. How can I accomplish this?
Thanks.

A: You can't file_get_contents a PHP file on the local file system like that. It won't get executed, you'll just get back the plain-text, unprocessed code.
You need include or require instead for a local PHP file.

A: Why aren't you just doing a regular require? e.g.,
<?php

require "path/to/nav-bar.php";

You're not supposed to use file_get_contents to load and run a PHP file. Take a look at require.


text:
Q: 'NoneType' object is not subscriptable : tf.keras.layers.concatenate : 'layer should be called on a list of 'f'at least 1 input I am trying to implement Unet with TensorFlow 2.7 and python 3.8. I am following the guide but I am facing an issue while running the architecture.
The problem I am facing is while using concatenating the inputs and Conv2DTranspose.
I am also looking for various implementations of Unet but all are written in different styles and different versions of tensorflow.
please let me know the possible solution as this code looks clean and I don't want to look for a different complex version.
import os
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
import tensorflow as tf

image_height, image_width = 96, 96
smoothness = 1.0
work_dir = ''

def convolution_layer(filters, kernel=(3,3), activation='relu', input_shape=None):
    if input_shape is None:
        return tf.keras.layers.Conv2D(
            filters=filters,
            kernel_size=kernel,
            activation=activation,padding='same')
    else:
        return tf.keras.layers.Conv2D(
            filters=filters,
            kernel_size=kernel,
            activation=activation,
            input_shape=input_shape,padding='same')

def concatenated_de_convolution_layer(filters):
    return tf.keras.layers.concatenate([
        tf.keras.layers.Conv2DTranspose(
            filters=filters,
            kernel_size=(2, 2),
            strides=(2, 2),
            padding='same'
        )],
        axis=3
    )

def pooling_layer():
    return tf.keras.layers.MaxPooling2D(pool_size=(2, 2))

unet = tf.keras.models.Sequential()
inputs = tf.keras.layers.Input((image_height, image_width, 1))
input_shape = (image_height, image_width, 1)
unet.add(convolution_layer(32, input_shape=input_shape))
unet.add(convolution_layer(32))
unet.add(pooling_layer())

unet.add(convolution_layer(64))
unet.add(convolution_layer(64))
unet.add(pooling_layer())

unet.add(convolution_layer(128))
unet.add(convolution_layer(128))
unet.add(pooling_layer())

unet.add(convolution_layer(256))
unet.add(convolution_layer(256))
unet.add(pooling_layer())

unet.add(convolution_layer(512))
unet.add(convolution_layer(512))

**unet.add(concatenated_de_convolution_layer(256))**
unet.add(convolution_layer(256))
unet.add(convolution_layer(256))

unet.add(concatenated_de_convolution_layer(128))
unet.add(convolution_layer(128))
unet.add(convolution_layer(128))

unet.add(concatenated_de_convolution_layer(64))
unet.add(convolution_layer(64))
unet.add(convolution_layer(64))

unet.add(concatenated_de_convolution_layer(32))
unet.add(convolution_layer(32))
unet.add(convolution_layer(32))

unet.add(convolution_layer(1, kernel=(1, 1), activation='sigmoid'))

unet.compile(optimizer=tf.keras.optimizers.Adam(lr=1e-5),
              loss=dice_coefficient_loss,
              metrics=[dice_coefficient])

Error:

A: You cannot concatenate a single Conv2DTranspose layer, since it is only one. Try this:
def concatenated_de_convolution_layer(filters):
    return  tf.keras.layers.Conv2DTranspose(
            filters=filters,
            kernel_size=(2, 2),
            strides=(2, 2),
            padding='same')

If you want to concatenate two layers, then you have to feed two inputs, but you are making your life unnecessarily difficult by using the Sequential API. Generally, I would recommend using the functional Keras API for building a UNET model. Here is a good starting point.


text:
Q: Tidio Chat - no longer installed but still trying to pull .js I installed Tidio Chat for wordpress then uninstalled it. It is still however trying to retrive .js code. It's adding 9-10 seconds on my site load time.
www.ivebeangrounded.com search for tidio on page source and it's there.
I assumed removing that script code would work. But I can't figure out what file that code is located in. It's not in footer.php

A: Tidio Developer here. We are adding our js code dynamically via plugin so the only way to remove this behavior is to purge your cache.
Thanks for notice!


text:
Q: Implementation of drawing from a set with non-uniform weights I would like to discuss how to optimally implement the following:
Given a set of elements,
all of them are distinct. Call this input set N, it has size n. These element each have a weight. Now, you need to create a subset (R) of this N of size r, where r is smaller then or equal to n.
This subset, again, cannot contain repetitions. Every element of R needs to be randomly chosen from N, if an element has a higher weight, the chance of it being chosen needs to be higher. If the total weight of all element in N is W, then the chance that element i is chosen needs to be w_i/W.
One last detail is that the weights are prone to change, but only to increase, they cannot decrease.
I want a neat implementation for this. I am working in Java, but I am hoping to find some language agnostic properties or details (or even pseudo code) that are interesting.
Now, for my own solution: I create an Array List of the original set of elements. I make sure that the weights are natural numbers and I add them n times if the weight of the element is n. Then I shuffle the arraylist (collections.shuffle) and I keep on taking element from the shuffled list and adding them to a Java Set until the size of the set is r. If the weight of an element increases, it gets added some more times to the original array list. Shuffle again, make a new subset.
My implementation needs loads of memory and the shuffle thingy is also slower if the set becomes bigger. Is there a better idea out there?

A: First, let's simplify it to drawing only one element, you calcualte
sum[-1] = 0
sum[i] = sum[i-1] + weight[i]

Then, you simply draw a number r in range [0,sum), and do binary search for r. The range it falls on, is the number you draw.
This is O(n) time solution.
You can obviously do it for more elements, but you will have to remove elements you have chosen from the set, or to repeat until you chose a new item. Both solutions however decay to quadric complexity for large subset size :(
But, can we improve it to do better?
Yes. Use a binary search tree instead of array. The binary search tree is actually a variation of order statistics tree, where instead of storing #children(v), you store the sum of weights in each subtree. Other than that - that's basically remains the same as order statistics tree.
More information about the tree solution can be found as an answer to a similar question: Algorithm to shuffle an Array randomly based on different weights
Complexity of building the tree is O(nlogn), and each query + removal is O(logn), which gives you O(nlogn + klogn) = O(nlogn)
So, we have two options:
If k in o(logn) (little o here), prefer recreating array with O(n) time per each query. Otherwise, you should prefer (in terms of time complexity) O(nlogn) tree based solution.
In terms of space, both solutions are linear in amount of extra space needed.

This can be even done better, with a single pass. This is called weighted reservoir sampling. It's main drawback is instability due to numeric issues for large weights due to the exponent part (at least from my experience).
This solution runs in linear time, with O(1) extra space (if not including the output array of size k).


text:
Q: Pandas Dataframe fransform according to condition I have the following dataframe and would like to transform the values of the dataframe according to the function bellow, but I can't get it to work with .transform nor with .apply.
dgp_id        8    13
lasso_class  4.0  2.0
lasso_reg    3.0  1.0
rf_class     1.0  4.0
rf_reg       2.0  3.0
xgb_class    6.0  6.0
xgb_reg      5.0  5.0

def scoring(x):
    if x == 1.0:
        x = 1
    elif x == 2.0:
        x=1/2
    elif x == 5.0:
        x=-1/2
    elif x==6.0:
        x=-1
    else:
        x=0

A: Assuming the column you want to transform has name "mycol", you could replace it explicitly:
newvals = [scoring(item) for item in df['mycol']]
df['mycol'] = newvals

*

*also note your scoring function needs "return x" at the bottom

A: IIUC, you can use a combination of transform, map, and fillna to create a column based change like this.

*

*transform will apply a function to each of our specified columns

*map will change values for us according to a dictionary

*fillna will take care of the fallthrough case- where anything not in the map dictionary will be replaced this value

# create a mapping of old values to new values
scoring = {1.0: 1, 2.0: 1/2, 5.0: -1/2, 6.0: -1}

new_df = (
    df.filter(["8", "13"]) # select columns to score
    .transform(lambda column: column.map(scoring)) # convert values
    .fillna(0)             # fill in fallthrough cases
)

print(new_df)
     8   13
0  0.0  0.5
1  0.0  1.0
2  1.0  0.0
3  0.5  0.0
4 -1.0 -1.0
5 -0.5 -0.5

If you then want to combine this with the original data, you can use .join like so:

full_df = df.join(new_df, rsuffix="_scored")

print(full_df)
        dgp_id    8   13  8_scored  13_scored
0  lasso_class  4.0  2.0       0.0        0.5
1    lasso_reg  3.0  1.0       0.0        1.0
2     rf_class  1.0  4.0       1.0        0.0
3       rf_reg  2.0  3.0       0.5        0.0
4    xgb_class  6.0  6.0      -1.0       -1.0
5      xgb_reg  5.0  5.0      -0.5       -0.5


text:
Q: create object using properties of other object Given these two objects:
firstObject:
var firstObject = {
    title: 'value1',
    year: 'value2',
    contributors: 'value3',
    abstract: 'value4'
};

secondObject:
var secondObject = {
    title: 'Title',
    year: 'Year',
    contributors: 'Contributors',
    abstract: 'Abstract'
};

How can I create a third object structured like this?:
var thirdObject = {
    Title: 'value1'
    Year: 'value2',
    Contributors: 'value3',
    Abstract: 'value4'
};

Basically assigning the properties of the secondObject as the keys of the thirdObject and the properties of the firstObject as the properties of the thirdObject.
Note: I don't want any uppercase of the of the firstObject keys.

A: You can use something like that :
var firstObject = {
    title: 'value1',
    year: 'value2',
    contributors: 'value3',
    abstract: 'value4'
};

var secondObject = {
    title: 'Title',
    year: 'Year',
    contributors: 'Contributors',
    abstract: 'Abstract'
};

var newObj = {};

$.each(secondObject, function(i){
    newObj[this] = firstObject[i];
});

//Vanilla JS version
for(var x in secondObject){
    newObj[secondObject[x]] = firstObject[x];
}
console.log(newObj);

http://jsfiddle.net/kq6tcp5L/

A: Example here. This assign "" if key doesn't exists in firstObject.
  var firstObject = {
        title: 'value1',
        year: 'value2',
        contributors: 'value3',
        abstract: 'value4'
    };

    var secondObject = {
        title: 'Title',
        year: 'Year',
        contributors: 'Contributors',
        abstract: 'Abstract',
        extra:''
    };
    var thirdObject ={};

    for(var key in secondObject)
    {
        if (secondObject.hasOwnProperty(key))
        {
          thirdObject[key] = (typeof firstObject[key] === "undefined")?"":firstObject[key];
        }
    }

    console.log(thirdObject);


text:
Q: onclick is not fired in a scrollable div I'm not able to capture the click event on a div which is inside the scrollable div in some devices like Tab 3 and Galaxy grand. But it is working absolutely fine in other android devices.
My parent div has style
#parentDiv { overflow:true}

I have tried all methods like
$(document).on("click","#id"+i,function(){
    alert("tapped");
});
$(document).on("tap","#id"+i,function(){
    alert("tapped");
});
$(document).on("swipeleft","#id"+i,function(){
    alert("tapped");
});

where "id"+i are the dynamically generated divs inside parentDiv
Even I tried replacing the divs with "button" and "a" tag, still does not work

A: I am not getting your problem, but I can give you an idea to debug the problem. I don't think, it is because of the scrollable HTML. What you can do is, while iterating the elements add an onlick attribute to with some alert statement. If it works the problem is somewhere in your script.
For example,
JS
var ele = '';
for(var i=0; i<arr.length; i++){
  ele += 'element +' i '+'
}

A: I have face similar problem and it is simple to solve, as you did not detail in case you are adding or midifying the divs dinamically.
Be sure the div exist in the dom at the moment the ready page triggers, if you are adding the div or parent dinamically the trick is to attach the click event inside the parent and filter by children, that way the click event is attached to an existent element.
The parent should exist since the beginning, if you are targetting the same event to all child divs use a class instead, if no your ids are ok.
Something like
$('#parentDiv').on('click', '.myClassDiv', function (){…});


text:
Q: Import cv2 error but opencv-python is already installed I've been trying to make a project with opencv, so I followed the YouTube video (It's in python), the video told me to go to cmd (win10) and use the command "pip install opencv-python" so that I can use the command import cv2. But the problem is after I did everything it still gave me an error.
I've done some research on it and nothing seem to work. I tried restarting my laptop or reinstall opencv, but nothing works for me. I'm thinking maybe it's because the PATH was wrong so it couldn't access it? But I've never worked with these before so I don't know what I'm supposed to do. I've seen some people with the same problem but the solution doesn't seem to work.
I'm using:
python 3.10.8
windows 10
IDLE Shell 3.10.1

A: Welcome to Stack Overflow!
Try installing with pip3
pip3 install opencv-python


text:
Q: callback function is not working in codeigniter I have used callback function for checking whether the email is active or not:
My controller is not accessing the callback function.
my controller code:
     function index() {
    //Session redirection
    header('Last-Modified:'.gmdate('D, d M Y H:i:s').'GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: post-check=0, pre-check=0',false);
    header('Pragma: no-cache');
    $this->session->unset_userdata('created_user_id');
    $this->session->unset_userdata('created_user_type');
    $this->session->unset_userdata('edit_user_type');
    if ($this->input->server('REQUEST_METHOD') === 'POST'){
    $this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email');
    $this->form_validation->set_rules('terms', 'Terms', 'trim|required');
        if($this->input->post('email'))
        {
        $this->form_validation->set_rules('email', 'Email ID', 'callback_email_check');
        } echo "out"; die;
    $this->form_validation->set_error_delimiters('
', '
');
    if($this->form_validation->run()){
                if($this->input->post('Join')!="") {
                $this->session->set_userdata('join_email', $this->input->post('email'));
                    redirect(base_url().'caregivers/my-account');
                }
        }
    }
    $this->load->view('site/landing-page');

}

My callback function code:
    public function email_check(){
    $get_status = $this->web_user_model->get_status($this->input->post('email'));
    if($get_status['is_active']=='1')
    {
        $this->form_validation->set_message('email_check','Email ID already Exits');
        return FALSE;
    }else{
        return TRUE;
    }

}

I dont know where i have done the mistake.
Can anyone help me???
thanks in advance..

A: You set twice your validation rule :
$this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email');
....
if($this->input->post('email'))
{
    $this->form_validation->set_rules('email', 'Email ID', 'callback_email_check');
 }

this is useless because you already set your email field to required so the if is already checked by the validation rule.
Try :
$this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email|callback_email_check');

Also your callback function should expect one parameter
public function email_check($email)
{
     $get_status = $this->web_user_model->get_status($email);
     ...


text:
Q: count() without GROUP BY So I tried running this simple code
select COUNT(Ename),BOSS
from EMPLOYEE
WHERE BOSS=7839

but seems I did not get the output unless I use a "group by" boss below. I am not able to understand why can't I get output without "group by".
Can anybody explain in laymen terms. Would be much appreciated.

A: Count is an aggregate function. When you use Count (or any other aggregate function such as Count, Sum, Max, Min) next to select, then every other column item must be in group by. If you only use
select COUNT(Ename) -- there is no BOSS
from EMPLOYEE

then you don't have to use Group By. Lets say you have 5 columns: 1-COUNT(Ename), 2- BOSS, 3- column3, 4- column4, 5-column5. Then you would have to write select code as below:
select COUNT(Ename),BOSS, column3, column4, column5
from EMPLOYEE
WHERE BOSS=7839
GROUP BY
   BOSS, column3, column4, column5

A: SELECT COUNT(*) FROM employee WHERE boss=7839 should work.
COUNT(), like AVG(), MIN(), MAX(), is an aggregate function: it takes several rows, and outputs only one. So, since a row can have several columns, the value for one of those column is established by the function; the value chosen, among the many rows, for each of the other columns has to be specified somehow. This is normally done with GROUP BY.
If you ask COUNT(*), name, the request would not be fulfillable, because which employee's name would be returned across the rows? The first employee's? The last? A random one? -- and so an error is raised: you cannot select the field unless you GROUP BY it. Some RDBMS might allow skipping this specification, and use any of the previous options (MySQL uses the first row, I think) to resolve the ambiguity.
If you ask COUNT(*), boss, the request is fulfillable even if useless, because the WHERE condition specifies that boss=7389. So there is no ambiguity... this is actually the same as asking SELECT COUNT(*), 7389 AS boss. But the RDBMS might not have the insight to understand this, since it is an edge case (it is otherwise legal SQL, and it could happen, but it's not so common except in contrived cases); and might raise the same error as before on general principles.

A: You need GROUP BY because COUNT() is an aggregate function. Really, the best way to do this is by using the HAVING command:
SELECT COUNT(ename), boss
FROM employee
GROUP BY boss
HAVING boss = 7839

A: Either you specify COUNT() alone, or you ask for COUNT(),boss but latter implies GROUP BY.
COUNT() is an "aggregate function", which means that, unlike regular functions (that can be evaluated for each row), these ones wait for the dataset to complete before they can give you an answer. That's case for SUM(), MIN(), MAX() or such as long it regards a whole column.
This means that you cannot ask for their value while the dataset is being parsed and, for this reason, cannot display their result aside the current value of a field (here being "boss"), because it just makes no sense. They're meant to be displayed as a bottom line after the data themselves.
However, you may do some groupings, according to a given criteria, that will sort your table along, then forming some subgroups each having a same value for the fields you specified in GROUP BY. These groups will each act as a mini-table upon which you aggregate functions can be evaluated.

A: When we use an aggregate function it return a single value. Using multiple aggregate function in a single query is also ok but when we mix up aggregate and normal then this become a mismatch. If we want to mix them up then we need to make others column on group by


text:
Q: How to bypass records with case I have got a CTE with this sort of data
ID | Name | UserID | SupervisorID
1.   Mark      1           2
2.   John      1           1
3.   Julia     3           1
4.   Tomm      1           2
5.   Eric      2           2

And if the SupervisorID is equal 2, then the rows with UserID equal 1 should NOT be returned.
If the SupervisorID is equal 1, then the rows with UserID equal 1 should NOT be returned.
I have tried with this query, but got stuck and can't figure out how to solve this problem.
SELECT * FROM CTE WHERE UserID <> CASE SupervisorID WHEN 1 THEN ??


text:
Q: How to fetch all same value field like categories and its subcategories? I am actually facing problem with a sql query execution which I am failing to execute as I want.
For a brief of what I want :
Here's my table structure-
| id | categoryname | nameofthing |
| 1  |   category1  |    name 1   |
| 2  |   category2  |    name 2   |
| 3  |   category 3 |    name 3   |
| 4  |   category 1 |    name 4   |
| 5  |   category 1 |    name 5   |
| 6  |   category 3 |    name 6   |

And what I want to display the results is like:
Category1
 - Name 1
 - Name 4
 - Name 5
Category2
 - Name 2
Catergot3
 - Name 3

and so on..
I want to run a query which first fetch all the samevalue categoryname and then its values( nafeofthing ) and again next samevalye categoryname and their value.
Please help me achieve this!
$query=mysql_query("SELECT * FROM thing WHERE tol_id='$bid' ORDER BY categoryname, name");
    if(mysql_num_rows($query) > 0){
    while($row=mysql_fetch_array($query)) {
    $categoryname = $row['categoryname'];
    $name = $row['name'];
    echo"

".$categoryname."

".$tname."

    ";
}

A: This is best done at the application layer, but you can get this result from a query:
select coalesce(concat('- ', nameofthing), categoryname)
from ((select categoryname, null as nameofthing
       from thing t
      ) union all
      (select categoryname, nameofthing
       from thing t
      )
     ) t
order by categoryname, (nameofthing = null) desc;

A:        <?php
        //use GROUP_CONCAT to CONCAT all name by comma(,) group by categoryname. 'thing' is your table name
        $query = "SELECT categoryname, GROUP_CONCAT(nameofthing) as 'name' FROM thing group by categoryname ORDER BY categoryname";

        $output ='';
    $query= mysqli_query($conn, $query);
        if(mysqli_num_rows($query) > 0){
        while($row=mysqli_fetch_array($query)) {
        $categoryname = $row['categoryname'];
        $output.="
".$categoryname."
";

        //using explode split the name in array
        $name = explode(',', $row['name']);

        $output.="
";

        //iterate the name from array
        for($i=0;$i<count($name);$i++){
             $output.= "
".$name[$i]."
";
        }
         $output.= "
";
    }
}

    echo $output;

OutPut will be like
https://www.screencast.com/t/ZWG7bqy0

A: $query=mysql_query("SELECT * FROM thing WHERE tol_id='$bid' ORDER BY categoryname, name");
$categories = [];
if(mysql_num_rows($query) > 0){
    while($row=mysql_fetch_array($query)) {
        $categories[$row['categoryname']][] = $row['name'];
    }
}
if(!empty($categories)) {
    foreach($categories as $categoryName => $subCategories) {
        echo "

".$categoryName."

";
                if(!empty($subCategories)) {
                    foreach($subCategories as $subCategory) {
                        echo "
".$subCategory."
";
                    }
                }
        echo "

";
    }
}


text:
Q: How i do for recognize what kind of error my function raises, using LDAP?    try {
        CentralDataLayer cdl = new CentralDataLayerOracleImpl();
        AuthenticationDataLayer adl = cdl.getAuthenticationDataLayer();

        String user = request.getParameter("username");
        String pass = request.getParameter("password");
        String site = request.getParameter("category");

        adl.Login(user, pass, site);
       response.sendRedirect("Configuration");

    } catch (AuthenticationException ex){
         request.setAttribute("error", "Invalid user/pass");
      } catch (NamingException ex) {
        request.setAttribute("error", "no connection");
    }

When exception raises, it appears only "no connection", but i want to distinguish both cases. How could I do?

A: It only appears that way because you coded it that way. You've thrown away the most useful part of the exception, which is the exception itself, and its message. Don't do that. Don't just create an error message of your own devising. Use the one that comes with the exception. As you test various failure modes, you will also discover that there is more than one kind of NamingException, and that you should catch them separately.


text:
Q: How to get child object key using a value? I have nested object as follows,
 {
  "Types": {
    "TEST": {
      "name": "EC",
      "alloweMultipls": "true"
    },
    "TEST1": {
      "name": "ED",
      "alloweMultipls": "true"
    }
  }
}

how can i retrive allowMyltipls if i have only the key "EC" not any other value.

A: Try this approach. You can get all properties of the fileTypes object and then iterate over them using .filter function and find that property for which the name equals to your key. Then with that key retrieve the nested object.

const object = {
  "fileTypes": {
    "TEST": {
      "name": "EC",
      "alloweMultipls": "true"
    },
    "TEST1": {
      "name": "ED",
      "alloweMultipls": "true"
    }
  }
};

const key = 'EC';
const fileTypes = object.fileTypes;

const property= Object.keys(fileTypes).filter(item => fileTypes[item].name === key);

console.log(fileTypes[property]);

A: Iterate over your object and check the 'name' property, if it matches to your desired then get the full object. Simple and elegant solution.

var data = {
  "Types": {
    "TEST": {
      "name": "EC",
      "alloweMultipls": "true"
    },
    "TEST1": {
      "name": "ED",
      "alloweMultipls": "true"
    }
  }
};

for(d in data.Types){
    if(data.Types[d].name=='EC'){
        console.log(data.Types[d]);
    }
}

A: Ataur Rahman,
 var data = {  "Types": {
"TEST": {
  "name": "EC",
  "alloweMultipls": "true"
},
"TEST1": {
  "name": "ED",
  "alloweMultipls": "true"
}  }}

 var allMultiplesInEC = [];

for(var i=0;i<data.Types.length-1;++i){  if(data.Types[i].name =='EC'{

 allMultiplesInEC.push(data.Types[i].alloweMultipls);}
}

console.log(allMultiplesInEC);


text:
Q: How to add new block (without phtml) with links to header content in Magento 2?
What is the correct way to add block with some links and few css classes to header content?
This is correct?
    <referenceContainer name="header-wrapper">
        <container name="header.decor" as="headerDecor" label="Header Decor" htmlTag="div" htmlClass="header-decor">
            <block class="Magento\Framework\View\Element\Html\Link" htmlClass="link-1" name="link-1">
                <arguments>
                    <argument name="css_class" xsi:type="string">link-1</argument>
                    <argument name="path" xsi:type="string">link-1</argument>
                </arguments>
            </block>
            <block class="Magento\Framework\View\Element\Html\Link" htmlClass="link-2" name="link-2">
                <arguments>
                    <argument name="css_class" xsi:type="string">link-2</argument>
                    <argument name="path" xsi:type="string">link-2</argument>
                </arguments>
            </block>
        </container>
    </referenceContainer>

But no class...

A: In you "own theme" under Magento_Theme/layout/default.xml, add the following content.
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <referenceContainer name="header-wrapper">
            <block class="Magento\Framework\View\Element\Template" name="top.custom.links" as="topCustomLinks" template="Magento_Theme::topCustomLinks.phtml" />
        </referenceContainer>

</page>

And add the HTML content inside your_theme/Magento_Theme/templates/topCustomLinks.phtml

Link 1

Link 2

Link 3

A: Add code to your default.xml ,
<referenceContainer name="header-wrapper">
   <container name="header-custom-link" as="header-custom-link" label="Page header-link" htmlTag="div" htmlClass="header-link content">
     <referenceBlock name="header.links">
      <block class="Magento\Customer\Block\Account\RegisterLink" htmlClass="register" before="-" name="register-link">
        <arguments>
            <argument name="label" xsi:type="string" translate="true">Create an Account</argument>
        </arguments>
      </block>

      <block class="Magento\Framework\View\Element\Html\Link" name="wish-link" htmlClass="wishlist" after="register-link">
        <arguments>
          <argument name="label" xsi:type="string" translate="false">My WishList</argument>
          <argument name="path"  xsi:type="string" translate="false">wishlist/</argument>
        </arguments>
      </block>
     </referenceBlock>
   </container>
 </referenceContainer>

Thanks


text:
Q: How to make my whole project responsive by using both percentages and pixels on css? I need to make html/css/javascript website responsive.
I read a lot about using percentages instead of pixels. But the thing is, I already used 250+ px's in my css. Is there any way to fix this without changing them all into percentages and using the @media query?
Some examples of my code:
.main-image {
  height: 100px;
}

footer {
  position: fixed;
  height: 50px;
}

.dropdown-content {
  list-style-type: upper-roman;
  margin: 0;
  padding: 40px;
}

nav a.admin_page {
  float: right;
  font-size: 1.5em;
  padding: 14px 30px;
  border: none;
}

.text {
  color: #f2f2f2;
  font-size: 20px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 50%;
  margin-left: 300px;
  text-align: center;
  background-color: #80af2b;
}

As you can see I used a lot of px's for different. Is there any easy way to fix this?


text:
Q: Removing XElements in a foreach loop So, I have a bug to remove
foreach (XElement x in items.Elements("x"))
{
    XElement result = webservice.method(x);

    if (/*condition based on values in result*/)
    {
        x.Remove();
    }
}

The problem is that calling x.Remove() alters the foreach such that if there are two Elements("x"), and the first is removed, the loop doesn't get to the second x element.
So how should I be looping this?  Or should this be rewritten another way?

A: I suspect that Linq may be able to help you out here as follows.
using System.Linq;

void foo()
{
    items.Elements("x")
         .Where(x => condition(webservice.method(x)))
         .Remove();
}

If that doesn't work (i.e. the internal enumerator is still invalidated), make a shallow copy of the selected elements and delete them as follows.
using System.Linq;

void foo()
{
    List xElements = items.Elements("x")
                          .Where(x => condition(webservice.method(x)))
                          .ToList();

    for (int i = xElements.Count - 1; i > -1; i--)
    {
        xElements[i].Remove();
    }
}

A: Create a collection before the loop logic, add the elements to be removed to the new collection, then call the items.Remove on each element in the new collection.

A: Try it without a for instead of the foreach.


text:
Q: How do I determine what ciphers & cipher modes I can use in dm-crypt/LUKS? I'm using an Ubuntu-based system, and I'm having difficulty determining what ciphers and cipher modes are available to me.
The cryptsetup man page says:
"See /proc/crypto for a list of available options. You might need to load additional kernel crypto modules in order to get more options."
My /proc/crypto has very little in it. How do I find out which extra kernel crypto modules are available for me to load?

A: The 5.1 kernel, current at the time I write this, has two different formats the for cipher string, the "old" format and the "new" format.  Everything in this question so far, and apparently all docs too, deals with the "old" format, so I'll describe it here.  This is for just encryption.  If using integrity with dm-crypt, then one must consider AEAD ciphers and it gets even more complicated.
The format parsed by the kernel is "cipher[:keycount]-mode-ivmode[:ivopts]".  Examples: aes-xts-plain64, blowfish-cbc-essiv:sha256, aes:64-cbc-lmk.

*

*cipher
The cipher to use, examples are aes, anubis, twofish, arc4, etc.  The kernel dm-crypt driver does not have a list of ciphers.  This is passed through to the Linux Crypto API, so any suitable cipher supported by the kernel can be used.

*keycount
Optional power of two number of keys to use with cipher.  This defaults to 1 for everything except the lmk ivmode, where it defaults to 64.  This really only applies to LMK and values other than 1 will will not work properly with other modes.

*mode The block chaining mode to use with the cipher.  Examples are ecb, cbc, xts.  Other than knowing that ecb uses no IV, the md-crypt driver passes this through to the Linux Crypto API and can use any chaining mode supported by the kernel.

*ivmode The algorithm used to generate the initialization vector (IV) for each sector.  In typical symmetric key encryption, unlike dm-crypt, the IV is another bit of data passed into the cipher along with the key when encrypting or decrypting.  There is just one IV passed in for the entire operation.  Since dm-crypt needs to be able to read and write each sector individually, it does not encrypt the entire disk as a single operation.  Instead, there is an IV for each sector.  Rather than passing in the IV as data, an algorithm for creating the IVs is specified here.  This isn't part of the Linux Crypto API, since IV generation isn't done by the cipher, and the allowed ivmode values are defined the dm-crypt driver.  They are:

*

*plain, plain64, plain64be, benbi
These simply use the sector number, in various formats, as the IV.  Meant for block modes like XTS that are designed to resist attacks like watermarking when using a simple and predictable IV.  plain64 appears to be the most commonly recommended.

*null IV is always zero.  For testing and backward compatibility, you shouldn't use this.

*lmk Compatible with the Loop-AES encryption scheme.

*tcw Compatible with TrueCrypt.

*essiv Uses sector number encrypted with a hash of the key.  Meant for modes, like CBC, that are not resistant to various attacks when using a simple IV like plain64.

*ivopts The hash to be used with essiv ivmode, ignored for all other modes.
As a special case, "cipher-plain" or just "cipher" are interpreted as "cipher-cbc-plain". Another special case is that ecb mode has no ivmode to specify.
How this relates to /proc/crypto
With respect to /proc/crypto, only the cipher and mode are relevant.  dm-crypt with construct a Crypto API specification of the form "mode(cipher)" and request this from the kernel.  This is what one should look for in /proc/crypto as the name for a skcipher.  Example:
name         : xts(aes)
driver       : xts-aes-aesni
module       : kernel
priority     : 401
refcnt       : 1
selftest     : passed
internal     : no
type         : skcipher
async        : yes
blocksize    : 16
min keysize  : 32
max keysize  : 64
ivsize       : 16
chunksize    : 16
walksize     : 16

The type of skcipher indicates this a symmetric key cipher, what dm-crypt uses, and the name of xts(aes) would be written aes-xts when specified with dm-crypt.  The keysize fields also tell us what key sizes can be used with this cipher.
If this was from a module, the module name might show up in the module line.  However, many ciphers (usually those in software that don't have any hardware specific code) are implement as a generic cipher that is combined with generic block chaining code to produce the final skcipher.  For example:
name         : xts(anubis)
driver       : xts(ecb(anubis-generic))
module       : kernel
type         : skcipher

name         : anubis
driver       : anubis-generic
module       : anubis
type         : cipher

In this case the anubis cipher is combined with the kernel XTS block chaining mode code to produce the final cipher xts(anbuis), which has been assigned a module of kernel.  But in order to have this available we need the generic anubis cipher, which is from the anubis module.  Most ciphers have a module alias of "crypto-cipher" that can be used to load them, e.g. modprobe crypto-anubis would load module that provides the anubis cipher.
When using the cryptsetup benchmark command, only the cipher and mode matter, since that is all that is benchmarked.  If mode is not specified it defaults to CBC.  The ivmode is totally ignored.  Thus, for benchmarking, aes, aes-cbc, and aes-cbc-foobar are all equivalent.

A: You can list the ciphers supported by your kernels with the following command,
[root@arif]# ls /lib/modules/[your kernel version]/kernel/crypto/
algif_rng.ko.xz   blowfish_common.ko.xz   cmac.ko.xz               cts.ko.xz          gf128mul.ko.xz           michael_mic.ko.xz  rsa_generic.ko.xz      tgr192.ko.xz           xts.ko.xz
ansi_cprng.ko.xz  blowfish_generic.ko.xz  crc32_generic.ko.xz      deflate.ko.xz      ghash-generic.ko.xz      pcbc.ko.xz         salsa20_generic.ko.xz  twofish_common.ko.xz   zlib.ko.xz
anubis.ko.xz      camellia_generic.ko.xz  crct10dif_common.ko.xz   des_generic.ko.xz  jitterentropy_rng.ko.xz  pcrypt.ko.xz       seed.ko.xz             twofish_generic.ko.xz
arc4.ko.xz        cast5_generic.ko.xz     crct10dif_generic.ko.xz  dh_generic.ko.xz   khazad.ko.xz             rmd128.ko.xz       serpent_generic.ko.xz  vmac.ko.xz
async_tx          cast6_generic.ko.xz     cryptd.ko.xz             drbg.ko.xz         lrw.ko.xz                rmd160.ko.xz       sha512_generic.ko.xz   wp512.ko.xz
authencesn.ko.xz  cast_common.ko.xz       crypto_null.ko.xz        fcrypt.ko.xz       mcryptd.ko.xz            rmd256.ko.xz       tcrypt.ko.xz           xcbc.ko.xz
authenc.ko.xz     ccm.ko.xz               crypto_user.ko.xz        gcm.ko.xz          md4.ko.xz                rmd320.ko.xz       tea.ko.xz              xor.ko.xz

You can list the ciphers and hashes you can use and their I/O comparison by for luks by the following command,
[root@arif arif]# cryptsetup benchmark
# Tests are approximate using memory only (no storage IO).
PBKDF2-sha1       289342 iterations per second for 256-bit key
PBKDF2-sha256     353293 iterations per second for 256-bit key
PBKDF2-sha512     227555 iterations per second for 256-bit key
PBKDF2-ripemd160  233224 iterations per second for 256-bit key
PBKDF2-whirlpool  236165 iterations per second for 256-bit key
argon2i       4 iterations, 917485 memory, 4 parallel threads (CPUs) for 256-bit key (requested 2000 ms time)
argon2id      4 iterations, 951672 memory, 4 parallel threads (CPUs) for 256-bit key (requested 2000 ms time)
#     Algorithm |       Key |      Encryption |      Decryption
        aes-cbc        128b       642.2 MiB/s      2495.8 MiB/s
    serpent-cbc        128b        89.3 MiB/s       542.6 MiB/s
    twofish-cbc        128b       100.4 MiB/s       343.1 MiB/s
        aes-cbc        256b       477.2 MiB/s      1979.2 MiB/s
    serpent-cbc        256b        89.3 MiB/s       538.9 MiB/s
    twofish-cbc        256b       173.3 MiB/s       343.1 MiB/s
        aes-xts        256b      1668.0 MiB/s      1664.1 MiB/s
    serpent-xts        256b       535.7 MiB/s       523.4 MiB/s
    twofish-xts        256b       332.6 MiB/s       339.8 MiB/s
        aes-xts        512b      1384.5 MiB/s      1380.7 MiB/s
    serpent-xts        512b       539.3 MiB/s       524.4 MiB/s
    twofish-xts        512b       335.0 MiB/s       340.1 MiB/s

You can compare specific ciphers by the following command,
[root@arif]# ciphers="aes-xts serpent-xts anubis-xts"

[root@arif]# echo "#     Algorithm |       Key |      Encryption |      Decryption";for i in $ciphers ; do cryptsetup benchmark --cipher $i|tail -n 1; done

#     Algorithm |       Key |      Encryption |      Decryption
        aes-xts        256b      1613.9 MiB/s      1642.8 MiB/s
    serpent-xts        256b       538.9 MiB/s       521.9 MiB/s
     anubis-xts        256b       182.0 MiB/s       182.1 MiB/s

A: There are many, many documents and man pages to read through, but one document that might particularly interest you is the LUKS On-Disk Format Specification (PDF).
Appendix B (which is, naturally, near the end) says,

Cipher and Hash specification registry
Even if the cipher-name and cipher-mode strings are not interpreted by any
  LUKS operation, they must have the same meaning for all implementations
  to achieve compatibility among different LUKS-based implementations. LUKS
  has to ensure that the underlaying cipher system can utilise the cipher name
  and cipher mode strings, and as these strings might not always be native to the
  cipher system, LUKS might need to map them into something appropriate.
Valid cipher names are listed in Table 1.
Valid cipher modes are listed in Table 2. By contract, cipher modes using
  IVs and tweaks must start from the all-zero IV / tweak. This applies for all
  calls to the encrypt / decrypt primitives especially when handling key material.
  Further, these IVs / tweaks cipher modes usually cut the cipher stream into
  independent blocks by reseeding tweaks / IVs at sector boundaries. The all-zero IV / tweak requirement for the first encrypted / decrypted block
  is equivalent to
  the requirement that the first block is defined to rest at sector 0.
Table 3 lists valid hash specs for hash-spec field. A compliant implementation
  does not have to support all cipher, cipher mode or hash specifications.

Table 1: Valid cipher names

*

*aes - Advanced Encryption Standard - FIPS PUB 197

*twofish - Twofish: A 128-Bit Block Cipher -
http://www.schneier.com/paper-twofish-paper.html    (See below)

*serpent - http://www.cl.cam.ac.uk/~rja14/serpent.html

*cast5 - RFC 2144

*cast6 - RFC 2612

Table 2: Valid cipher modes

*

*ecb - The cipher output is used directly

*cbc-plain - The cipher is operated in CBC mode. The CBC chaining
is cut every sector, and reinitialised with the sector number
as initial vector (converted to 32-bit and to little-endian).
This mode is specified in [Fru05b], Chapter 4.

*cbc-essiv:hash - The cipher is operated in ESSIV mode
using hash for
generating the IV key for the original key. For instance,
when using sha256 as hash, the cipher mode spec is "cbcessiv:sha256".
ESSIV is specified in [Fru05b], Chapter 4.

*xts-plain64 - http://grouper.ieee.org/groups/1619/email/pdf00086.pdf, plain64 is 64-bit version of plain initial vector

Table 3: Valid hash specifications

*

*sha1 - RFC 3174 - US Secure Hash Algorithm 1 (SHA1)

*sha256 - SHA variant according to FIPS 180-2

*sha512 - SHA variant according to FIPS 180-2

*ripemd160 - http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
  (See below)

Editor's Note: The above is copied from the specification.
Subsequent to its writing, these documents' URLs have changed:

*

*Twofish: A 128-Bit Block Cipher   (new URL)

*The hash function RIPEMD-160   (new URL)


text:
Q: Android GroupActivity Backpress trigger Fatal Exception / NullPointerException I have some problems on BackPressed when using the ActivityGroup under TabHost.
To illustrate, first of all, codes are drilled down in layers as follows:
TabGroupActivity class
The following TabGroupActivity.java is referenced from an online tutorial.
public class TabGroupActivity extends ActivityGroup
{
    private ArrayList<String> mIdList;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (mIdList == null) mIdList = new ArrayList<String>();
    }

    /**
     * This is called when a child activity of this one calls its finish method.
     * This implementation calls {@link LocalActivityManager#destroyActivity} on the child activity
     * and starts the previous activity.
     * If the last child activity just called finish(),this activity (the parent),
     * calls finish to finish the entire group.
     */
  @Override
  public void finishFromChild(Activity child)
  {
      LocalActivityManager manager = getLocalActivityManager();
      int index = mIdList.size()-1;

      if (index < 1)
      {
          finish();
          return;
      }

      manager.destroyActivity(mIdList.get(index), true);
      mIdList.remove(index); index--;
      String lastId = mIdList.get(index);
      Activity a = manager.getActivity(lastId);
      Intent lastIntent = a.getIntent();      // LINE 49
      Window newWindow = manager.startActivity(lastId, lastIntent);
      setContentView(newWindow.getDecorView());
  }

  /**
   * Starts an Activity as a child Activity to this.
   * @param Id Unique identifier of the activity to be started.
   * @param intent The Intent describing the activity to be started.
   * @throws android.content.ActivityNotFoundException.
   */
  public void startChildActivity(String Id, Intent intent)
  {
      Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
      if (window != null)
      {
          mIdList.add(Id);
          setContentView(window.getDecorView());
      }
  }

  /**
   * The primary purpose is to prevent systems before android.os.Build.VERSION_CODES.ECLAIR
   * from calling their default KeyEvent.KEYCODE_BACK during onKeyDown.
   */
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event)
  {
      if (keyCode == KeyEvent.KEYCODE_BACK)
      {
          //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
          return true;
      }
      return super.onKeyDown(keyCode, event);
  }

  /**
   * Overrides the default implementation for KeyEvent.KEYCODE_BACK
   * so that all systems call onBackPressed().
   */
  @Override
  public boolean onKeyUp(int keyCode, KeyEvent event)
  {
      if (keyCode == KeyEvent.KEYCODE_BACK)
      {
          onBackPressed(); //LINE 88
          return true;
      }
      return super.onKeyUp(keyCode, event);
  }

  /**
   * If a Child Activity handles KeyEvent.KEYCODE_BACK.
   * Simply override and add this method.
   */
  @Override
  public void  onBackPressed  ()
  {
      int length = mIdList.size();
      if ( length > 1)
      {
          Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1));
          current.finish(); //LINE 103
      }
  }
}

Tools_GroupActivity class
public class Tools_GroupActivity extends TabGroupActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        startChildActivity("Tools_index", new Intent(this, Tools_index.class));
    }
}

Tools_index.class
It is a page with 9 buttons, for example when pressing button 1, it will invoke the Tools_1_diamond claass:
public void tools_button1_click (View view)
{
    Intent edit = new Intent(getParent(), Tools_1_Diamond.class);
    TabGroupActivity parentActivity = (TabGroupActivity)getParent();
    parentActivity.startChildActivity("Tools_1_Diamond", edit);
}

Inside Tools_1_diamond class
The layout has a button that can back to the Tools_index page, as follows:
public void button_tools_subpage_back_click (View view)
{
    Intent edit = new Intent(getParent(), Tools_index.class);
    TabGroupActivity parentActivity = (TabGroupActivity)getParent();
    parentActivity.startChildActivity("Tools_index", edit);
}

@Override
public void onBackPressed()
{
    Intent edit = new Intent(getParent(), Tools_index.class);
    TabGroupActivity parentActivity = (TabGroupActivity)getParent();
    parentActivity.startChildActivity("Tools_index", edit);
}

Problem reproduced:
Case A:
1. When pressing self-designed button in Tools_1_Diamond class, (instead of the backpressed) the app can return properly back to the Tools_index page.

*

*Then, inside the Tools_index page, if the user at this time press the BackPressed Button, the app will go back to Tools_1_Diamond page,

*and then further press the BackPress Button, error FATAL EXCEPTION: main java.lang.NullPointerException will occur.
Case B:
When all the way just using BackPress without touching the self-designed back button, everything runs smoothly.
Question / Intention:
I think the problem should be the self-designed button does not reduce the ArrayList similar to BackPress method...but...
How could this be solved? I would like to offer user that when pressing either the self-designed back button or the BackPress method will return to the Tools_index page, and further pressing the BackPress in the Tools_index page will offer no reaction, or even better, to pop up an alertDialog asking user whether want to quit the app.
Logcat:
06-19 22:40:03.570: D/webviewglue(23395): nativeDestroy view: 0x51909960
06-19 22:40:06.585: D/AndroidRuntime(23395): Shutting down VM
06-19 22:40:06.585: W/dalvikvm(23395): threadid=1: thread exiting with uncaught exception (group=0x40fe72a0)
06-19 22:40:06.670: E/AndroidRuntime(23395): FATAL EXCEPTION: main
06-19 22:40:06.670: E/AndroidRuntime(23395): java.lang.NullPointerException
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.abc.abc_v1.TabGroupActivity.finishFromChild(TabGroupActivity.java:49)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.app.Activity.finish(Activity.java:4215)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.abc.abc_v1.TabGroupActivity.onBackPressed(TabGroupActivity.java:103)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.abc.abc_v1.TabGroupActivity.onKeyUp(TabGroupActivity.java:88)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.KeyEvent.dispatch(KeyEvent.java:2729)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.app.Activity.dispatchKeyEvent(Activity.java:2431)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2033)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1363)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1363)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1363)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.widget.TabHost.dispatchKeyEvent(TabHost.java:309)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1363)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1363)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1363)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:2106)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1466)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.app.Activity.dispatchKeyEvent(Activity.java:2426)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2033)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3852)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3800)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2935)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.os.Looper.loop(Looper.java:137)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at android.app.ActivityThread.main(ActivityThread.java:4921)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at java.lang.reflect.Method.invokeNative(Native Method)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at java.lang.reflect.Method.invoke(Method.java:511)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
06-19 22:40:06.670: E/AndroidRuntime(23395):    at dalvik.system.NativeStart.main(Native Method)

A: First
The problem could be that in TabGroupActivity, after you have done:
mIdList.remove(index);

you don't check that index is still valid, ie bigger than or equal to one. The following code should probably be:
if (index > 0) {
     index--;
     String lastId = mIdList.get(index);
     Intent lastIntent = manager.getActivity(lastId).getIntent(); //LINE49
     Window newWindow = manager.startActivity(lastId, lastIntent);
     setContentView(newWindow.getDecorView());
}
else {
    // Handle case where there are no children left.
}

Second
It is worth noting that LocalActivityManager was deprecated in API level 13, and so, unless you are only targeting pre-13 devices, it shouldn't be used.
Even if you do decide to proceed with using it, there are some conditions under which it won't actually start a new Activity. See here.


text:
Q: ATHENA/PRESTO complex query with multiple unnested tables i have i would like to create a join over several tables.
table login : I would like to retrieve all the data from login
table logging : calculating the Nb_of_sessions for each db & for each a specific event type by user
table meeting : calculating the Nb_of_meetings for each db & for each user
table live : calculating the Nb_of_live for each db & for each user
I have those queries with the right results :
SELECT db.id,_id as userid,firstname,lastname
FROM  "logins"."login",
UNNEST(dbs) AS a1 (db)

SELECT dbid,userid,count(distinct(sessionid)) as no_of_visits,
       array_join(array_agg(value.from_url),',') as from_url
FROM "loggings"."logging"
where event='url_event'
group by db.id,userid;

SELECT dbid,userid AS userid,count(*) as nb_interviews,
      array_join(array_agg(interviewer),',') as interviewer
FROM  "meetings"."meeting"
group by dbid,userid;

SELECT dbid,r1.user._id AS userid,count(_id) as nb_chat
FROM "lives"."live",
UNNEST(users) AS r1 (user)
group by dbid,r1.user._id;

But when i begin to try put it all together, it seems i retrieve bad data (i have only on db retrieved) and it seems not efficient.
select a1.db.id,a._id as userid,a.firstname,a.lastname,count(rl._id) as nb_chat
FROM
"logins"."login" a,
"loggings"."logging" b,
"meetings"."meeting" c,
"lives"."live" d,
UNNEST(dbs) AS a1 (db),
UNNEST(users) AS r1 (user)
where a._id = b.userid AND a._id = c.userid AND a._id = r1.user._id
group by 1,2,3,4

Do you have an idea ?
Regards.

A: The easiest way is to work with with to structure the subquery and then reference them.
with parameter reference:

You can use WITH to flatten nested queries, or to simplify subqueries.
The WITH clause precedes the SELECT list in a query and defines one or
more subqueries for use within the SELECT query.
Each subquery defines a temporary table, similar to a view definition,
which you can reference in the FROM clause. The tables are used only
when the query runs.

Since you already have working sub queries, the following should work:
with logins as
(
    SELECT db.id,_id as userid,firstname,lastname
    FROM  "logins"."login",
    UNNEST(dbs) AS a1 (db)
)
,visits as
(
    SELECT dbid,userid,count(distinct(sessionid)) as no_of_visits,
           array_join(array_agg(value.from_url),',') as from_url
    FROM "loggings"."logging"
    where event='url_event'
    group by db.id,userid
)
,meetings as
(
    SELECT dbid,userid AS userid,count(*) as nb_interviews,
          array_join(array_agg(interviewer),',') as interviewer
    FROM  "meetings"."meeting"
    group by dbid,userid
)
,chats as
(
    SELECT dbid,r1.user._id AS userid,count(_id) as nb_chat
    FROM "lives"."live",
    UNNEST(users) AS r1 (user)
    group by dbid,r1.user._id
)
select *
from logins l
left join visits v
    on l.dbid = v.dbid
    and l.userid = v.userid
left join meetings m
    on l.dbid = m.dbid
    and l.userid = m.userid
left join chats c
    on l.dbid = c.dbid
    and l.userid = c.userid;


text:
Q: Retrieving JSON Object Property comes out as undefined in NodeJS Request I'm sending a POST request to an external API which returns a JSON response. But I'm unable to access the JSON property it comes out as undefined however when I print the whole body the property exists. I have tried cloning the body to a new variable but it didn't work. Also tried parsing the JSON again but it didn't work either.
request.post({url:`http://2captcha.com/in.php?key=${key}&method=${service}&sitekey=${sitekey}&pageurl=${pageurl}&json=${json}`}, function(error, response, body){
                   if (response.statusCode == 200) {
                       console.log(body);
                       console.log(body.status);
                       console.log(body.request);
                   }

My console
{"status":1,"request":"67055353796"}
undefined
undefined


text:
Q: Performance bottlenecks in fast evaluation of trig functions using Eigen and MEX In a project using Matlab's C++ MEX API, I have to compute the value exp(j * 2pi * x) for over 100,000 values of x where x is always a positive double. I've written some helper functions that breakdown the computation into sin/cos using euler's formula. I then apply the method of range reduction to reduce my values to their corresponding points in the domain [0,T/4] where T is the period of the exponential I'm computing. I keep track of which quadrant in [0, T] the original value would have fallen into for later. I can then compute the trig function using a taylor series polynomial in horner form and apply the appropriate shift depending on which quadrant the original value was in. For further information on some of the concepts in this technique, check out this answer. Here is the code for this function:
Eigen::VectorXcd calcRot2(const Eigen::Ref<const Eigen::VectorXd>& idxt) {

    Eigen::VectorXd vidxt = idxt.array() - idxt.array().floor();
    Eigen::VectorXd quadrant = (vidxt.array()*2+0.5).floor();
    vidxt.array() -= (quadrant.array()*0.5);
    vidxt.array() *= 2*3.14159265358979;
    const Eigen::VectorXd sq = vidxt.array()*vidxt.array();

    Eigen::VectorXcd M(vidxt.size());
    M.real() = fastCos2(sq);
    M.imag() = fastSin2(vidxt,sq);
    M = (quadrant.array() == 1).select(-M,M);
    return M;
}

I profiled the code segment in which this function is called using std::chrono and averaged over 500 calls to the function (where each call to the mex function processes all 100,000+ values by calling calcRot2 in a loop. Each iteration passes about 200 values to calcRot2). I find the following average runtimes:
runtime with calcRot2:                   75.4694 ms
runtime with fastSin/Cos commented out:  50.2409 ms
runtime with calcRot2 commented out:     30.2547 ms

Looking at the difference between the two extreme cases, it seems like calcRot has a large contribution to the runtime. However, only a portion of that comes from the sin/cos calculation. I would assume Eigen's implicit vectorization and the compiler would make the runtime of the other operations in the function effectively negligible. (floor shouldn't be a problem!) Where exactly is the performance bottleneck here?
This is the compilation command I'm performing (It uses MinGW64 which I think is the same as gcc):
mex(ipath,'CFLAGS="$CFLAGS -O3 -fno-math-errno -ffast-math -fopenmp -mavx2"','LDFLAGS="$LDFLAGS -fopenmp"','DAS.cpp','DAShelper.cpp')

Reference Code
For reference, here is the code segment in the main mex function where the timer is called, and the helper function that calls calcRot2():
MEX function call:
chk1 = std::chrono::steady_clock::now();
// Calculate beamformed signal at each point
Eigen::MatrixXcd bfVec(p.nPoints,1);
#pragma omp parallel for
for (int i = 0; i < p.nPoints; i++) {
    calcPoint(idxt.col(i),SIG,p,bfVec(i));
}
chk2 = std::chrono::steady_clock::now();
auto diff3 = chk2 - chk1;

calcPoint:
void calcPoint(const Eigen::Ref<const Eigen::VectorXd>& idxt,
               const Eigen::Ref<const Eigen::MatrixXcd>& SIG,
               Parameters& p, std::complex<double>& bfVal) {

Eigen::VectorXcd pRot = calcRot2(idxt*p.fc/p.fs);

int j = 0;
for (auto x : idxt) {
    if(x >= 0) {
        int vIDX = static_cast<int>(x);
        bfVal += (SIG(vIDX,j)*(vIDX + 1 - x) + SIG(vIDX+1,j)*(x - vIDX))*pRot(j);
    }
    j++;
}
}

Clarification
To clarify, the line
(vidxt.array()*2+0.5).floor()

is meant to yield:
0 if vidxt is between [0,0.25]
1 if vidxt is between [0.25,0.75]
2 if vidxt is between [0.75,1]

The idea here is that when vidxt is in the second interval (quadrants 2 and 3 on the unit circle for functions with period 2pi), then the value needs to map to its negative value. Otherwise, the range reduction maps the values to the correct values.

A: The benefits of Eigen's vectorization are outweighed because you evaluate your expressions into temporary vectors. Allocating, deallocating, filling and reading these vectors has cost that seems significant. This is especially so because the expressions themselves are relatively simple (just a few scalar operations).
Expression objects
What usually helps here is aggregating into fewer expressions. For example line 3 and 4 can be collapsed into one:
vidxt.array() = 2*3.14159265358979 * (vidxt.array() - quadrant.array()*0.5);
(BTW: Note that that math.h contains a constant M_PI with pi in double precision).
Beyond that, Eigen expressions can be combined and reused. Something like this:
    auto vidxt0 = idxt.array() - idxt.array().floor();
    auto quadrant = (vidxt0*2+0.5).floor();
    auto vidxt = 2*3.14159265358979 * (vidxt0 - quadrant.array()*0.5);
    auto sq = vidxt.array().square();

    Eigen::VectorXcd M(vidxt.size());
    M.real() = fastCos2(sq);
    M.imag() = fastSin2(vidxt,sq);
    M = (quadrant.array() == 1).select(-M,M);

Note that none of the auto values are vectors. They are expression objects that behave like arrays and can be evaluated into vectors or arrays.
You can pass these on to your fastCos2 and fastSin2 function by declaring them as templates. The typical Eigen pattern would be something like
template<Derived>
void fastCos2(const Eigen::ArrayBase<Derived>& sq);

The idea here is that ultimately, everything compiles into one huge loop that gets executed when you evaluate the expression into a vector or array. If you reference the same sub-expression multiple times, the compiler may be able to eliminate the redundant computations.
Unfortunately, I could not get any better performance out of this particular code, so it is no real help here but it is still something worth exploring in these kind of cases.
fastSin/Cos return value
Speaking of temporary vectors: You didn't include the code for your fastSin/Cos functions but it looks a lot like you return a temporary vector which is then copied into the real and imaginary parts or the actual return value. This is another temporary that you may want to avoid. Something like this:
template<class Derived1, class Derived2>
void fastCos2(const Eigen::MatrixBase<Derived1>& M, const Eigen::MatrixBase<Derived2>& sq)
{
    Eigen::MatrixBase<Derived1>& M_mut = const_cast<Eigen::MatrixBase<Derived1>&>(M);
    M_mut = sq...;
}

fastCos2(M.real(), sq);

Please refer to Eigen's documentation on the topic of function arguments.
The downside of this approach in this particular case is that now the output is not consecutive (real and imaginary parts are interleaved). This may affect vectorization negatively. You may be able to work around this by combining the sin and cos functions into one expression for both. Benchmarking is required.
Using a plain loop
As others have pointed out, using a loop may be easier in this particular case. You noted that this was slower. I have a theory why: You did not specify -DNDEBUG in your compile options. If you don't, all array indices in Eigen vectors are range-checked with an assertion. These cost time and prevent vectorization. If you include this compile flag, I find my code significantly faster than using Eigen expressions.
Alternatively, you can use raw C pointers to the input and output vector. Something like this:
std::ptrdiff_t n = idxt.size();
Eigen::VectorXcd M(n);
const double* iidxt = idxt.data();
std::complex<double>* iM = M.data();
for(std::ptrdiff_t j = 0; j < n; ++j) {
    double ival = iidxt[j];
    double vidxt = ival - std::floor(ival);
    double quadrant = std::floor(vidxt * 2. + 0.5);
    vidxt = (vidxt - quadrant * 0.5) * (2. * 3.14159265358979);
    double sq = vidxt * vidxt;
    // stand-in for sincos
    std::complex<double> jval(sq, vidxt + sq);
    iM[j] = quadrant == 1. ? -jval : jval;
}

Fixed sized arrays
To avoid the cost of memory allocation and make it easier for the compiler to avoid memory operations in the first place, it can help to run the computation on blocks of fixed size. Something like this:

std::ptrdiff_t n = idxt.size();
Eigen::VectorXcd M(n);
std::ptrdiff_t i;
for(i = 0; i + 4 <= n; i += 4) {
    Eigen::Array4d idxt_i = idxt.segment<4>(i);
    ...
    M.segment<4>(i) = ...;
}
if(i + 2 <= n) {
    Eigen::Array2D idxt_i = idxt.segment<2>(i);
    ...
    M.segment<2>(i) = ...;
    i += 2;
}
if(i < n) {
    // last index scalar
}

This kind of stuff needs careful tuning to ensure that vectorized code is generated and there are no unnecessary temporary values on the stack. If you can read assembler, Godbolt is very helpful.
Other remarks

*

*Eigen includes vectorized versions of sin and cos. Have you compared your code to these instead of e.g. Eigen's complex exp function?

*Depending on your math library, there is also an explicit sincos function to compute sine and cosine in one function. It is not vectorized but still saves time on range reduction. You can (usually) access it through std::polar. Try this:
Eigen::VectorXd scale = ...;
Eigen::VectorXd phase = ...;
// M = scale * exp(-2 pi j phase)
Eigen::VectorXd M = scale.binaryExpr(-2. * M_PI * phase,
      [](double s, double p) noexcept -> std::complex<double> {
          return std::polar(s, p);
});

*

*If your goal is an approximation instead of a precise result, shouldn't your first step be to cast to single precision? Maybe after the range reduction to avoid losing too many decimal places. At the very least it will double the work done per clock cycle. Also, regular sine and cosine implementations take less time in float.

Edit

*

*I had to correct myself on the cast to int64 instead of int. There is no vectorized conversion to int64_t until AVX512

*The line (vidxt.array()*2+0.5).floor() bugs me slightly. This is meant to round down to negative infinity for [0, 0.5) and up to positive infinity for [0.5, 1), correct? vidxt is never negative. Therefore this line should be equivalent to (vidxt.array()*2).round(). With AVX2 and -ffast-math that saves one instruction. With SSE2 none of these actually vectorize, as can be seen on Godbolt


text:
Q: Flask-admin display image with path from column I have my DB set like this :
  MediaPath    DateCreated    Message   Type
/home/1/1.jpg   21.09.2017              jpeg
/home/2/2.jpg   ....          ....      ....

How can i set up Flask code to preview images from the MediaPath column without uploading them to /static/ folder?
This is usual flask-admin code template:
class ImageView(sqla.ModelView):
def _list_thumbnail(view, context, model, name):
    if not model.path:
        return ''

    return Markup('' % url_for('static',
                                             filename=form.thumbgen_filename(model.path)))

column_formatters = {
    'path': _list_thumbnail
}

form_extra_fields = {
    'path': form.ImageUploadField('Image',
                                  base_path=file_path,
                                  thumbnail_size=(100, 100, True))
}

A: Is the path for the files in the MeidaPath column their absolute path?
Make sure that the path returned by form.thumbgen_filename(model.path) is the absolute path for the file and you can do the following:
Instead of:
return Markup('' % url_for('static',
    filename=form.thumbgen_filename(model.path)))
Use:
return Markup('' % form.thumbgen_filename(model.path))
** Assuming that the method thumbgen_filename() returns the absolute path to the image thumbnail (you haven't posted the code for that method so I assuming that is what the method returns)**
When you use url_for('static', filename='some-path') it generate a URL that includes the static path and the files that are inside the static folder depending on the value you provide to url_for's filename argument. If want to load your files using their absolute path, just provide their absolute path without using url_for()


text:
Q: R: calculate number of occurrences which have started but not ended - count if within a datetime range I've got a dataset with the following shape
ID     Start Time             End Time
1   01/01/2017 00:15:00  01/01/2017 07:15:00
2   01/01/2017 04:45:00  01/01/2017 06:15:00
3   01/01/2017 10:20:00  01/01/2017 20:15:00
4   01/01/2017 02:15:00  01/01/2017 00:15:00
5   02/01/2017 15:15:00  03/01/2017 00:30:00
6   03/01/2017 07:00:00  04/01/2017 09:15:00

I would like to count every 15 min for an entire year how many items have started but not finished, so count the number of times with a start time greater or equal than the time I'm looking at and an end time less or equal than the time I'm looking at.
I'm looking for an approach using tidyverse/dplyr if possible.
Any help or guidance would be very much appreciated.

A: If I understand correctly, the OP wants to count the number of simultaneously active events.
One possibility to tackle this question is the coverage() function from Bioconductor's IRange package. Another one is to aggregate in a non-equi join which is available with the data.table package.
Non-equi join
# create sequence of datetimes (limited to 4 days for demonstration)
seq15 <- seq(lubridate::as_datetime("2017-01-01"),
          lubridate::as_datetime("2017-01-05"), by = "15 mins")
# aggregate within a non-equi join
library(data.table)
result <- periods[.(time = seq15), on = .(Start.Time <= time, End.Time > time),
        .(time, count = sum(!is.na(ID))), by = .EACHI][, .(time, count)]
result

                    time count
  1: 2017-01-01 00:00:00     0
  2: 2017-01-01 00:15:00     1
  3: 2017-01-01 00:30:00     1
  4: 2017-01-01 00:45:00     1
  5: 2017-01-01 01:00:00     1
 ---
381: 2017-01-04 23:00:00     0
382: 2017-01-04 23:15:00     0
383: 2017-01-04 23:30:00     0
384: 2017-01-04 23:45:00     0
385: 2017-01-05 00:00:00     0

The result can be visualized graphically:
library(ggplot2)
ggplot(result) + aes(time, count) + geom_step()

Data
periods <- readr::read_table(
  "ID     Start.Time             End.Time
1   01/01/2017 00:15:00  01/01/2017 07:15:00
2   01/01/2017 04:45:00  01/01/2017 06:15:00
3   01/01/2017 10:20:00  01/01/2017 20:15:00
4   01/01/2017 02:15:00  01/01/2017 00:15:00
5   02/01/2017 15:15:00  03/01/2017 00:30:00
6   03/01/2017 07:00:00  04/01/2017 09:15:00"
)

# convert date strings to class Date
library(data.table)
cols <- names(periods)[names(periods) %like% "Time$"]
setDT(periods)[, (cols) := lapply(.SD, lubridate::dmy_hms), .SDcols = cols]
periods

   ID          Start.Time            End.Time
1:  1 2017-01-01 00:15:00 2017-01-01 07:15:00
2:  2 2017-01-01 04:45:00 2017-01-01 06:15:00
3:  3 2017-01-01 10:20:00 2017-01-01 20:15:00
4:  4 2017-01-01 02:15:00 2017-01-01 00:15:00
5:  5 2017-01-02 15:15:00 2017-01-03 00:30:00
6:  6 2017-01-03 07:00:00 2017-01-04 09:15:00


text:
Q: how to loop through an array to hide items i have an html form in which the user clicks on the plus sign and it shows you a list of items, if you click on a minus sign it will hide those items
as follows:

                                        ${categoryGrouping.name}
                                        add
                                        remove

                                            ${user.firstName} ${user.lastName}

${user.emailAddress || 'mock@email.com'}

in type script
async Activate(user: userListModel[], department: any) {
        this.categoryDepartment.forEach(x => {
            x.hideDetails = true;
        });

            this.categoryDepartmentTypes = await this.getTypes(user, department.name);
            department.hideDetails = false;

    }

    async DeActivate(user: userListModel[], department: any) {

        department.hideDetails = true;
    }

this.categoryDepartment stores my array as follows:
0:{hideDetails:true, name:"Hello"}
1:{hideDetails:false,name:"Test"}

so the above looks as the following image

so now for example if i had to click on the "Hello" plus sign while the details for "Test" is open it  would close "Test".
How can i loop through the departments to have it remain open but only when i click the minus then it should close.
I need to pass in the department name to this await this.getTypes(user, department.name); method, so only the item i click on should pass that name in and not all the department names.
does anyone know how i can achieve this?
i tried doing the following
if (this.categoryDepartment.find(x => x.name == department.name)){
            this.categoryDepartmentTypes = await this.getTypes(user, department.name);
            department.hideDetails = false;
        }

but it still does the same thing, it closes on the next item i click on

A: You hide everything in this loop:
    this.categoryDepartment.forEach(x => {
        x.hideDetails = true;
    });

So you can remove it.


text:
Q: floating element extends past footer I am working on making a "school" type website which will have a secondary navigation contained within the "classroom" pages. I have the secondary navigation setup as an accordion which is contained within  and  tags. The aside element is set to a fixed position using the css aside { position: absolute; height: 700px;}. The issue that I am having is that my  section is sitting in the middle of my  section. I have tried using the css property of clear: both; for the footer section but this has no effect.

The relevant css code is:
#footerContain {
    clear: both;
}
aside {
    font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", serif;
    font-size: 18px;
    margin: 2% 2% 6% 0%;
    padding-right: 3%;
    position: absolute;
    border-radius: 7px;
    top: 165px;
    width: 20%;
    height: 900px;
}
section {
    margin-left: 23%;
}

here is a jsFidle example of what I am getting: https://jsfiddle.net/Dragoonman/1rx6dchc/
Any and all help figuring this one out would be great.

A:

Main Div

Section

Aside

Footer

A: Take a look at here for possible solutions:
1- You need to set a height which matches your section.
height: 350px;

2- Set the overflow on the aside (either to hidden or scroll)
 overflow-y: hidden;

2- set the right top for your asside
top: 20px;

And that's it.

A: Maybe something like:

* {
 box-sizing: border-box;
 margin: 0;
 padding: 0;
}
.container {
 width: 100%;
}
.row {
 width: 100%;
 overflow: auto;
}
aside {
 width: 20%;
 background-color: red;
 float: left;
}
section {
 margin-left:20%;
 width: 80%;
 background-color: blue;
 vertical-align: top;
}
#footerContain {
 width: 100%;
 height: 200px;
 background-color: grey;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempor ipsum in auctor commodo. Vestibulum non erat imperdiet mi malesuada interdum. In odio ante, luctus id eros non, vestibulum dictum ex. Mauris ac sagittis nisl. Maecenas non facilisis velit. Maecenas accumsan elit sed sem sagittis laoreet. Aenean eu luctus nisl. Praesent bibendum, dolor ut elementum posuere, lectus ex sagittis risus, nec lacinia est mauris ut magna. Nam vestibulum, mi nec tempor lacinia, libero odio euismod augue, et volutpat purus dui in quam.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempor ipsum in auctor commodo. Vestibulum non erat imperdiet mi malesuada interdum. In odio ante, luctus id eros non, vestibulum dictum ex. Mauris ac sagittis nisl. Maecenas non facilisis velit. Maecenas accumsan elit sed sem sagittis laoreet. Aenean eu luctus nisl. Praesent bibendum, dolor ut elementum posuere, lectus ex sagittis risus, nec lacinia est mauris ut magna. Nam vestibulum, mi nec tempor lacinia, libero odio euismod augue, et volutpat purus dui in quam. Vestibulum aliquet dui at nulla volutpat, quis aliquam nulla viverra. Quisque in sapien sit amet tortor sagittis congue. Quisque magna odio, pharetra porta volutpat consequat, molestie sed lacus. Nam eget massa diam. Praesent accumsan ante nisl, in bibendum lorem ullamcorper a. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer id magna ut purus maximus aliquam eget in quam.

Whatever element is bigger, aside or section, pushes the footer down, so it can grow as needed.

A: You can use "clear: both" when you have floating elements. In this case, I recommend you setup min-height 100vh (which is the screen height) in the body and use position:absolute in the footer element.
body { min-height: 100vh; }
#footerContain {position: absolute; bottom: 0;}

If you want full width footer:
#footerContain {
  position: absolute;
  bottom: 0;
  display block;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
  height: 30px;
  line-height: 30px;
}

A: *

*Reduce gap between aside and title.
top: 20px;

*Set height property of aside
height: 100%;

*Set overflow-y property of aside
overflow-y: scroll;

*increase section margin to accommodate scroll bar
margin-left: 25%;

These edits put the footer under the aside and lets the user scroll through the aside no matter how long it gets. Hope this helps.
https://jsfiddle.net/1rx6dchc/4/