text:
Q: Horizontal merging of columns from multiple files I tried to write a script that takes two columns each from multiple files and concatenates them together horizontally. The problem is, the content of the columns is not in the same order in the files, so the data needs to be sorted before concatenating.
This is what I've come up with so far:
!/bin/bash

ls *.txt > list

while read line; do
    awk '{print $2}' "$line" > f1
    awk '{print $8}' "$line" > f2
    paste f1 f2 | sort > "$line".output
done < list

ls *.output > list2

head -n 1 list2 > start

while read line; do
    cat "$line" > output
done < start

tail -n +2 list2 > list3

while read line; do
    paste output "$line" | cat > output
done < list3

My programing is probably not that efficient, but it does what I want it to do, with the exception of the second last line, which does not concatenate the files together properly. If I enter the line in the command-line it works fine, but in the while loop it misses columns.
The data files look like this:
bundle_id   target_id   length  eff_length  tot_counts  uniq_counts est_counts  eff_counts  ambig_distr_alpha   ambig_distr_beta    fpkm    fpkm_conf_low   fpkm_conf_high  solvable    tpm
1   comp165370_c0_seq1  297 0.000000    0   0   0.000000    0.000000    0.000000e+00    0.000000e+00    0.000000e+00    0.000000e+00    0.000000e+00    F   0.000000e+00
2   comp75418_c0_seq1   1371    852.132325  35  0   0.005490    0.008832    8.287807e-04    5.283100e+00    4.583199e-04    0.000000e+00    2.425095e-02    T   6.225299e-04
3   comp76235_c0_seq1   1371    871.645349  44  9   43.994510   69.198412   2.002884e+00    3.142003e-04    3.590738e+00    3.516301e+00    3.665174e+00    T   4.877251e+00
4   comp31034_c0_seq1   379 251.335522  14  0   7.049180    10.629771   1.000000e+00    1.000000e+00    1.995307e+00    0.000000e+00    5.957982e+00    F   2.710199e+00
5   comp36102_c0_seq1   379 234.689179  14  0   6.950820    11.224893   1.000000e+00    1.000000e+00    2.107017e+00    0.000000e+00    6.350761e+00    F   2.861933e+00
6   comp26522_c0_seq1   220 0.000000    0   0   0.000000    0.000000    0.000000e+00    0.000000e+00    0.000000e+00    0.000000e+00    0.000000e+00    F   0.000000e+00
7   comp122428_c0_seq1  624 0.000000    0   0   0.000000    0.000000    0.000000e+00    0.000000e+00    0.000000e+00    0.000000e+00    0.000000e+00    F   0.000000e+00

And I need the target_id and the eff_counts columns.
This is not the complete problem, but I thought I'd start small. Later I want the target ID only to be present once at the beginning. And I would like to have a heading in the new file that contains the name of the file that contributed to the particular column.
target_id             file_1        file_2        file_3
comp26522_c0_seq1     0.000000      [number]      [number]
comp31034_c0_seq1     10.629771     [number]      [number]
comp36102_c0_seq1     11.224893     [number]      [number]
comp75418_c0_seq1     0.008832      [number]      [number]
comp76235_c0_seq1     69.198412     [number]      [number]
comp122428_c0_seq1    0.000000      [number]      [number]
comp165370_c0_seq1    0.000000      [number]      [number]

Edit:
I added more information to the examples. The [number] are only placeholders; in reality, they would be numbers similar to the row under file_1. Also, the header "file_1" would be the name of the input file. And the target_id should be sorted. All files should include the same target_ids, but all in a different order.
Edit two: output
I tested it with four files and the output looks like this:
    comp0_c0_seq1   0.000000
    comp100000_c0_seq1      1.919404
    comp100002_c0_seq1      2.118776
    comp100003_c0_seq1      0.072916
    comp100004_c0_seq1      0.000000
    comp100005_c0_seq1      0.000000
    comp100006_c0_seq1      1.548160
    comp100007_c0_seq1      7.616481
    comp100008_c0_seq1      0.000000
    comp100009_c0_seq1      1.374209

there is an empty column to the left of the first column with data. And only the data from the last file is present.
Thank you for your help!
Update:
I solved the issue I had with the second last line. This is the code I used:
while read line; do
     join output "$line" > output2
     cat output2 > output
done < list3

This is the output:
comp0_c0_seq1      0.000000 0.000000 0.000000 0.000000
comp100000_c0_seq1 1.919404 1.919404 0.000000 1.919404
comp100002_c0_seq1 2.118776 2.118776 2.225852 2.118776
comp100003_c0_seq1 0.072916 0.072916 1.228136 0.072916
comp100004_c0_seq1 0.000000 0.000000 0.000000 0.000000
comp100005_c0_seq1 0.000000 0.000000 1.982851 0.000000
comp100006_c0_seq1 1.548160 1.548160 1.902749 1.548160
comp100007_c0_seq1 7.616481 7.616481 0.000000 7.616481
comp100008_c0_seq1 0.000000 0.000000 0.000000 0.000000
comp100009_c0_seq1 1.374209 1.374209 1.378667 1.374209

Now I just need to figure out how to add a header with all the file names to the top of the file.

A: You could also begin with a collection of the filenames and the columns of interest like below and than transpose it using a solution like here: Transpose CSV data with awk (pivot transformation)
find . -name "bundle*.txt" -exec awk 'NR>1 {print FILENAME,$2,$8}' {} \; | sed 's/.\//''/' > superbundle.txt

Explanation
- find all files with a name like bundle*.txt
- execute an awk statement which shows the filename and column 2 and 8 (without the header)
- use sed to remove ./ from the filenames
Now we can use the "superbundle.txt" and transpose it using the mentioned solution from jaypal.
$ cat transpose.awk
{
    if(!($1 in filenames)) { filename[++types] = $1 }; filenames[$1]++
    if(!($2 in target_ids)) { target_id[++num] = $2 }; target_ids[$2]++
    map[$1,$2] = $3
}
END {
    printf "%s\t" ,"target_id";
    for(ind=1; ind<=types; ind++) {
        printf "%s%s", sep, filename[ind];
        sep = "\t"
    }
    print "";
    for(target=1; target<=num; target++) {
        printf "%s", target_id[target]
        for(val=1; val<=types; val++) {
            printf "%s%s", sep, map[filename[val], target_id[target]];
        }
        print ""
    }
}

Below output only shows three files, since I've only created 3 bundle example text files.
$ awk -f transpose.awk superbundle.txt | column -t
target_id           bundle.txt  bundle2.txt  bundle3.txt
comp165370_c0_seq1  0.000000    1.000000     0.000000
comp75418_c0_seq1   0.008832    2.008832     1.008832
comp76235_c0_seq1   69.198412   3.198412     2.198412
comp31034_c0_seq1   10.629771   4.629771     3.629771
comp36102_c0_seq1   11.224893   5.224893     4.224893
comp26522_c0_seq1   0.000000    6.000000     4.000000
comp122428_c0_seq1  0.000000    7.000000     4.000000

A: After a lot of reading and testing, I finally came up with a script that does exactly what I want.
It might not be the most efficient use of bash in places, but it works just fine.
ls *.xprs > list

while read line; do
    echo "parsing $line"
    awk '{print $2}' "$line" > f1
    awk '{print $8}' "$line" > f2
    paste f1 f2 | sort | head -n -1 > "$line".output
done < list

ls *.output > list2

head -n 1 list2 > start

while read line; do
    cat "$line" > output
done < start

tail -n +2 list2 > list3

while read line; do
    join output "$line" > output2 2>/dev/null
    cat output2 > output
done < list3
sed '1i Contig_ID' list2 | awk '{printf("%s ", $0)}' | sed -e '$a\' | sed 's/.xprs.output//g' > list4

cat list4 output > results.txt


text:
Q: How to get MIME-TYPE from Base 64 String of PPT or docx? I am getting base64 string from append and I am then decoding it in PHP and saving it in the database.
This string can be any file .pdf, .img, .docx, .zip, .ppt, .docx etc.
My base64 string does not include the mime-type for example 'data:application/pdf;base64' part. So I need to get mime type of base64.
Is there any way to solve this solution with PHP?
Currently, I am using this code and it is working fine for Images and pdf.
$file = base64_decode($formData['image'], true)

$mineType = $this->getMimeType($file);

public function getBytesFromHexString($hexdata)
{
    for ($count = 0; $count < strlen($hexdata); $count += 2)
        $bytes[] = chr(hexdec(substr($hexdata, $count, 2)));

    return implode($bytes);
}

public function getMimeType($imagedata)
{
    $imagemimetypes = array(
        "jpg" => "FFD8",
        "png" => "89504E470D0A1A0A",
        "gif" => "474946",
        "bmp" => "424D",
        "tiff" => "4949",
        "pdf" => "25504446",
        "docx"=> "504B0304",
        "doc" => "D0CF11E0A1",
        "xlsx"=> "504B030414000600",
        "xls" => "D0CF11E0A1B11AE1"
    );

    foreach ($imagemimetypes as $mime => $hexbytes) {
        $bytes = $this->getBytesFromHexString($hexbytes);
        if (substr($imagedata, 0, strlen($bytes)) == $bytes){
            return $mime;
        }
    }

    return false;
}

A: function base64_mimetype(string $encoded, bool $strict = true): ?string {
    if ($decoded = base64_decode($encoded, $strict)) {
        $tmpFile = tmpFile();
        $tmpFilename = stream_get_meta_data($tmpFile)['uri'];

        file_put_contents($tmpFilename, $decoded);

        return mime_content_type($tmpFilename) ?: null;
    }

    return null;
}

http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

redpajama_set_name: RedPajamaStackExchange


text:
Q: Showing that an integer solution does not exist I am given a quadratic form (non-homogeneous) in 12 variables and I want to show that it does not have an integer solution.
The 'FindInstance' and 'Solve' command both give {} while 'Reduce' returns 'false'. So that is good news. However, I want to use the fact in a paper, and simply relying on a mathematica result is not the good way to go in algebraic geometry.
My next step would have been to consider the equation modulo different prime numbers and have mathematica check for solutions there. As soon as I find a prime number such that the equation does not have a solution modulo that prime, I could start to think about an argument there. However, starting from p=5, the program refuses to run. Can an equation be so complicated that the program does not even try to solve it, or what could be the issue here?
I'm using the following command:
 FindInstance[
 c* (-4* c + 2* d) + d* (2 *c - 4 *d + 2* e) +
   e* (2* d - 4 *e + 2* f) + (-2 *b + 2 *f + 2* g - 4* h)* h +
   f* (2* e - 4* f + 2* h) + g* (-4* g + 2* h) +
   j* (126* b - 28* i - 196* j + 182* k) +
   i* (56* a + 154* b - 140* i - 28* j - 63* k - 560 *l) +
   k *(42* a - 28* b - 63* i + 182 *j - 266 *k - 420* l) + (238 *a +
      560 *b - 560 *i - 420* k - 2380 *l) *l +
   a* (-24* a - 56* b + 56* i + 42 *k + 238 *l) +
   b *(-56* a - 220 *b - 2 *h + 154* i + 126* j - 28* k +
      560* l) == -2, {a, b, c, d, e, f, g, h, i, j, k, l},
 Modulus -> 5]

Additonally: apart from Simplify and FullSimplify, does mathematica have special commands for quadratic forms to transform them into a standard form?

A: Here is something of a brute-force approach.
poly = c*(-4*c + 2*d) + d*(2*c - 4*d + 2*e) +
   e*(2*d - 4*e + 2*f) + (-2*b + 2*f + 2*g - 4*h)*h +
   f*(2*e - 4*f + 2*h) + g*(-4*g + 2*h) +
   j*(126*b - 28*i - 196*j + 182*k) +
   i*(56*a + 154*b - 140*i - 28*j - 63*k - 560*l) +
   k*(42*a - 28*b - 63*i + 182*j - 266*k - 420*l) + (238*a + 560*b -
      560*i - 420*k - 2380*l)*l +
   a*(-24*a - 56*b + 56*i + 42*k + 238*l) +
   b*(-56*a - 220*b - 2*h + 154*i + 126*j - 28*k + 560*l);
vars = Variables[poly];

Create the corresponding symmetric quadratic form.
qform = Normal[CoefficientArrays[poly, vars][[3]]];
qform2 = (qform + Transpose[qform])/2;

Check this:
Expand[vars.qform2.vars - poly]

(* Out[161]= 0 *)

It is negative definite (easy to check: all eigenvalues are negative). Find the Cholesky decomposition of its negative.
cd = CholeskyDecomposition[-qform2];

Check this:
Max[Abs[Transpose[cd].cd + qform2]]

(* Out[163]= 0 *)

Integer solutions of the form ivec will satisfy ivec.qform2.ivec==-2. This in turn means we have a fundamental equation:
(cd.ivec) . (cd.ivec) == 2

If it can be shown that no integer vector ivec can satisfy this, then that does the job. We'll show how to (fairly tightly) bound the search space, after which one can do an exhaustive search.
Note that any integer vector that works is of course an integer combination of the 12 unit vectors (our quadratic form is 12x12 because we have 12 variables in the polynomial). For a vector of the form cd.ivec, if it has 1-norm larger than or equal to 5 then a standard argument shows the 2-norm (Euclidean length) must be at least 5/12*sqrt(12) which is in turn slightly larger than sqrt(2) (so the dot product of this vector with itself would exceed 2). (For fixed 1-norm, the 2-norm is minimized where all components are equal). We can use this to bound the search space. Actually we can tighten to 2 sqrt(6) plus a small increment to allow for approximate arithmetic.
Another perhaps stronger constraint is that no individual component can exceed sqrt(2) in magnitude.
The optimization step uses mixed linear integer programming, with integer variables for the multiples of the unit vectors. We use a constraint that a certain one (in a loop) be at least 1. As noted above we also constraint that the 1-norm not exceed 2 sqrt(6)+epsilon and that individual components not exceed sqrt(2) in size. We use the fact that negating ivec gives a vector cd.ivec of all opposite signs (thus not changing the fundamental equation) so we only need compute upper bounds. I do the computation at machine precision so a strictly symbolic proof would require redoing the ILP in exact arithmetic (more than I'll do but by no means impossible).
We use cvars below to form the integer vector, absvars to denote absolute values of components of cd.cvars, impose constraints for sizes, and iteratively force each component of cvars to be greater-equal to one. Note that absvars need not be integer valued.
cvars = Array[cc, Length[vars]];
absvars = Array[aa, Length[vars]];
cvec = cd.cvars;
c1 = Thread[cvec <= absvars];
c2 = Thread[-cvec <= absvars];
c3 = Map[0 <= # <= Sqrt[2] &, absvars];
c4 = Total[absvars] <= 2*Sqrt[6] + 1/1000;
c5 = Element[cvars, Integers];
bounds = Table[c6 = cc[j] >= 1;
   NMaximize[{cc[j], Join[c1, c2, c3, {c4, c5, c6}]},
    Join[cvars, absvars]], {j, Length[cvars]}];
bounds[[All, 1]]

(* Out[220]= {1., 2., 3., 4., 2., 2., 4., 1., 2., 1., 1., 1.} *)

This give a large, but computationally tractable, search space (<100M cases, by my count). One can perhaps improve matters by breaking into more special cases though. Here is our vector whose norm-square needs to be 2.
cvec

(* Out[244]= {2 cc[1] - cc[2], Sqrt[3] cc[2] - (2 cc[3])/Sqrt[3],
 2 Sqrt[2/3] cc[3] - Sqrt[3/2] cc[4],
 Sqrt[5/2] cc[4] - 2 Sqrt[2/5] cc[7],
 2 Sqrt[55] cc[5] + cc[7]/Sqrt[55] - (63 cc[8])/Sqrt[55] -
  7 Sqrt[11/5] cc[9] + (14 cc[10])/Sqrt[55] + (28 cc[11])/Sqrt[55] -
  56 Sqrt[5/11] cc[12], 2 cc[6] - cc[7],
 2 Sqrt[19/55] cc[7] + (63 cc[8])/(2 Sqrt[1045]) +
  7/2 Sqrt[11/95] cc[9] - (7 cc[10])/Sqrt[1045] - (14 cc[11])/Sqrt[
  1045] + 28 Sqrt[5/209] cc[12],
 7/2 Sqrt[953/95] cc[8] - (3331 cc[9])/(2 Sqrt[90535]) - (
  4499 cc[10])/Sqrt[90535] + (882 cc[11])/Sqrt[90535] -
  1764 Sqrt[5/18107] cc[12],
 2 Sqrt[34/953] cc[9] + (89 cc[10])/(2 Sqrt[32402]) -
  14 Sqrt[2/16201] cc[11] + 140 Sqrt[2/16201] cc[12],
 1/2 Sqrt[5271/34] cc[10] - 26 Sqrt[14/12801] cc[11] +
  260 Sqrt[14/12801] cc[12],
 2 Sqrt[38/753] cc[11] - (7 cc[12])/Sqrt[28614], Sqrt[7/38] cc[12]} *)

The first and sixth components are fairly convenient in form.
cvec[[{1, 6}]]

(* Out[246]= {2 cc[1] - cc[2], 2 cc[6] - cc[7]} *)

Neither can exceed 1 in size so one can create 3x3=9 separate cases from:
{2*cc[1] - 1 <= cc[2] <= 2*cc[1] + 1,
 2*cc[6] - 1 <= cc[7] <= 2*cc[6] + 1}

Not sure whether this will help substantially. The original formulation I had would benefit but this improved one might not.
--- edit ---
We can get further improvement by simply noting that any sum of two elements in cd.ivec cannot exceed 2 (because the 2-norm would be minimized when each was 1, and that 2-norm squared would then be the target value of 2. This will tighten the search space.
cvars = Array[cc, Length[vars]];
absvars = Array[aa, Length[vars]];
cvec = cd.cvars;
c1 = Thread[cvec <= absvars];
c2 = Thread[-cvec <= absvars];
c3 = Map[0 <= # <= Sqrt[2] &, absvars];
c4 = Total[absvars] <= 2*Sqrt[6] + 1/1000;
c5 = Element[cvars, Integers];
c7 = Map[0 <= # <= 2 &,
   Union[Flatten[Outer[Plus, absvars, absvars]]] /. 2*_ :> Nothing];
bounds = Table[c6 = cc[j] >= 1;
   NMaximize[{cc[j], Join[c1, c2, c3, {c4, c5, c6}, c7]},
    Join[cvars, absvars]], {j, Length[cvars]}];
bounds[[All, 1]]

(* Out[231]= {1., 1., 2., 3., 2., 2., 3., 1., 2., 1., 1., 1.} *)

This brings down the size of the search space.
Round[Times @@ Map[2*# + 1 &, bounds[[All, 1]]]]

(* Out[232]= 22325625 *)

One can do similarly with triples of the absolute value variables, restricting sums to be no larger than 3 sqrt(2/3). This gives a healthy improvement, bringing the bounds to {1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1.}, for a search space of less than 10^6 integer combinations for the original variables.
--- end edit ---


text:
Q: Como poner imagen de fondo en un panel en JAVA Tengo una clase donde tengo el siguiente codigo:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class imagenfondo extends JPanel{
private Image fondo=null;
@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(fondo,0,0,getWidth(),getHeight(),null);
}
public void setImage(String image){
    if (image!=null) {
        fondo=new ImageIcon(getClass().getResource(image)).getImage();
    }
  }
}

y en jframe tengo lo siguiente:
 public menu() {
    initComponents();
    imagenfondo image=new imagenfondo();
    image.setImage("/imagenes/fondo.jpg");
    setContentPane(image);
 }

pero resulta que me muestra el fondo de la siguiente manera:

pero resulta que yo ya tengo un contenido, entonces cuando quito la imagen de fondo me sale asi:

como hago para poner el imagen de fondo,pero que me salga detras de mi contenido?


text: Q: Изменение привилегий файла su Из-за своей невнимательности и желании установить Linux из Linux Deploy изменил привилегии к файлу su, что находится в /system/xbin. Теперь, как бы я не пытался, назад вернуть не могу. Помогите решить данный вопрос. Телефон Meizu M5c.


text:
Q: Rounded QuickContactBadge with text I have a listview with a QuickContactBadge and then the contact's name. The problem is the badge is a square, and if the contact does not have an image, then it is just blank. I want a circular picture or just the first initial of the contacts like in android lollipop:

I tried the solution to this question, but I couldn't get it to work. Maybe I just implemented it wrong? This is what I have:
ContactsTab.java:
public class ContactsTab extends ListFragment implements LoaderCallbacks<Cursor> {

    private CustomAdapter mAdapter;
    private Cursor mCursor;
    private String currentQuery;
    private int mIdColumn;
    private int mLookupKeyColumn;
    private Uri mContactUri;
    private QuickContactBadge mBadge;
    private static final String[] PROJECTION = {
            Contacts._ID,
            Contacts.DISPLAY_NAME_PRIMARY,
            Contacts.LOOKUP_KEY,
            Contacts.PHOTO_THUMBNAIL_URI,
            Contacts.HAS_PHONE_NUMBER,
    };
    private static final String[] FROM = { Contacts.PHOTO_THUMBNAIL_URI, Contacts.DISPLAY_NAME_PRIMARY };
    private static final int[] TO = { R.id.badge, R.id.contact_text };
    private static final String SELECTION = "(" + Contacts.IN_VISIBLE_GROUP + " = 1) AND (" + Contacts.HAS_PHONE_NUMBER + " != 0 )";

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

        mAdapter = new CustomAdapter(getActivity(), R.layout.contacts_list_item, null, FROM, TO, 0)
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        setListAdapter(mAdapter);
        getLoaderManager().initLoader(0, null, this);
        getListView().setDivider(null);
        getListView().setDividerHeight(0);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri contentUri = Contacts.CONTENT_URI;

        return new CursorLoader(getActivity(),
                contentUri,
                PROJECTION,
                SELECTION,
                null,
                Contacts.DISPLAY_NAME_PRIMARY + " ASC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }
}

CustomAdapter.java:
public class CustomAdapter extends SimpleCursorAdapter {
    private Cursor _cursor;
    private Context _context;
    private String[] _from;
    private int[] _to;
    private QuickContactBadge badge;
    private String lookUpKey;

    public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
        _cursor = c;
        _context = context;
        _from = from;
        _to = to;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        int id = cursor.getColumnIndex(ContactsContract.Data._ID);

        lookUpKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.LOOKUP_KEY));

        badge = (QuickContactBadge) view.findViewById(R.id.badge);
        badge.assignContactUri(ContactsContract.Contacts.getLookupUri(id, lookUpKey));
        badge.setImageBitmap(generateCircleBitmap(R.color.accent, 42, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY.substring(0,1)));
    }

    public static Bitmap generateCircleBitmap(int circleColor, float diameterDP, String text){
        final int textColor = 0xffffffff;

        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        float diameterPixels = diameterDP * (metrics.densityDpi / 160f);
        float radiusPixels = diameterPixels/2;

        // Create the bitmap
        Bitmap output = Bitmap.createBitmap((int) diameterPixels, (int) diameterPixels, Bitmap.Config.ARGB_8888);

        // Create the canvas to draw on
        Canvas canvas = new Canvas(output);
        canvas.drawARGB(0, 0, 0, 0);

        // Draw the circle
        final Paint paintC = new Paint();
        paintC.setAntiAlias(true);
        paintC.setColor(circleColor);
        canvas.drawCircle(radiusPixels, radiusPixels, radiusPixels, paintC);

        // Draw the text
        if (text != null && text.length() > 0) {
            final Paint paintT = new Paint();
            paintT.setColor(textColor);
            paintT.setAntiAlias(true);
            paintT.setTextSize(radiusPixels * 2);
            paintT.setTypeface(Typeface.SANS_SERIF);
            final Rect textBounds = new Rect();
            paintT.getTextBounds(text, 0, text.length(), textBounds);
            canvas.drawText(text, radiusPixels - textBounds.exactCenterX(), radiusPixels - textBounds.exactCenterY(), paintT);
        }

        return output;
    }
}

A: Create a custom drawable and you can do it
file : drawable/contact_badge_round.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">

    <size android:width="32dp" android:height="32dp"/>

    <gradient android:centerColor="#123456"
              android:startColor="#123456"
              android:endColor="#123456"
        />

</shape>

then in your layout create a Button and set the background as contact_badge_round
 <Button
        android:id="@+id/roundContact"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:text="A"
        android:gravity="center"
        android:background="@drawable/background_new_entity_symbol"
       />

Done cheers!


text:
Q: JS: extracting href and src attributes URLs from DOM as absolute I'm using JQuery to extract the src and href from elements in the DOM as follows:
var mysrc;
$('img[src]').each(function (index) {
   mysrc = $(this).attr('src');
   // convert relative path to absolute url
});

However many of these paths to images or in link href are relative, not absolute. Sometimes they start from the web root like this: /blah/img.jpg and something they go up or down one directory: ../blah/img.jpg.
I'd like to make all these paths as absolute URLs, and I haven't found a script to do this. I know how to extract the host of a given page from the location, but then i'm missing all the logic that would convert those relative paths into absolute urls. Any idea where I could find something to do this in Javascript/JQuery, or how I should proceed.
Thanks for your help,

A: .prop() returns the calculated property value, ie the absolute path.
Instead of using a jQuery method, you can also use a plain this.src.
$('img[src]').each(function (index) {
   // var mysrc = $(this).prop('src');  //<-- jQuery
   var mysrc = this.src;
   // Why do you want to get the absolute path, by the way?
});

A: You probably want to get the app context - I don't think it's available in javascript. You might know it per app though.
In JSP you can get context like this:
var contextPath = "<%=request.getContextPath()%>";
other server-side languages should have similar constructs. Having context you could form absolute path like
Absolute path = window.location - contextPath + relativeURL;
so, if your URL is
http://mysite.com/foo/bar and context is http://mysite.com/foo/ and the relative path is "../somedir/mypic.jpg" then the absolute path would be
/bar/../somedir/mypic.jpg


text:
Q: How do I use android room to create Entity which has multi-list or nested list? I'm using Room to store some data. but the json is slightly complicated. How can I use Room to do this?
This is my json:
{
  "pagination" : {
    "total" : 50,
    "limit" : 30,
    "page" : 1
  },
  "list" : [
    {
      "guid" : "123",
      "data" : {
        "light" : 240,
        "snoring" : 5,
        "talking" : [
          {
            "time" : 1556437167,
            "file" : "file/file.file"
          }
        ],
        "turnover" : 14,
        "temp" : "25.5",
        "duration" : 480,
        "hum" : "78.6",
        "sleep" : [
          {
            "stage" : 1,
            "time" : 1556437167
          }
        ],
        "deep" : 180
      },
      "date" : 1556437167
    }
  ]
}

How do I use @Relation,@Embedded and stuff to store/convert this json to Room's Entity?

A: I think you can do something like this.
@Entity
data class List(
    val date: Int,
    val guid: String,
    @Embedded val data: Data
) {
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null
}

@Entity
data class Data(
    val deep: Int,
    val duration: Int,
    val hum: String,
    val light: Int,
    val snoring: Int,
    val temp: String,
    val turnover: Int
){
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null
}
@Entity(
    foreignKeys = [
        ForeignKey(
            entity = Data::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("data_id")
            )
    ]
)
data class Talking(
    val `file`: String,
    val time: Int,
    val data_id: Int
){
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null
}

@Entity(
    foreignKeys = [
        ForeignKey(
            entity = Data::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("data_id")
        )
    ]
)
data class Sleep(
    val stage: Int,
    val time: Int,
    val data_id: Int
){
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null
}

You have a list of objects And these objects are your actual data
that you might need to store using room.
So inside your list you have 3 items "guid", "data", "date"
Except data other two values "guide" and "date can be saved because they are primitive data type. for data you need another class. And for the Talking and Sleep you need other classes.


text:
Q: Побайтная запись данных в структуру С# Есть структура данных (С#) необходимо принимая данные из SerialPort записать их в  структуру побайтно.
Код объявления структуры (VS2010)
Структура упакована побайтно, размер соответствует.
:
// ------------------ telemetry data structures
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct BMS //  BMS telemetry data
    {
        public ushort voltage;
        public short current;
        public sbyte temperature;
        public byte status;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct MOTOR //  Traction MOTOR telemetry data
    {
        sbyte acceleration;
        short current;
        short speed;
        sbyte motor_temp;
        sbyte controller_temp;
        byte status;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct GENERATOR //  Gasoline GENERATOR telemetry data
    {
        byte fuel_level;
        short speed;
        short current;
        ushort voltage;
        sbyte motor_temp;
        sbyte generator_temp;
        sbyte controller_temp;
        byte status;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct CABLE_REEL //  CABLE REEL telemetry data
    {
        sbyte force;
        short speed;
        sbyte motor_temp;
        sbyte controller_temp;
        byte status;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct UTP_TELEMETRY // UTP-1 telemetry packet struct
    {
        public BMS bms1;
        public BMS bms2;
        public MOTOR left_motor;
        public MOTOR right_motor;
        public GENERATOR generator;
        public CABLE_REEL reel;
    }

    //UTP_TELEMETRY packet;

    int packet_data_len = Marshal.SizeOf(typeof(UTP_TELEMETRY));  // number of bytes for data (45 bytes at the moment)

    // defines exactly as union in C++

    [StructLayout(LayoutKind.Explicit, Size=45)]
    public struct UNION_BUFF
    {
        [FieldOffset(0)]
        public byte buff;
        //public byte[] buff;

        [FieldOffset(0)]
        public UTP_TELEMETRY data_packet;
    }

   public UNION_BUFF data_buffer;

проект unsafe, разные способы испытал, но не знаю тонкостей работы с указателями С#, ничего не получается. пробовал запись по указателю, по индексу buff[index], еще несколько разных идей и все никак.
Как необходимо организовать запись побайтно в данную структуру?

A: Ну например, для структур, состоящих только из примитивных полей, подойдёт такой хелпер:
static void FillFromStream<T>(ref T t, Stream stream) where T : struct
{
    object boxed = t;
    using (var br = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true))
    {
        var fields = typeof(T).GetFields().OrderBy(f => f.MetadataToken);
        foreach (var field in fields)
        {
            if (!field.FieldType.IsPrimitive)
                throw new NotImplementedException("nested compound types");
            // for primitive types:
            if (!primitiveExtractors.TryGetValue(field.FieldType, out var extractor))
                throw new NotImplementedException("unsupported primitive type");
            var value = extractor(br);
            field.SetValue(boxed, value);
        }
    }
    t = (T)boxed;
}

Вспомогательная таблица:
static Dictionary<Type, Func<BinaryReader, object>> primitiveExtractors =
    new Dictionary<Type, Func<BinaryReader, object>>()
    {
        [typeof(sbyte)]  = br => br.ReadSByte(),
        [typeof(byte)]   = br => br.ReadByte(),
        [typeof(short)]  = br => br.ReadInt16(),
        [typeof(ushort)] = br => br.ReadUInt16(),
        [typeof(int)]    = br => br.ReadInt32(),
        [typeof(uint)]   = br => br.ReadUInt32(),
        [typeof(long)]   = br => br.ReadInt64(),
        [typeof(ulong)]  = br => br.ReadUInt64(),
        [typeof(float)]  = br => br.ReadSingle(),
        [typeof(double)] = br => br.ReadDouble()
    };

Как вы видите, без unsafe и прочих небезопасных методов можно обойтись.
Не забудьте открыть доступ у полям.

.OrderBy(f => f.MetadataToken) нужно для того, чтобы порядок полей соответствовал текстуальному порядку.

A: Например, используя Marshal.PtrToStructure:
object ByteArrayToStructure(byte[] bytearray, Type t)
{
    if (t.IsValueType == false) throw new ArgumentException("Type is not structure");
    IntPtr p = IntPtr.Zero;
    object obj = null;

    try
    {
        int len = Marshal.SizeOf(t);

        p = Marshal.AllocHGlobal(len);
        Marshal.Copy(bytearray, 0, p, len);
        obj = Marshal.PtrToStructure(p, t);
    }
    finally
    {
        if (p != IntPtr.Zero) Marshal.FreeHGlobal(p);
    }
    return obj;
}

/*...*/

byte[] arr = /*Считать массив байт из потока*/;
MyStruct s = (MyStruct)ByteArrayToStructure(arr,typeof(MyStruct));

Или как-то так (извращенный способ, но не требует выделения промежуточного блока памяти):
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyStruct
{
    /*Список полей*/
    short x;
    short y;
    sbyte a;
    byte b;

    /*Статические методы*/
    [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
    private static extern void CopyMemory(
        [In, Out] ref MyStruct dest,
        [MarshalAs(UnmanagedType.LPArray)] byte[] src,
        int count);

    public static MyStruct ByteArrayToStructure(byte[] bytearray)
    {
        MyStruct obj = new MyStruct();
        CopyMemory(ref obj, bytearray, bytearray.Length);
        return obj;
    }
}

/*...*/

byte[] arr = /*Считать массив байт из потока*/;
MyStruct s = MyStruct.ByteArrayToStructure(arr);


text:
Q: Where does this proof use the fact that $f'$ is continuous? I'm reading part of a proof where $\mathcal{O}$ be an open subset of $\mathbb{R}$, and $f$ is continuously differentiable.
Then the proof starts as follows:

Suppose $f'(x_0) > 0$. Since $x_0$ is an interior point of $\mathcal{O}$ and the function $f' : \mathcal{O} \rightarrow \mathbb{R}$ is continuous, we can choose $r > 0$ such that the closed interval $[x_0 - r, x_0 + r] \subseteq \mathcal{O}$

I don't understand how this follows from continuity. Since $x_0 \in \text{ int } \mathcal{O}$, we can choose an open ball about $x_0$ contained in $\mathcal{O}$. But how can we include the endpoints? I'm guessing that this is where continuity of $f'$ comes into play, but I'm not sure.

A: Since $x_0 \in \mathcal{O}$ where the latter is open, there exists an open interval $(x_0-\delta,x_0 + \delta) \subseteq \mathcal{O}$. In particular,
$$
\left[x_0-\frac{\delta}{2},x_0+\frac{\delta}{2}\right] \subset (x_0-\delta,x_0 + \delta) \subseteq \mathcal{O}.
$$
You are also correct in saying that continuity is not required for this. Although as pointed out in the comments, the continuity of $f^\prime$ is used elsewhere in the proof you are referring to. Namely, we use the continuity of $f^\prime$ together with the fact that $f^\prime(x_0) > 0$ to ensure that $f^\prime > 0$ on $\left[x_0-\frac{\delta}{2},x_0+\frac{\delta}{2}\right]$.
To see why this is possible, it will be enough to establish the following result:

Lemma. Let $O\subseteq \mathbb{R}$ be an open set and $g :O \to \mathbb{R}$ a continuous function on $O$. Assume further that $x_0 \in O$ is such that $g(x_0) > 0$. Then, there exists a compact interval
  $$
\left[x_0-{\delta},x_0+{\delta}\right] \subseteq {O}
$$
  on which $g$ is strictly positive.

To prove this, let $\epsilon := g(x_0)/2 > 0$. Using the continuity of $g$, we can find $\delta_1 > 0$ such that
$$
g(x_0) - g(x) \leq |g(x)-g(x_0)| < \epsilon = \frac{g(x_0)}{2}
$$
for all $x \in {O}$ with $|x-x_0| < \delta_1$. Hence, one has
$$
g(x) > \frac{g(x_0)}{2} > 0
$$
for all these $x$. On the other hand, because $O$ is open, we can find $\delta_2 > 0$ such that
$$
\left[x_0-{\delta_2},x_0+{\delta_2}\right] \subseteq O.
$$
Taking $0 < \delta < \min(\delta_1,\delta_2)$ then proves the lemma.


text:
Q: Hibernate extend entity - Object was not of the specified subclass - Java I would like to build field which can be String, Boolean or Long. In this case I tried use generics type and inheratiance. All code compiles correctly but when I want to get some parameters from database I got a error like:

Object [id=1] was not of the specified subclass
  [unity.app.domain.Parameter] : Discriminator: 1",

What is more if I want to use post method to adding parameter to DB I got error like this:

"Type definition error: [simple type, class
  unity.app.domain.Parameter]; nested exception is
  com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot
  construct instance of unity.app.domain.Parameter (no Creators, like
  default construct, exist): abstract types either need to be mapped to
  concrete types, have custom deserializer, or contain additional type
  information\n at [Source: (PushbackInputStream); line: 1, column: 1]",

How to resolve this problem?
@Data
@Entity
@Table(name = "parameter")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "parameter", discriminatorType = DiscriminatorType.STRING)
public abstract class Parameter<T> {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "code")
    private String code;

    private T value;

    @Transient
    public abstract T getValue();

    public abstract void setValue(T value);
}

@Entity
@DiscriminatorValue(value = "boolean")
public class BooleanValue extends Parameter<Boolean> {

    @Column(name = "bool_value")
    private Boolean booleanValue;

    getValue()/setValue()[...]
}

@Entity
@DiscriminatorValue(value = "long")
public class LongValue extends Parameter<Long> {}

@Entity
@DiscriminatorValue(value = "string")
public class StringValue extends Parameter<String> {}

I am using postgresql and this is my table "parameter":
  id BIGINT,
  code VARCHAR,
  name VARCHAR,
  description VARCHAR,
  bool_value BOOLEAN,
  string_value VARCHAR,
  long_value BIGINT


text:
Q: How to bind a widget to a value from Kivy App I have the following Kivy app and I'm trying to change the text of a Label based on another widget's variable.
I mean, if the variable testing of the class TestApp changes, I want also the value of the variable text of the class TestLabel to change.
To do so, I've created a BooleanProperty in the TestLabel class that points to the testing variable of the TestApp class. The problem is that this callback is never executed despite being changing it each time I press the button.
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import BooleanProperty

Builder.load_string('''
<MainApp>:
    orientation: 'horizontal'
    rows: 2

    TestButton:
        text: 'Change value'
        on_release: self.change_value()
    TestLabel:
''')

class TestLabel(Label):
    testing = BooleanProperty()

    def __init__(self, **kwargs):
        super(TestLabel, self).__init__(**kwargs)
        self.app = App.get_running_app()
        self.testing = self.app.testing
        self.bind(testing=self.changed_value)

    def changed_value(self, _instance, newvalue):
        self.text = str(newvalue)

class TestButton(Button):

    def __init__(self, **kwargs):
        super(TestButton, self).__init__(**kwargs)
        self.app = App.get_running_app()

    def change_value(self):
        self.app.testing = not self.app.testing

class MainApp(BoxLayout):
    pass

class TestApp(App):
    testing = BooleanProperty(False)

    def build(self):
        return MainApp()

if __name__ == '__main__':
    TestApp().run()

A: It is not necessary to create a testing property in TestLabel since when you do: self.bind(testing = self.changed_value) you are connecting the testing of TestLabel  and not the testing of TestApp , so as it never changes testing after the bind then it never gets call the callback.
The bind has to be done using the object that has that property, and in your case the testing belongs to the App, so you must the App.
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import BooleanProperty

Builder.load_string('''
<MainApp>:
    orientation: 'horizontal'
    rows: 2

    TestButton:
        text: 'Change value'
        on_release: self.change_value()
    TestLabel:
''')

class TestLabel(Label):
    def __init__(self, **kwargs):
        super(TestLabel, self).__init__(**kwargs)
        self.app = App.get_running_app()
        self.app.bind(testing=self.changed_value)

    def changed_value(self, _instance, newvalue):
        self.text = str(newvalue)

class TestButton(Button):
    def __init__(self, **kwargs):
        super(TestButton, self).__init__(**kwargs)
        self.app = App.get_running_app()

    def change_value(self):
        self.app.testing = not self.app.testing

class MainApp(BoxLayout):
    pass

class TestApp(App):
    testing = BooleanProperty(False)
    def build(self):
        return MainApp()

if __name__ == '__main__':
    TestApp().run()


text:
Q: Closing a background form from a custom message box Brief description:
Cannot close form1 by clicking a button that is on form2.
I have the following forms:
form1
formMessageBox which has button1
form3
I want to:
Pop up formMessageBox from form1 (this is working ok) then from formMessageBox, click button1 to close form1 and open form3.
I have used a variety of techniques however form1 cannot be targeted.
Help much appreciated.
Edit
When form1 and the messagebox are open at the same time. Form1 does not close or hide when button1 is clicked to try and close form1.

A: Not really sure what you're looking for, but I think you are needing something like this.
Say you have Form1 and you pop up a formMessageBox using ShowDialog().
public class Form1 : Form
{
    if (somethingHappened)
    {
        var formMessageBox = new FormMessageBox();

        //ShowDialog() sets the formMessageBox object as a modal dialog owned by Form1
        DialogResult result = formMessageBox.ShowDialog();

        //Assuming you have OK buttons or something like that in formMessageBox
        if (result == DialogResult.OK)
        {
            var form3 = new Form3();

            /*Can't use this.Close() here as it would close the entire application
            Just hide it and don't forget to dispose of it later when you actually
            want the application to close*/
            this.Hide();

            form3.Show();

        }
    }
}

Then in your formMessageBox code, just set the DialogResult according to what occurs:
public class FromMessageBox : Form
{
    private void okButton_Click(object sender, EventArgs e)
    {
         //Do some stuff
         this.DialogResult = DialogResult.OK
         this.Close();
    }
 }


text:
Q: Getting Multiple Values from a CSV and using them in a For Loop I'm new to PowerShell, so I'm still getting used to the way variables and for loops are used, but I'd just like to have someone double check my script. I haven't run it yet, as it uses a set command and I'd rather be doubly sure the code works before testing. Once I get some input I'll run a very small number of users through it. The code is for assigning users intercall numbers.
I'm using an excel file that has 4 columns. The columns are labled "userprofilename", "RPTF", "RPTOLL", and "RPConfCode", same as the variables. Here is my code:
$accounts = ipcsv 'C:\Powershell-dest\intercall-numbers.csv'

$accounts | % {
$userprofilename = $_.userprofilename
$RPTF = $_.RPTF
$RPTOLL = $_.RPTOLL
$RPConfCode = $_.RPConfCode
Set-CsUserAcp -Identity $userprofilename -Name "InterCall" -Domain example.com -TollNumber $RPTOLL -TollFreeNumbers $RPTF -ParticipantPasscode $RPConfCode -Url http://www.intercall.com/l/dial-in-number-lookup.php}

I'll of course change "example.com" to the actual domain when I run it. Am I declaring/using the variables correctly?


text:
Q: Why does object class does not allow attributes?
Possible Duplicate:
Can set any property of Python object

In [67]: obj = object()
In [68]: obj.x = 42
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/user/<ipython-input-68-0203a27904ca> in <module>()
----> 1 obj.x = 42

AttributeError: 'object' object has no attribute 'x'
In [69]: class myc(object):
   ....:     pass
   ....:
In [70]: my = myc()
In [71]: my.x = 42

Looks like an inconsistency. How do I make my classes similar to object without allowing to add new attributes?

A: Most builtin types do not allow custom attributes, as these come with the overhead of a dictionary associated to each instance.  Custom classes have such a dictionary by default (it's accessible via the __dict__ attribute), but you can avoid its creation by adding
__slots__ = []

to the class definition – see the documentation for full details.


text:
Q: Angular Storybook Component is part of two modules error I'm testing the UI on some shared components with Storybook and running into a bug where it appears that Storybook is loading the component into the DynamicModule, resulting in the following error:
Type DigFinderComponent is part of the declarations of 2 modules: DigFinderModule and DynamicModule! Please consider moving DigFinderComponent to a higher module that imports DigFinderModule and DynamicModule. You can also create a new NgModule that exports and includes DigFinderComponent then import that NgModule in DigFinderModule and DynamicModule.

The DigFinder component is definitely only declared in its module:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DigFinderComponent } from './components/dig-finder/dig-finder.component';
import { DigFinderPanelComponent } from './components/dig-finder-panel/dig-finder-panel.component';
import { DigFinderNodeComponent } from './components/dig-finder-node/dig-finder-node.component';
import {DigUiModule} from '../dig-ui/dig-ui.module';
import {DigCardModule} from '../dig-card/dig-card.module';
import {DigContainerModule} from '../dig-container/dig-container.module';
import {DigBreadcrumbsModule} from '../dig-breadcrumbs/dig-breadcrumbs.module';
import {RouterModule} from '@angular/router';

@NgModule({
  declarations: [DigFinderComponent, DigFinderPanelComponent, DigFinderNodeComponent],
  imports: [
    CommonModule,
    DigBreadcrumbsModule,
    DigCardModule,
    DigContainerModule,
    DigUiModule,
    RouterModule
  ],
  exports: [
    DigFinderComponent
  ]
})
export class DigFinderModule { }

The unit tests are all passing, but this error comes up when its rendered by storybook:
import {moduleMetadata, storiesOf} from '@storybook/angular';

import {withNotes} from '@storybook/addon-notes';
import {action} from '@storybook/addon-actions';
import {DigFinderModule} from '../../../src/modules/dig/dig-finder/dig-finder.module';
import {DigFinderComponent} from '../../../src/modules/dig/dig-finder/components/dig-finder/dig-finder.component';

const testData = [
  '/about',
  '/about/team',
  '/about/services',
]
storiesOf('DigFinder', module)
  .addDecorator(
    moduleMetadata({
      imports: [
        DigFinderModule,
      ]
    })
  )
  .add('Default', () => ({
    component: DigFinderComponent,
    props: {
      data: testData,
      select: action('Selected: ')
    }
  }));

A: This is happening because you're using the component prop inside of the Storybook add method. I believe that's how it ends up in DynamicModule, and then  moduleMetadata's import is getting it the second way.
One solution is to do what you answered: skip importing the module and declare/import the bits of the module that you need. The alternative is to use the template prop instead of the component prop:
import {moduleMetadata, storiesOf} from '@storybook/angular';

import {withNotes} from '@storybook/addon-notes';
import {action} from '@storybook/addon-actions';
import {DigFinderModule} from '../../../src/modules/dig/dig-finder/dig-finder.module';
import {DigFinderComponent} from '../../../src/modules/dig/dig-finder/components/dig-finder/dig-finder.component';

const testData = [
  '/about',
  '/about/team',
  '/about/services',
]
storiesOf('DigFinder', module)
  .addDecorator(
    moduleMetadata({
      imports: [
        DigFinderModule,
      ]
    })
  )
  .add('Default', () => ({
    template: `
      <app-dig-finder
        [data]="data"
      ></app-dig-finder>
    `,
    props: {
      data: testData,
    }
  }));

Note that you still needs props here.

A: I was able to resolve this by explicitly importing all of the requirements, rather than importing the module:
storiesOf('DigFinder', module)
  .addDecorator(
    moduleMetadata({
      declarations: [DigFinderComponent, DigFinderPanelComponent, DigFinderNodeComponent],
      imports: [
        CommonModule,
        DigBreadcrumbsModule,
        DigCardModule,
        DigContainerModule,
        DigUiModule,
        RouterModule
      ],
    })
  )
  .add('Default', () => ({
    component: DigFinderComponent,
    props: {
      data: testData,
      select: action('Selected: ')
    }
  }));

But would still like to figure out why the module import doesnt work (its working on several other examples).

A: Should this import:
import {DigFinderComponent} from '../../../src/modules/dig/dig-finder/components/dig-finder/dig-finder.component';

Be importing from the module instead?
import {DigFinderComponent} from '../../../src/modules/dig/dig-finder/dig-finder.module';


text:
Q: queue of different class objects I need to create a queue of different class objects (These classes are not related). I found a solution as follows:
Create a base class and use polymorphism.
Here is how I implemented it,
class Task {
    public:
    virtual void operator()() {
        printf("should not be called\n");
    }
};

class TaskRPCB : public Task {
    private:
        int x;
        // other varibles
        std::function<void(int)> func;
    public:
        TaskRPCB(std::function<void(int)>&f , int x) {
            this->func = f;
            this->x = x;
        }
        void operator()() {
            printf("TaskRPCB function is executing...\n");
            func(x);
        }
};

class TaskECB : public Task {
    private:
        // other varibles
        std::function<void(void)> func;
    public:
        TaskECB(std::function<void(void)>&f) : func(f) {}
        void operator()() {
            printf("TaskECB function is executing...\n");
            func();
        }
};

void F1() { // dummy function for example
    cout <<"no x"<<endl;
}
void F2(int x) { // dummy function for example
    cout <<"x : "<<x<<endl;
}

int main() {

    queue<unique_ptr<Task>> Q;

    function<void()>    func1   = F1;
    function<void(int)> func2   = F2;

    TaskECB task1(func1);
    TaskRPCB task2(func2,4);

    Q.emplace(new TaskECB(func1));
    Q.emplace(new TaskRPCB(func2,4));

    (*Q.front())();
    Q.pop();

    (*Q.front())();
    Q.pop();

}

The problem is, I can not push the objects directly as shown above. I have to create an object of an inherited class and pass it to another function to do the push action. It is because ( in my case ) the queue is a part of a thread-safe queue and it has separate Push() method.
template<typename T>
void threadSafeQueue<T>::Push(T newData) { /* TODO: size check before pushing */
    std::shared_ptr<T> data(std::make_shared<T>(std::move(newData)));
                                           /* construct the object before lock*/
    std::lock_guard<std::mutex> lk(mut);
    taskQueue.push(data);
    dataCond.notify_one();
}

Earlier I did not have multiple tasks to execute ( or push ) into the queue, therefore
threadSafeQueue<TaskRPCB> workQ declaration worked fine for me.
Creating a base Task class like above is not working because of object slicing
Can you suggest other ways to store objects in the queue ( so that I can still use the lock guarded Push() method )
Thanks !
update :
is the correct way of using variant?
typedef std::variant<TaskECB, TaskRPCB> myType;

int main() {

    queue<unique_ptr<myType>> Q;

    function<void()>    func1   = F1;
    function<void(int)> func2   = F2;

    TaskECB task1(func1);
    TaskRPCB task2(func2,4);

    myType x = task1;

    Q.push(make_unique<myType>(x));
    x = task2;
    Q.push(make_unique<myType>(x));

    if((*Q.front()).index() == 0) {
        auto f1 = get<TaskECB>(*Q.front());
        f1();
        Q.pop();
    }
    if((*Q.front()).index() == 1) {
        auto f1 = get<TaskRPCB>(*Q.front());
        f1();
        Q.pop();
    }

}

update2:
using myVariantType = std::variant<TaskECB, TaskRPCB>;

struct VisitPackage {
    void operator()(TaskECB & task) {
        task();
    }
    void operator()(TaskRPCB& task) {
        task();
    }
};

int main() {
    queue<myVariantType> Q;

    function<void()>    func1   = F1;
    function<void(int)> func2   = F2;

    TaskECB task1(func1);
    TaskRPCB task2(func2,4);

    Q.emplace(task1);
    Q.emplace(task2);

    std::visit(VisitPackage(), Q.front());
    Q.pop();
    std::visit(VisitPackage(), Q.front());
    Q.pop();
}


text:
Q: Codeblocks with Qt - something terribly wrong After creating qt project in codeblocks and running it I'm getting:

Anyone knows how to resolve it?
Thanks

A: This looks to me like you're building against one version of Qt and linking against another at runtime. Run the QtSDK Maintenance Tool and remove any versions of Qt Desktop that you don't need. You may then need to repoint Codeblocks at the correct headers.
I'm guessing that if you're running from within Codeblocks, you've had to explicitly specify which dlls to use when you run your newly built app. If so, make sure that those are the correct versions (i.e. replace them with dlls from QT INSTALL DIR\Desktop\4.7.x\mingw\bin [though I'm not on my work PC at the moment, so this path may be slightly wrong. Just make sure you're in the correct 4.7.x folder]).
To be honest though, if you're running from Windows, why not use QtCreator? Aside from slightly lacking in terms of GDB integration, it's pretty good and you'd find problems like this are harder to come across.

A: This is (esp on Windows) a common problem. When installing the Qt SDK, you'll get at least 2 .dll's with the same name but in different versions. It happens, that you link against the intended (dev-)lib but at runtime the version from the Designer/Creator is used.
The easiest way to avoid this, is to deploy the right version of the dll's together with your binaries (.exe and stuff) in a separate folder. This can be achived by modifying your build script. It depends on your build system which is usually qmake/.pro or cmake/CMakeLists.txt.
As for CMake, given an environment variable MYQTDLLDIR containing the path to the files to be deployed you can use something like that:
configure_file($ENV{MYQTDLLDIR}/QtCore4.dll ${CMAKE_CURRENT_BINARY_DIR} COPYONLY)
configure_file($ENV{MYQTDLLDIR}/QtGui4.dll ${CMAKE_CURRENT_BINARY_DIR} COPYONLY)

documentation stripped from cmake --help-full:

configure_file    Copy a file to another location and modify its
  contents.
configure_file(
                    [COPYONLY] [ESCAPE_QUOTES] [@ONLY])
Copies a file  to file  and substitutes variable
  values    referenced in the file content.  If  is a relative
  path it is    evaluated with respect to the current source directory.
  The     must be a file, not a directory.  If  is a
  relative path it is    evaluated with respect to the current binary
  directory.  If     names an existing directory the input file
  is placed in that directory    with its original name.
This command replaces any variables in the input file referenced as
  ${VAR} or @VAR@ with their values as determined by CMake.  If a
  variable is not defined, it will be replaced with nothing.  If
  COPYONLY is specified, then no variable expansion will take place.  If
  ESCAPE_QUOTES is specified then any substituted quotes will be C-style
  escaped.  The file will be configured with the current values of CMake
  variables.  If @ONLY is specified, only variables of the form @VAR@
  will be replaces and ${VAR} will be ignored.  This is useful for
  configuring scripts that use ${VAR}.  Any occurrences of #cmakedefine
  VAR will be replaced with either #define VAR or /* #undef VAR */
  depending on the setting of VAR in CMake.  Any occurrences of
  #cmakedefine01 VAR will be replaced with either #define VAR 1 or
  #define VAR 0 >depending on whether VAR evaluates to TRUE or FALSE in
  CMake

As for qmake you could use INSTALLS (used when make install is called) or execute a "plain command" after linking. Using INSTALLS:
mytarget.path = /output/path
mytarget.files += /path/to/QtCore4.dll
mytarget.files += /path/to/QtGui4.dll
INSTALLS += mytarget

qmake using command execution:
win32 {
    EXTRA_BINFILES += \
        $${MYQTDLLDIR}/QtCore4.dll \
        $${MYQTDLLDIR}/QtGui4.dll
    EXTRA_BINFILES_WIN = $${EXTRA_BINFILES}
    EXTRA_BINFILES_WIN ~= s,/,\\,g
        DESTDIR_WIN = $${DESTDIR}
    DESTDIR_WIN ~= s,/,\\,g
    for(FILE,EXTRA_BINFILES_WIN){
                QMAKE_POST_LINK +=$$quote(cmd /c copy /y $${FILE} $${DESTDIR_WIN}$$escape_expand(\n\t))
    }
}


text:
Q: Making an HTML form Work I am trying to make my first Contact form. I have already done the HTML & CSS part. Maybe there are some errors in the HTML tagging.
Now that my HTML/CSS looks fine I need to make it work so the submissions get sent to my email and the page displays a Thank you message or redirects to a thank u page.
Can someone help me with the code for creating a secure functionality for the form to make it work?
Also i would like to add a captcha to the form to avoid spam submissions.
Live link of form - http://wishamemory.com/makeawish/index.html
The HTML code of the form is this:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Quick Minimal Contact Form</title>

      <link rel="stylesheet" href="css/style.css">

  <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>

<form id="contact-form">

WISH A MEMORY!

I
    wish for
    <input type="text" name="your-wish" id="wish" minlength="3" placeholder="(describe your wish here)" required>

    in
    <input type="text" name="your-location" id="location" minlength="3" placeholder="(location in Goa only)" required>

    on
    <input type="text" name="your-date" id="date" minlength="3" placeholder="(dates)" required>

***********

    Is this wish for yourself or dedicated to someone else?
    <input type="text" name="your-credits" id="credits" minlength="3" placeholder="Who is the lucky one?" required>

    Preferred budget to make this wish a reality:
    <input type="text" name="your-budget" id="budget" minlength="3" placeholder="(amount in INR)" required>

    Maximum you can spend to make the experience even more memorable:
    <input type="text" name="your-maxbudget" id="maxbudget" minlength="3" placeholder="(let's make it special)" required>

    Why do you think this wish deserves becoming a memory?
    <textarea name="your-reason" id="your-reason" placeholder="(Not all wishes come true. Share some background and the importance of this wish)" class="expanding" required></textarea>

Personal details

    Name
    <input type="text" name="your-name" id="name" minlength="3" placeholder="(full name)" required>

    Email address
    <input type="email" name="your-email" id="email" placeholder="(your email address)" required>

    Mobile number
    <input type="text" name="your-phone" id="phone" placeholder="(mobile number)" required>

    <button type="submit">
      <svg version="1.1" class="send-icn" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100px" height="36px" viewBox="0 0 100 36" enable-background="new 0 0 100 36" xml:space="preserve">
        <path d="M100,0L100,0 M23.8,7.1L100,0L40.9,36l-4.7-7.5L22,34.8l-4-11L0,30.5L16.4,8.7l5.4,15L23,7L23.8,7.1z M16.8,20.4l-1.5-4.3
    l-5.1,6.7L16.8,20.4z M34.4,25.4l-8.1-13.1L25,29.6L34.4,25.4z M35.2,13.2l8.1,13.1L70,9.9L35.2,13.2z" />
      </svg>
      send
    </button>

</form>

Powered by wishamemory.com

I tried making a mail.php as follows to test. And in my HTML file changed
<form id="contact-form">

for this
<form action="mail.php" method="POST">

mail.php file
<?php
$your-wish = $_POST['your-wish'];
$your-location = $_POST['your-location'];
$your-date = $_POST['your-date'];
$formcontent="From: $your-name \n Message: $wish";
$recipient = "arminbaig@gmail.com";
$subject = "Contact Form";
$mailheader = "From: $your-email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>

but I get the following error on this url - http://wishamemory.com/makeawish/mail.php
This page isn't working
wishamemory.com is currently unable to handle this request.
HTTP ERROR 500
Where am i going wrong?

A: you are missing action atribute in <form> tag
like this <form id="something" action="link-to-php file">
you have to add mail.php in action attribute like this,
    <form action="mail.php" id="contactform" method="post">
-------
------------
</form>

A: <!DOCTYPE html>

Responsive Form

Resize the browser window to see the effect. When the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other.

  <form action="/action_page.php">

        First Name

        <input type="text" id="fname" name="firstname" placeholder="Your name..">

        Last Name

        <input type="text" id="lname" name="lastname" placeholder="Your last name..">

        Country

        <select id="country" name="country">
          <option value="australia">Australia</option>
          <option value="canada">Canada</option>
          <option value="usa">USA</option>
        </select>

        Subject

        <textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>

      <input type="submit" value="Submit">

  </form>


text:
Q: Construct a calculus which produces exactly all pairs $(S,t)$, such that $free(t)=S$. Construct a calculus which produces exactly all pairs $(S,t)$, such that $free(t)=S$. This calculus will operate on pairs $(S,t)$, where $S$ is a set of variables and t is a term.
I've got an understanding of free vs bound variable.
for instance, $x^y$, $x$ is bound and $y$ is free.
If I understand the rule or rules I construct for this calculus will be such that any term $t$ will contain all free variables that are in contained in $S$ and any term in $S$ will satisfy this.
I'm not sure what rules I need exactly, maybe
a rule to construct  variables, and a rule that generates terms with some n-ary function. But anything quantified is bounded so then that variable is no longer free.

A: Note that in a term all variables are free. So the following calculus will do:
$${\over (\{v_n\}, v_n)} $$ where $v_n$ is a variable.
$${\over (\emptyset, c)}$$ where c is a constant symbols.
$${(S_1, t_1) \\ \dots \\ (S_n, t_n) \over ( \bigcup_i S_i, ft_1\dots t_n) }$$
where f is an n-ary function symbol.


text:
Q: Can't find name 'ChangeDetectorRef' in Angular 4 I'm migrating an Ionic 2 app to Ionic 3, with Angular 4.
import { Component, Input, Output, OnInit, Inject, AfterViewInit, forwardRef, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

[...]
  constructor( @Inject(forwardRef(() => TimelineComponent)) private _parent: TimelineComponent, private cd: ChangeDetectorRef) {
    this.window = <Window>window;
}

And i'm getting an error : Can't find name 'ChangeDetectorRef in this constructor :(
Here my package.json :
"dependencies": {
"@angular/animations": "4.0.0",
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/compiler-cli": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/platform-server": "4.0.0",
"@ionic-native/core": "3.4.2",
"@ionic-native/splash-screen": "3.4.2",
"@ionic-native/status-bar": "3.4.2",
"@ionic/storage": "2.0.1",
"@ngx-translate/core": "^6.0.1",
"@ngx-translate/http-loader": "0.0.3",
"install": "^0.8.8",
"intl": "^1.2.5",
"ionic-angular": "3.0.1",
"ionicons": "3.0.0",
"lodash": "^4.17.3",
"npm": "^4.5.0",
"pdfmake": "0.1.26",
"rxjs": "5.1.1",
"smoothscroll-polyfill": "0.3.4",
"sw-toolbox": "3.4.0",
"typings": "2.1.1",
"zone.js": "^0.8.4"  },
"devDependencies": {
"@ionic/app-scripts": "1.3.0",
"typescript": "~2.2.1",
"gulp": "^3.9.1",
"gulp-help": "^1.6.1",
"gulp-inject-string": "^1.1.0",
"gulp-load-plugins": "^1.4.0",
"gulp-replace-task": "^0.11.0",
"gulp-war": "^0.1.4",
"gulp-zip": "^4.0.0"

},
Here my errors in Chrome

A: I upgrated with the new version and now it works :)
"dependencies": {
"@angular/animations": "4.0.2",
"@angular/common": "4.0.2",
"@angular/compiler": "4.0.2",
"@angular/compiler-cli": "4.0.2",
"@angular/core": "4.0.2",
"@angular/forms": "4.0.2",
"@angular/http": "4.0.2",
"@angular/platform-browser": "4.0.2",
"@angular/platform-browser-dynamic": "4.0.2",
"@angular/platform-server": "4.0.2",
"@angular/tsc-wrapped": "4.1.0",
"@ionic/storage": "2.0.1",
"@ngx-translate/core": "^6.0.1",
"@ngx-translate/http-loader": "0.0.3",
"ionic-angular": "3.1.0",
"install": "^0.8.8",
"intl": "^1.2.5",
"ionicons": "~3.0.0",
"lodash": "^4.17.3",
"npm": "^4.5.0",
"pdfmake": "0.1.26",
"rxjs": "5.1.1",
"smoothscroll-polyfill": "0.3.4",
"sw-toolbox": "3.4.0",
"ng2-pdf-viewer": "1.0.2",
"zone.js": "^0.8.5"  },


text:
Q: Elasticsearch Cluster can't join new node I use es-2.2 version, build cluster with 3 node in different server. now some server get more memory to used, so plan to start other node in existing server.
server1:
10.1.192.31 port use default 9200 and 9300
server2:
10.1.192.32 port use default 9200 and 9300
server3:
10.216.90.225 port default 9200 and 9300

now i wanna add two new node in 31 and 32 server
newnode1: get new configure like below:
cluster.name: EScluster
node.name: ESnode-1-1
network.host: 10.1.192.32
node.master: false
node.data: true
http.port: 9202
transport.tcp.port: 9302
discovery.zen.ping.multicast.enabled: false
discovery.zen.ping.unicast.hosts: ["10.216.90.225", "10.1.192.31:9300", "10.1.192.31:9302", "10.1.192.32:9300"]

newnod2: config like below
cluster.name: EScluster
node.name: ESnode-2-1
network.host: 10.1.192.31
node.master: false
node.data: true
http.port: 9202
transport.tcp.port: 9302
discovery.zen.ping.multicast.enabled: false
discovery.zen.ping.unicast.hosts: ["10.216.90.225", "10.1.192.31:9300", "10.1.192.32:9300", "10.1.192.32:9302"]

after start get error like below:
 [INFO ][discovery.zen            ] [ESnode-1-1] failed to send join request to master [{ESnode-2}{C4Z7lLTASmiZYtswsljZYA}{10.1.192.31}{10.1.192.31:9300}{max_local_storage_nodes=1, master=true}], reason [RemoteTransportException[[ESnode-2][10.1.192.31:9300][internal:discovery/zen/join]]; nested: IllegalStateException[failure when sending a validation request to node]; nested: RemoteTransportException[[ESnode-1-1][10.1.192.32:9302][internal:discovery/zen/join/validate]]; nested: IllegalArgumentException[No custom metadata prototype registered for type [licenses], node like missing plugins]; ]
    [2016-05-26 10:35:26,408][WARN ][transport.netty          ] [ESnode-1-1] exception caught on transport layer [[id: 0x770dcb9e, /10.1.192.31:37584 => /10.1.192.32:9302]], closing connection

A: I met this error just now.
There are three nodes(one master node with two data node, all in docker) running on my vps.
I install marvel in master node with command:
bin/plugin install license
bin/plugin install marvel-agent

But I got No Marvel Data Found on kibana page.
Soon, I found other data node died.
The error was
IllegalArgumentException[No custom metadata prototype registered for type [licenses], node like missing plugins

and
So just install license in other two data nodes:
bin/plugin install license

restart them would work.

A: guys
The problem been solved, main reason like below:
[internal:discovery/zen/join/validate]]; nested: IllegalArgumentException[No custom metadata prototype registered for type [licenses], node like missing plugins]

I install some plugin like marvel but not working then disabled, but it's not install that plugin for new node。 This is big mistake, so don't try any unused plugin in your enviroment, should be carefully on it.
So, my configuration is correctly hope this can help other people, thanks.

A: My logs were filled with annoying license errors even though I had uninstalled marvel and was not running anything that should require a license.  Nodes would not join the cluster.
I ran:
bin/plugin remove license

and restarted the nodes.  Things came back online fine and the logspam stopped.


text:
Q: django - how to return one to many this is my model
class plans(models.Model):
    plan_name = models.CharField(max_length=50)
    plan_price = models.IntegerField(default=0)
    plan_is_active = models.BooleanField(max_length=1, default='1')

    def __str__(self):
        return self.plan_name

class plan_cat(models.Model):
    cat_name = models.CharField(max_length=50)
    plan = models.ForeignKey(plans, on_delete=models.CASCADE)
    cat_is_active = models.BooleanField(max_length=1, default='1')

    def __str__(self):
        return self.cat_name

my serializer is
class PlanSerializer(serializers.ModelSerializer):

    class Meta:
        model = plans
        fields = ('plan_name','plan_price')

class CatSerializer(serializers.ModelSerializer):

    plan = PlanSerializer()
    class Meta:
        model = plan_cat
        fields = ('cat_name','plan')

this is my view
class plan_details(APIView):
    def get(self, requests):
        queryset = plan_cat.objects.filter(cat_is_active='1')
        serializer = CatSerializer(queryset, many=True)
        return Response(serializer.data)

when i call this view http://localhost:8000/plans/details/
getting this output
[
    {
        "cat_name": "category 1",
        "plan": {
            "plan_name": "free",
            "plan_price": 0
        }
    },
    {
        "cat_name": "category 2",
        "plan": {
            "plan_name": "paid",
            "plan_price": 10
        }
    },
    {
        "cat_name": "category 3",
        "plan": {
            "plan_name": "free",
            "plan_price": 0
        }
    }
]

instead i want a output like this
[
    {
        "plan_name": "free",
        "plan_price": 0,
        "cat_name": {
            "category 1",
            "category 3",
        }
    },
    {
        "plan_name": "paid",
        "plan_price": 0,
        "cat_name": {
            "category 2",
        }
    },
]

the problem is the foreign key is with the second model,
so i cant serialize to get the grouped content output as mentioned above.
do i have to rewrite the model or serializer class ?

A: You can use reverse ralation name plan_cat_set. Rewrite your view and serializer to this:
class plan_details(APIView):
    def get(self, requests):
        queryset = plans.objects.filter(cat_is_active='1')
        serializer = PlanSerializer(queryset, many=True)
        return Response(serializer.data)

class CatSerializer(serializers.ModelSerializer):

    class Meta:
        model = plan_cat
        fields = ('cat_name',)

class PlanSerializer(serializers.ModelSerializer):
    cat_name = CatSerializer(source='plan_cat_set', many=True)

    class Meta:
        model = plans
        fields = ('plan_name','plan_price', 'cat_name')

Note that source='plan_cat_set' on CatSerializer allow you to change serializer field name from default plan_cat_set to cat_name.


text:
Q: Add additional half-transparent layer on picturebox I have a standard picture box control with an image on it. I want to add half-transparent layer. It will not hide an image, it will be some kind of filter.
How can I do it ?

A: The code would be similar to this:
private void pictureBox1_Paint (object sender, PaintEventArgs e)
{
   using (SolidBrush b = new SolidBrush(Color.FromArgb(128, Color.White))
   {
       e.Graphics.FillRectangle (b, 0, 0, pictureBox1.Width, pictureBox1.Height);
   }

However, the code above simply using a single color brush whose opactity is set to 128. There are other brush classes available, such as LinearGradientBrush, TextureBrush, PAthGradientBrush and HatchBrush.
Recommendation
To paint custom effects like you want to (for a button pressed state), a recommended approach would be to generate pre-rendered images that you can create either at runtime of your application or using an external program such as Adobe Photoshop and then save these images.
Then the painting code would simply take the image that represents the current state of your "button" and draw that image in the overriden pictureBox1_Paint method.
This technique results in better graphics painting performance as opposed to simply repainting the same states at different state-change times in the application.

A: You can register the Paint event and write some code like this:
private void pictureBox1_Paint (object sender, PaintEventArgs e)
    {
      e.Graphics.FillRectangle (Brushes.Transparent, 0, 0, pictureBox1.Width, pictureBox1.Height);
    }

You need to genereate a semi-transparent brush (change the alpa-level of the needed color)
more information about custom painting in controls can be found in MSDN
This is just a small code snippet. To use Print events and the Graphics object correctly read the MSDN stuff first.


text:
Q: JS How to make a reduce to sum a index of a array? I need help to learn how to make a reduce to a array like this:
a=[ ["ww","fsf",40],["ww","fsf",30],["ww","fsf",10]]

I want to learn how to sum the 40+30+10 using the method reduce. I know how to do it if the array was [40,30,10].
Can anyone help me? Thank you.

A: .reduce applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value:
a.reduce(callback[, initialValue])

Your values will be arrays:
["ww","fsf",40]
["ww","fsf",30]
["ww","fsf",10]

So you can use:
a.reduce(function(sum, value) {
  return sum + value[2];
}, 0);

Or using ES6 new arrow functions:
 a.reduce((sum, value) => sum + value[2], 0);

A: a.reduce((sum, row) => sum + row[row.length - 1], 0)


text:
Q: Calculate the number of Month based on the Dates Entered in Textboxes I have a userform in which three textboxes are there.
Textbox1 belongs to Start date
Textbox2 belongs to  End Date
Textbox3 belongs to No of Months.
Below is my code.
Dim mon As Integer

'Check Whether the Start Date Text Box is Empty or Not
If IsNull(Me.TextBox1.Text) = True Then
Me.TextBox3.Value = ""

Else
Me.TextBox2.Value = Format(DateAdd("yyyy", 1, Me.TextBox1.Value) - 1, "dd-mmm-yyyy")

mon = DateDiff("m", Me.TextBox1, Me.TextBox2)
Me.TextBox3.Value = mon

End If

The above code calculates the end date and no. of months. The problem is when i enter the 1st date of any month, it shows me only 11 months. However, if i enter any other date except 1st, it shows 12 months.
Please advise me how can i get 12 months if i enter the 1st date of any month.
Thanks
Salman

A: Well, I tested this code and it works nice:
Sub Test()

Dim mon As Integer

'Check Whether the Start Date Text Box is Empty or Not
If IsNull(Cells(4, 3).Text) = True Then
Cells(5, 3).Value = ""

Else
Cells(4, 4).Value = DateAdd("yyyy", 1, Cells(4, 3).Value - 1)
Cells(4, 4).NumberFormat = "d-mmm-yyyy"

mon = DateDiff("m", Cells(4, 3), Cells(4, 4) + 1)
Cells(5, 3).Value = mon

End If

End Sub

When Format function was used, I couldn't just add 1 day in DateDiff. It is because you can't add 1 to a string, I guess.
Sub Test2()
Dim xDate As Long
Dim xNewDate As Long

xDate = 40179  'It is 01.01.2010
xNewDate = DateAdd("yyyy", 1, xDate - 1)

xDateFormat = Format(xDate, "dd-mmm-yyyy")
xNewDateFormat = Format(xNewDate, "dd-mmm-yyyy")

MsgBox DateDiff("m", xDate, xNewDate + 1)

Debug.Print xDate
Debug.Print Format(xDate, "dd-mmm-yyyy")
Debug.Print xNewDate
Debug.Print Format(xNewDate, "dd-mmm-yyyy")

Debug.Print ""

'Debug.Print CLng(xDateFormat)                                                                 'Type Mismatch
'Debug.Print CLng(xNewDateFormat)                                                              'Type Mismatch
Debug.Print DateDiff("m", xDateFormat, xNewDateFormat)                                         'It works so DateDiff converts it
Debug.Print DateDiff("m", DateDiff("d", 0, xDateFormat), DateDiff("d", 0, xNewDateFormat) + 1) 'Now you can add one day

End Sub

I hope that this code should work:
Dim mon As Integer

'Check Whether the Start Date Text Box is Empty or Not
If IsNull(Me.TextBox1.Text) = True Then
Me.TextBox3.Value = ""

Else
Me.TextBox2.Value = Format(DateAdd("yyyy", 1, Me.TextBox1.Value) - 1, "dd-mmm-yyyy")

mon = DateDiff("m", Me.TextBox1, Me.TextBox2)
mon = DateDiff("m", DateDiff("d", 0, Me.TextBox1), DateDiff("d", 0, Me.TextBox2) + 1)
Me.TextBox3.Value = mon

End If


text:
Q: Facebook and Google+ login with Dart I would like to write a website using Dart as scripting language.
However, I need a robust way to login my users using their Facebook and/or Google+ ids.
So, I would like to know what is the best way to implement Facebook and Google+ login with Dart in a Website?
Please, if is it possible, I would like to have code snippets to better illustrate the process.

A: There is a pub package available for Google OAuth 2 login http://pub.dartlang.org/packages/google_oauth2_client
and one that claims to support facebook http://pub.dartlang.org/packages/simple_oauth2_server


text:
Q: Probability of dice roll affected by reroll. Say I wanted a 16-sided die with either A, B, C or D on each side, with the following probabilities:
A. 1/16
B. 7/16
C. 3/16
D. 5/16
I could roll the die and get either A, B, C or D with above probabilities. However, I read that 16-sided dice are not isohaedral: not every side can have the same size.
Now consider a 20-sided die (one of the Platonic solids) with the following probabilities:
A. 1/20
B. 7/20
C. 3/20
D. 5/20
E (null reroll). 4/20
Four sides now have a value of $E$, which is void and results in a reroll until either A, B, C or D are obtained. Does this have implications on the probability of getting each of the valid results? Would using the 20-sided die be similar to using the 16-sided die with equal size sides?

A: Notice that the probabilities are the same regardless of rerolls.
The probability of rolling A is still $\frac{1}{16}$, B still $\frac{7}{16}$, etc.
Let's consider side A.
Say I roll A with probability $\frac{1}{20}$, or maybe I get a null and reroll A, or I get a null and another null and reroll A, or i get a null.....(x) times and roll A.
What this looks like is $\frac{1}{20}$(roll) + $\frac{1}{20}*(\frac{1}{5})$(chance to null & reroll) + $\frac{1}{20}*(\frac{1}{25})$(chance to roll null twice & reroll)...$\frac{1}{20}(\frac{1}{5^n})$
The chance of rolling A first then would be $\frac{1}{20}+\frac{1}{100}+\frac{1}{500}+\frac{1}{2500}$.... it's a geometric series with sum $\frac{1}{16}$.
Similar logic for B, C, D.
This is because you can't actually end with E, so the probabilities are still in the ratio of A:B:C:D.

A: Those two dice will be identical in terms of probabilities.
Consider the 20-sided die. The expected outcome is:
$$E=A\frac{1}{20}+B\frac{7}{20}+C\frac{3}{20}+D\frac{5}{20}+E\frac{4}{20}$$
Rerolling results in $E$ because $E$ is the expected outcome. Now modify this equality.
$$E\frac{16}{20}=A\frac{1}{20}+B\frac{7}{20}+C\frac{3}{20}+D\frac{5}{20}$$
$$E=A\frac{1}{16}+B\frac{7}{16}+C\frac{3}{16}+D\frac{5}{16}+E\frac{4}{16}$$
which is exactly the same with 16-sided die's expectation equation.

A: Indeed, using the proposed 20-sided die does not affect the probability of resulting in $A$, $B$, $C$ or $D$. Let $A_n$ denote the event that, starting from the $n^{th}$ roll, we end up with an $A$. Then we get:
$$P[A_1] = P[A] + P[E_1] P[A_2] = \frac{1}{20} + \frac{4}{20} P[A_2]$$
However, the turn in which we're in does not affect the probability of, eventually, ending up with $A$ - it is a memoryless process. We can thus state that $P[A_1] = P[A_2]$, and we get:
$$P[A_1] = \frac{1}{20} + \frac{4}{20} P[A_1] \iff \frac{16}{20} P[A_1] = \frac{1}{20} \iff P[A_1] = \frac{1}{16}$$
You can also look at it this way: since we always reroll the die after we hit $E$, it is impossible to end the series with $E$. As such, we can only consider the events of hitting $A$, $B$, $C$ and $D$:
$$P[A_1] = \frac{P[A]}{P[A] + P[B] + P[C] + P[D]} = \frac{\frac{1}{20}}{\frac{16}{20}} = \frac{1}{16}$$
As mentioned in the comments, however, one disadvantage to this approach is that you could potentially end up with a high number of rerolls before you finally hit a valid side of the die.


text:
Q: Memory alignment and strict aliasing for continuous block of raw bytes I have a question about using same continuous block of raw bytes as storage of various typed objects from the point of C++ standard rules.
Consider we create continuous block of raw bytes, f.e.
void *data = ::operator new(100); // 100 bytes of raw data - not typed

Could then we use this memory like:
template<class T>
T* get(std::size_t bshift)
{
    return static_cast<T*>(
        reinterpret_cast<void*>(
            reinterpret_cast<unsigned char*>(data) + bshift
        )
    );
}

*

*Is it safe or UB? Why?

float &fvalue2 = *get<float>(sizeof(float));
fvalue2 = 0.02f;

*Is it safe or UB? Why?

float &fvalue_reserve = *get<float>(sizeof(float)*2 + 1);
fvalue = 0.03f;

*Is it safe or UB? Why?

double &dvalue = *get<double>(sizeof(float)*3 + 1);
dvalue = 0.04;

*Is it safe or UB? Why?

// assume that somehow there is no unused internal padding in struct
struct POD_struct{
    float fvalue1;                   //[0..sizeof(float)]
    float fvalue2;                   //[sizeof(float)..sizeof(float)*2]
    char reserved[sizeof(float) + 1];//[sizeof(float)*2..sizeof(float)*3+1]
    double dvalue;                   //[sizeof(float)*3+1..sizeof(float)*3+1+sizeof(double)]
};

POD_struct pod_struct;
std::memcpy(&pod_struct, get<void*>(0), sizeof(POD_struct));
pod_struct.fvalue2 == 0.02f; //true ??
pod_struct.dvalue == 0.04f; //true ??

*Is it safe or UB? Why? is it any different from №4?

// assume that somehow there is no unused internal padding in struct
struct POD_struct{
    float fvalue1;                   //[0..sizeof(float)]
    float fvalue2;                   //[sizeof(float)..sizeof(float)*2]
    char reserved[sizeof(float) + 1];//[sizeof(float)*2..sizeof(float)*3+1]
    double dvalue;                   //[sizeof(float)*3+1..sizeof(float)*3+1+sizeof(double)]
};

POD_struct pod_struct;
std::memcpy(&pod_struct, get<POD_struct*>(0), sizeof(POD_struct));
pod_struct.fvalue2 == 0.02f; //true ??
pod_struct.dvalue == 0.04f; //true ??

*Would it make any significant difference if we "fill" memory pointed by data pointer not from zero offset (f.e. 1, 2, 3?) and then memcpy to POD_struct object from that offset?

*Is it safe to assume that if we manage required size of continuous block of raw memory buffer to fit all POD members without paddings (aligned by 1 byte) then it's ok to interpret it as any POD type? Is it safe to reuse raw memory and interpret it as another POD type storage since we done using it?

A: First, it is unclear from your question, but I will assume that there is no other code inbetween the individual snippets you are showing.
Snippet 1. has undefined behavior because the pointer get will return cannot actually be pointing to a float object. ::operator new does implicitly create objects and return a pointer to a suitable created object, but that object would have to be a unsigned char object part of an unsigned char array in order to give the pointer arithmetic in reinterpret_cast<unsigned char*>(data) + bshift defined behavior.
However, then the return value of get<float>(sizeof(float)); would also be a pointer to an unsigned char object. Writing through a float glvalue to a unsigned char violates the aliasing rules.
This could be remedied by either using std::launder before returning the pointer from get or better by explicitly creating the object:
template<class T>
T* get(std::size_t bshift)
{
    return new(reinterpret_cast<unsigned char*>(data) + bshift) T;
}

Although this will create a new object with indeterminate value each time it is called.
std::launder would be sufficient here without creating a new object since ::operator new can implicitly create an unsigned char array which provides storage for a float object which is also implicitly-created. (Assuming all objects used in this way fit in the storage, are correctly aligned (see below), do not overlap and are implicit-lifetime types):
template<class T>
T* get(std::size_t bshift)
{
    return std::launder(reinterpret_cast<T*>(reinterpret_cast<unsigned char*>(data) + bshift));
}

However, 2. and 3. have undefined behavior even with this modification if alignof(float) != 1 (which is very likely to be true). You cannot create and start the lifetime of an object with wrong alignment either implicitly or explicitly. (Although it may technically be possible to create an object with wrong alignment explicitly without starting its lifetime.)
For 4. and 5., assuming the above weren't undefined behavior due to misalignment or out-of-bounds access and given the assumptions in the question, I think these snippets should have defined behavior. Note however that it is extremely unlikely that these requirements are satisfied.
For 6., if you offset everything you need to again take care not to go out-of-bounds of the allocation and not to violate the alignment of any of the involved types. (Including the alignment of POD_struct for 5.)
For 7. the formulation is very vague, so I am not sure what you mean. But you explicitly generally can't interpret memory as a different type than it is. In your examples 4. and 5. you are copying object representations, which is different.

To be clear again: Practically speaking your code has UB due to the alignment violations. This probably extends even to platforms that allow unaligned access, because the compiler may optimize code based on the assumption of pointer alignment. Compilers may offer type annotations to indicate that a pointer may be unaligned. You need to use these or other tools if you want to implement unaligned access in practice.


text:
Q: How to do a measure %? Team,
I'm trying to create a measure so I can pull over our Maintenance and repairs by % of revenue:
Z - Maint/Repairs % = sum('LSI DP_JP_HistorySummaryBySiteMaster'[Maint/Repairs]/[Z - JP TTM Rev. Copy])
I receive this error: 'The SUM function only accepts a column reference as an argument.'
Do you know what I'm doing wrong?

A: For me it's difficult to interpret what you are doing or trying to do just with the information that's given to us. But I am going to make my guess anyway.
In any case, whatever you do or try to do, use divide() -doc- as intended in place of the / operator.

*

*For operation at row level use sumx () doc.

*Have you tryed out [my_measure] = divide( sum( [my_column] ), [my_other_measure] )?

A: I am guessing [Z - JP TTM Rev. Copy] is a measure.
The reason for the error are missing parenthesis and missing syntax.
Sum('LSI DP_JP_HistorySummaryBySiteMaster'[Maint/Repairs])/([Z - JP TTM Rev. Copy])
A better Measure is this
measure =
VAR _num =
    SUM ( 'LSI DP_JP_HistorySummaryBySiteMaster'[Maint/Repairs] )
RETURN
    DIVIDE ( _num, [Z - JP TTM Rev. Copy] )


text:
Q: Sending keys from ahk so ahk registers them Is it possible to Send key strokes (e.g., ctrl+alt+b xyz) using ahk and have activated corresponding hotkey ?
E.g., I have ^!b:: that shows MsgBox. I have ^!c:: from which I'd like to Send, ^!b and I want ^!b:: code to be activated.
My goal: I have various hotkeys in combination with Input. I want to have a hotkey to repeat last command.
Thank you


text:
Q: Pandas df to database using flask-sqlalchemy I'm trying to insert a pandas dataframe into a mysql database. I am using flask-sqlalchemy.
I have created this table:
class Client_Details(db.Model):
    __tablename__ = "client_history"

    client_id = db.Column(db.Integer, primary_key=True)
    client_name = db.Column(db.VARCHAR(50))
    shack= db.Column(db.VARCHAR(50))

and I would like to insert the data from this df into it:
index   name     shack
0        jay       H9
1        ray       I8
2        t-bop     I6
3        jay-k     F89
4        phil      D89

This doesn't seem to work:
for index, row in df.iterrows():
    client_add = client_history(client_name = row[1], shack =row[2])
    db.session.add(client_add)
    db.session.commit()

Is there a better way to do this, using to_sql, perhaps?

A: df.to_sql(engine, 'client_history')

Is what you are looking for.  There is no lighting fast way to do this (that I am aware of) but typically using builtin pandas functions is going to be faster than any solution that you can create on your own.

A: Kyle's answer was close - the flask-sqlalchemy engine IS created behind the scenes with some magic, but the correct way to access it is with db.engine. Here's what you're looking for:
df.to_sql(name='client_history', con=db.engine, index=False)

I also agree with VinceP's assessment that to_sql can be slow for larger tables, so keep that in mind.
For what it's worth, you can also access the session with Flask-SQLAlchemy as db.session.


text:
Q: Chromedriver throwing path error when imported into some other file Chromedriver is only giving path error when the module is being imported (I even added it to path still not working). Its working fine when used like the code under.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from searching.credentials import *
from button_ids import *

driver = webdriver.Chrome(PATH)

driver.get("the website link goes here")

username = driver.find_element(by=By.ID, value="j_username")
password = driver.find_element(by=By.ID, value='j_password')

driver.implicitly_wait(2)
username.send_keys(LOGIN_CREDENTIALS['username'])
password.send_keys(LOGIN_CREDENTIALS['password'])

driver.implicitly_wait(3)

login_button = driver.find_element(by=By.XPATH, value= login_button_xpath)

driver.implicitly_wait(1)
login_button.click()

driver.implicitly_wait(2)

search = driver.find_element(by=By.ID, value='lookupModule_mergedLookup')
search.send_keys('sample input')
driver.implicitly_wait(3)
driver.find_element(by=By.ID, value="ui-id-3").click()

This code above works fine
The problem starts when I import the same code but just from a different module
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from credentials import *

class Searching(webdriver.Chrome):

    def __init__(self, driver_path = 'C:\\Users\\saura\\OneDrive\\Desktop\\Code\\Python Files\\Database Automation\\bot\\searching\\chromedriver.exe'):

        self.driver_path = driver_path
        os.environ['PATH'] += self.driver_path #to add it to path (not working)
        super(Searching, self).__init__()

    def login(self):

        self.get("the website link goes here")

        username = self.find_element(by=By.ID, value="j_username")
        password = self.find_element(by=By.ID, value='j_password')

        self.implicitly_wait(2)
        username.send_keys(LOGIN_CREDENTIALS['username'])
        password.send_keys(LOGIN_CREDENTIALS['password'])

        self.implicitly_wait(3)

        login_button = self.find_element(by=By.XPATH, value= login_button_xpath)

        self.implicitly_wait(1)
        login_button.click()

When I import this module into this code:
from searching.searching import Searching

s = Searching()
s.login()

It throws this error:

PS C:\Users\saura\OneDrive\Desktop\Code\Python Files> & C:/Users/saura/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/saura/OneDrive/Desktop/Code/Python Files/Database Automation/bot/run.py"
Traceback (most recent call last):
File "C:\Users\saura\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\common\service.py", line 71, in start
self.process = subprocess.Popen(cmd, env=self.env,
File "C:\Users\saura\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\saura\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\Users\saura\OneDrive\Desktop\Code\Python Files\Database Automation\bot\run.py", line 37, in
s = Searching()
File "c:\Users\saura\OneDrive\Desktop\Code\Python Files\Database Automation\bot\searching\searching.py", line 15, in init
super(Searching, self).init()
File "C:\Users\saura\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 69, in init
super().init(DesiredCapabilities.CHROME['browserName'], "goog",
File "C:\Users\saura\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 89, in init
self.service.start()
File "C:\Users\saura\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://chromedriver.chromium.org/home