text:
Q: Get all strings separated by newlines in text area Hi I'll like to get strings that are separated by a newline from a text area in javascript.
If the following is entered in a text area
1
2
3
4

I'll like to get a regex match of
["1", "2", "3", "4"]

I've tried /\n?(.*)/g and a few other variations but I wasn't able to get the combination that I wanted. Help is greatly appreciated!

A: You can do this using split()
var arrayOfLines = $('textarea').val().split('\n');

A: I suggest you to try this one
/^.*?$/g

It selects the whole line from the beginning (^) to the end ($).
Your's selects the newlines, which is a good approach, but not optimal in this place.

A: I found the answer to what I'm searching for.
var matches = $('textarea').val().split('\n');

This worked and I got the result that I wanted.

A: I'm assuming you are using JavaScript or Perl?
Try this:
/^[^\n]+$/mg


text:
Q: Adding form elements to a table with iTextSharp I'm trying to create a PDF document that is essentially a list of users in a table format. I need the table to have checkboxes in it. So far, I have the table and the checkboxes separately but I cannot find a way to get the checkboxes in the table. I think I need to add them using the AddCell() method.
Here is my code:
static void Main(string[] args)
    {
        // create the document, filestream, writer
        Document doc = new Document(PageSize.LETTER);
        FileStream file = new FileStream(@"C:\Users\test\User List.pdf", FileMode.OpenOrCreate);
        PdfWriter writer = PdfWriter.GetInstance(doc, file);

        try
        {
            // metadata
            doc.AddAuthor("Test User");
            doc.AddCreator("Test Document");
            doc.AddKeywords("Test Document");
            doc.AddSubject("Test Document");
            doc.AddTitle("Test Document - Test User");

            // open up the PDF document
            doc.Open();

            PdfContentByte cb = writer.DirectContent;
            Font _bf = new Font(Font.FontFamily.HELVETICA, 9);

            // create a table
            PdfPTable table = new PdfPTable(3);
            PdfPCell cell = new PdfPCell(new Phrase("User List"));

            PdfFormField field = PdfFormField.CreateCheckBox(writer);
            field.SetWidget(new Rectangle(40, 500, 60, 530), PdfAnnotation.HIGHLIGHT_INVERT);
            field.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
            field.FieldName = "Delete";
            writer.AddAnnotation(field);

            cell.Colspan = 3;
            cell.HorizontalAlignment = 0; //0 = left, 1 = center, 2 = right
            cell.VerticalAlignment = 1;
            table.AddCell("No.");
            table.AddCell("Users");
            table.AddCell("Delete");

            // create form fields
            PdfAppearance[] onOff = new PdfAppearance[2];
            Rectangle rect;
            PdfFormField checkbox;
            RadioCheckField _checkbox;

            onOff[0] = cb.CreateAppearance(10, 10);
            onOff[0].Rectangle(1, 1, 8, 8);
            onOff[0].Stroke();

            onOff[1] = cb.CreateAppearance(10, 10);
            onOff[1].SetRGBColorFill(255, 128, 128);
            onOff[1].Rectangle(1, 1, 8, 8);
            onOff[1].FillStroke();
            onOff[1].MoveTo(1, 1);
            onOff[1].LineTo(9, 9);
            onOff[1].MoveTo(1, 9);
            onOff[1].LineTo(9, 1);
            onOff[1].Stroke();

            for (int i = 0; i < 5; i++)
            {
                table.AddCell(i.ToString());
                table.AddCell("User " + i);
                //rect = new Rectangle(400, 675 - i*40, 415, 663 - i*40);
                rect = new Rectangle(400, 735 - i * 40, 415, 723 - i * 40);
                _checkbox = new RadioCheckField(writer, rect, "User "+(i+1), "Yes");
                checkbox = _checkbox.CheckField;
                checkbox.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0]);
                checkbox.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, "On", onOff[1]);
                writer.AddAnnotation(checkbox);

                // this is where I am trying to add the checkbox to the table
                // what can I add to AddCell() to make the checkbox show up?
                table.AddCell();
                //ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("User " + (i + 1), _bf), 50, 665 - i * 40, 0);
            }

            cb = writer.DirectContent;
            doc.Add(table);

        }
        catch(DocumentException dex)
        {
            throw (dex);
        }
        finally
        {
            // close
            doc.Close();
            writer.Close();
            file.Close();
        }
    }

Is there any way to do this using iTextSharp? Maybe there is a better library to use?

A: I'll reference the iText website showing how to pass a field to a custom IPdfPCellEvent implementation and how to create that that custom class and recreate it below in C#.
First, create a class the implements the IPdfPCellEvent:
public class ChildFieldEvent : IPdfPCellEvent {
    /** A parent field to which a child field has to be added. */
    protected PdfFormField parent;
    /** The child field that has to be added */
    protected PdfFormField kid;
    /** The padding of the field inside the cell */
    protected float padding;

    /**
     * Creates a ChildFieldEvent.
     * @param parent the parent field
     * @param kid the child field
     * @param padding a padding
     */
    public ChildFieldEvent(PdfFormField parent, PdfFormField kid, float padding) {
        this.parent = parent;
        this.kid = kid;
        this.padding = padding;
    }

    /**
     * Add the child field to the parent, and sets the coordinates of the child field.
     */
    public void CellLayout(PdfPCell cell, iTextSharp.text.Rectangle rect, PdfContentByte[] cb) {
        parent.AddKid(kid);
        kid.SetWidget(new iTextSharp.text.Rectangle(
                                                    rect.GetLeft(padding),
                                                    rect.GetBottom(padding),
                                                    rect.GetRight(padding),
                                                    rect.GetTop(padding)
                                                    ),
                                                    PdfAnnotation.HIGHLIGHT_INVERT
                                                    );
    }
}

Then just set the CellEvent on any cells that should have fields in them.
//File to create
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");

//Standard PDF creation, nothing special here
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, fs)) {
            doc.Open();

            //Create a root form object that we'll add "children" to. This way we don't have to add each "child" annotation to the writer
            var root = PdfFormField.CreateEmpty(writer);
            root.FieldName = "root";

            //Create a two column table
            var t = new PdfPTable(2);

            //Add a basic cell
            t.AddCell("First Name");

            //Create our textfield, the rectangle that we're passing in is ignored and doesn't matter
            var tf = new TextField(writer, new iTextSharp.text.Rectangle(0, 0), "first-name");

            //Create a new cell
            var cell = new PdfPCell();

            //Set the cell event to our custom IPdfPCellEvent implementation
            cell.CellEvent = new ChildFieldEvent(root, tf.GetTextField(), 1);

            //Add the cell to our table
            t.AddCell(cell);

            //Add the table to the document
            doc.Add(t);

            //IMPORTANT! Add the root annotation to the writer which also adds all of the child annotations
            writer.AddAnnotation(root);

            //Clean up
            doc.Close();
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert and insert string value 9,999.99 to float/double in sql using php I have arrays of data (import from excel) values in string. One of the data are accounting numbers eg: 9,999.99
my sql data type for that accounting numbers is float.
each time I insert the value.. it only store 9 instead 9,999.99
And I plan to store in format 9999.99 (without the comma)
I cannot change the sql data type to string as it will be use for calculations later on.. so how do i convert and store the data?
appreciate your suggestions.
Thanks
This is my code to insert into DB
// To set HMS daily collection
function set_pbb_data($sheetDataPBB)
{
    $OK = 0;
    $notOK = 0;
    $firstElement = true;

    foreach ($sheetDataPBB as $value)
    {
        if ($firstElement) {
            $firstElement = false;
        }
        else {
            $dbEntry = array(
            'sett_date'     => $value[0],
            'trans_date'    => $value[1],
            'card_no'       => $value[2],
            'card_type'     => $value[3],
            'trans_curr'    => $value[4],
            'trans_amt'     => $value[5],
            'sett_curr'     => $value[6],
            'sett_amt'      => $value[7],
            'gross_cur'     => $value[8],
            'gross_amt'     => $value[9],
            'mdr'           => $value[10],
            'mid'           => $value[11],
            'approval_code' => $value[12],
            'status'        => $value[13],
            'tid'           => $value[14],
            'batch_no'      => $value[15],
            'dba'           => $value[16],
            'trace_no'      => $value[17],
            'prod_type'     => $value[18]
            );
            if ($value[0] != null){
                $this->db->insert('pbb_cc_tbl', $dbEntry);
                if ($this->db->affected_rows() > 0) {
                    $OK++;
                }
                else {
                    echo '<script>alert(" '.$value[0].' Already Exist!");</script>';
                    $notOK++;
                }
            }
        } //end-if
    } //end-foreach

    if ($this->db->affected_rows() > 0) {
        echo '<script>alert("'.$OK.' PBB Data Added Successfully");  </script>';
    }
    else {
        echo '<script>alert("'.$notOK.' PBB Data Already Exist!"); window.history.back();</script>';
    }
}

A: read each row in excel and insert one by one using sql query
 insert into database.table (value) values (cast("999,99" as decimal(9,3)));


text:
Q: php if statement within/inside single variable? I'm not sure if this will work, or how to make it work.
Any help would be so great thanks.
I need to make this contitional statement string into one variabe?
How can I do this?
if ($address1) {
    echo $address1 . ', ';
}

if ($address2) {
    echo $address2 . ', ';
}

if ($address3) {
    echo $address3 . ', ';
}

if ($address4) {
    echo $address4 . ', ';
}

if ($townCity) {
    echo $townCity . ', ';
}

if ($county) {
    echo $county . ', ';
}

if ($postCode) {
    echo $postCode;
}

So basically I need this in one variable, and the reason I have it in if statements, is because it is possible for the some off these variables to not exist.
And after each variable, it has a comma and space.
If I do it like this...
$singleVar =    $address1 . ', ' .
                $address2 . ', ' .
                $address3 . ', ' .
                $address4 . ', ' .
                $townCity . ', ' .
                $county . ', ' .
                $postCode;

Then for the variables that do not exist, will have and extra comma and space - not cool.

Can any one please advise.
Thanks

A: Lots of ways to do it, but here's what I'd use:
$items = array(
    $address1,
    $address2,
    $address3,
    $address4,
    $townCity,
    $county,
    $postCode
);
echo implode(', ', array_filter($items));

array_filter removes the "empty" ones, see converting to boolean in the PHP docs.
implode joins the array items together by the string you pass as the first argument, and makes sure there is no extra , dangling off the end of the output.
If you're worried the variables may not defined, use something like this instead:
$items = array();
$fields = array(
    'address1',
    'address2',
    'address3',
    'address4',
    'townCity',
    'county',
    'postCode'
);
foreach ($fields as $field)
{
    isset($$field) && $items[] = $$field;
}
echo implode(', ', $items);

Just remember that isset checks if something is "set", not if it is "empty". For example,  a variable with an empty string or a zero is "set", but fails the if ($var) condition.

A: $address1 = 'foo';
$address3 = 'bar';
$postCode = 'baz';

$vars = array();
foreach (array('address1', 'address2', 'address3', 'address4', 'townCity', 'county', 'postCode') as $var)
{
    isset($$var) and $vars[] = $$var;
}
$single = implode(', ', $vars);

Test http://codepad.org/WwzRYvuO

A: If the variables actually don't exist, you'll need isset to check for that. If they do exist but are empty/null/false, you may use the answer by Wesley Murch.
$singleVar = '';
$variables = array('address1','address2','address3',
                   'address4','townCity','county','postCode');

foreach($variables as $variable)
{
    if (isset($$variable))
      $singleVar .= ($$variable . ', ');
}

A: You can do it using variable variables, like so:
$arr = array('address1','address2','address3','address4','townCity','county','postCode');
$singleVar = '';
foreach ($arr as $val) {
   if (isset($$val)) {
      $singleVar .= $$val . ', ';
   }
}

A: $string='';
if($address1)
  $string.= $address1.',';
if(address2)
  $string.= $address2.',';
//...etc
echo $string;

A: i would propose the following:
join(array_filter(array($a,$b,$c,$d,$e,$f)), ", ");

with $a, etc being your variables. cf. https://stackoverflow.com/a/2603047/1689451


text:
Q: ASP - CDO Email Configuration Issue I have a legacy ASP application that I moved from a old server to Windows 2012 server with IIS 8.5.
I see the email sending is failing with the below error in IIS logs.

80040220|The__SendUsing__configuration_value_is_invalid

Current code is
Dim MyCDONTSMail2
Dim HTML
Set MyCDONTSMail2 = CreateObject("CDO.Message")
HTML = "all html format of mail content"
MyCDONTSMail2.From= "some from address"
MyCDONTSMail2.To="some to address"
MyCDONTSMail2.Subject="My Subject"
MyCDONTSMail2.HTMLBody=HTML
MyCDONTSMail2.Send
set MyCDONTSMail2=nothing

I have read a few other articles over Internet and this as well.  I add a little bit of configuration in the code as shown in all other articles
MyCDONTSMail2.HTMLBody=HTML
MyCDONTSMail2.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
MyCDONTSMail2.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")="SMTP Server Name"
MyCDONTSMail2.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
MyCDONTSMail2.Configuration.Fields.Update
MyCDONTSMail2.Send
set MyCDONTSMail2=nothing

But I still get the same error.  My SMTP Server Name is absolutely correct as I used the same server in my other .Net applications hosted on the same server to this ASP application.  The .Net app works well with the same configuration.
I'm not sure if ASP pages need any other configuration / installation required.
I have also tried to configure my SMTP server inside the IIS Website --> SMTL E-mail and changing the smtp server in the ASP code to localhost.  But, it also resulted in the same error.
EDIT: Application Pool is set to Classic Pipeline Mode and Identity as NetworkService

A: Your provided sample code is not SMTP Authenticated...please try to use SMTP Authenticated script..
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "mail@yourdomain.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "email account password"
After that, have a check with email delivery.


text:
Q: Upload a picture with a php function It's the first time I'm trying to create a function and I can't figure it out...
I'm trying to build a function who will upload a picture and return her path, but the echo doesn't display anything andI don't have any syntaxe error tho... I don't really understand?
I hope you may see more clearer than me.
function.inc.php:
function upload_photo(
$photo_input_name, $photo_path, $photo_type1, $photo_type2, $photo_max_weight, $photo_max_height, $photo_max_width)
{

if (isset($_FILES[$photo_input_name]))
{

    //UPLOAD DE FICHIER
    if(!empty($_FILES[$photo_input_name]['tmp_name']))
    { //si n'est pas vide

        //spécification du chemin d'enregistrement
        $dossier = $photo_path;

        if (exif_imagetype($_FILES[$photo_input_name]['tmp_name']) != $photo_type1 AND exif_imagetype($_FILES[$photo_input_name]['tmp_name']) != $photo_type2)
        { //si le format de l'image est différent de jpg ou png
            $erreur = 'Oups, extension non reconnu. Les extensions autorisées sont '.$photo_type1.' '.$photo_type2.'.';
        }

        else
        { //si l'image est un jpg ou png

            //on défini le poid max et on appel le poid de l'image uploader
            $max_weight = $photo_max_weight;
            $weight = filesize($_FILES[$photo_input_name]['tmp_name']);

            if ($weight > $max_weight)
            { // si le poid de l'image est supérieur au poid max autorisé
                unlink($_FILES[$photo_input_name]['tmp_name']);
                $erreur = 'Oups, le fichier est trops volumineux, il ne doit pas depasser '.$photo_max_weight.' mo.';
            }

            else
            { // si le poid de l'image est inférieur ou egal on continue
                $max_height = $photo_max_height;
                $max_width = $photo_max_width;
                $photo_size = getimagesize($_FILES[$photo_input_name]['tmp_name']);

                if ($photo_size == FALSE)
                { // si les informations récuperer par la fonction getimagesize ne sont pas valide,
                    // le fichier n'est pas une image, on le supprime et affiche une erreur
                    unlink($_FILES[$photo_input_name]['tmp_name']);
                    $erreur = 'Oups, il semble que le fichier ne soit pas valide.';
                }

                if ($photo_size[1] != $max_height AND $photo_size[0] != $max_width)
                { // si les dimensions de l'image sont differentes de $photo_max_width/height,
                 // on efface l'image uploader et on affiche une erreur
                    unlink($_FILES[$photo_input_name]['tmp_name']);
                    $erreur = 'Oups, il semble que l\'image ne soit pas au bon format ('.$max_width.' x '.$max_height.' px).';
                }

                if (!isset($erreur))
                { // si il n'y a aucune erreur on continue vers l'enregistrement

                    if (is_file($dossier.$_FILES[$photo_input_name]['name']))
                    {// si il y a un fichier du même nom dans le dossier on lui ajoute un prefix

                        $file_upload = rand (0, 15).'_'.$_FILES[$photo_input_name]['name'];

                        $fichier = $file_upload;
                    }

                    else $file_upload = $_FILES[$photo_input_name]['name'];

                    $fichier = $file_upload;

                    if(move_uploaded_file($_FILES[$photo_input_name]['tmp_name'], $dossier . $fichier))
                    { //si l'image est uploader
                        echo $dossier.$fichier;
                        return true;
                    }
                }

                else
                { //si l'upload echoue

                    $erreur = 'Oups, la copie de la photo sur le serveur a échoué';

                }

            }

        }

    }

}

}

And the page where I'm trying to use my function:
if (isset($_FILES))
{
    include('function.inc.php');

    $photo_input_name = 'photo_buste_coeurG_'.$line;
    $photo_path = '../../images/uploaded/';
    $photo_type1 = 'IMAGETYPE_JPEG';
    $photo_type2 = 'IMAGETYPE_PNG';
    $photo_max_weight = 1048576;
    $photo_max_height = 480;
    $photo_max_width = 480;

    upload_photo($photo_input_name, $photo_path, $photo_type1, $photo_type2, $photo_max_weight, $photo_max_height, $photo_max_width);

}

Thank you for your time.

A: The problem is here
if ($photo_size[1] != $max_height AND $photo_size[0] != $max_width)

You only allow photos that are exactly $max_height high and exactly $max_width wide. Those != should be >. Also, the AND should OR (or ||, which is more commonly used)
Also IMAGETYPE_JPEG and IMAGETYPE_PNG are constants, you should use them as such, not put that value in a string; it doesn't work.
While we're here, allow me to comment on how the function is set up.
There are a few structural problems in your code.

*

*You are assigning variables the value of other variables quite often, which is quite confusing and unnecessary.

*You are constantly doing if ... then ... else which is making the code overly complex. Just if it is not, and then return (or, better, throw an Exception).

*You are limiting yourself to two photo types. What if you ever want to remove on of them? What if you ever want to add one? You need to go through all your code and replace the function calls. Instead, use an array so you can give an arbitrary number of options.

For reference, this is how I would write your function
// the function is called upload_photo, no need to prepend photo to each and every argument
function upload_photo($input_name, $path, array $types, $max_weight, $max_height, $max_width)
{
    if (empty($_FILES[$photo_input_name]['tmp_name']))
    {
        throw new Exception('No file uploaded');
    }

    $type = exif_imagetype($_FILES[$photo_input_name]['tmp_name']);
    if (!in_array($type, $types))
    { //si le format de l'image est différent de jpg ou png
        throw new Exception('Oups, extension non reconnu. Les extensions autorisées sont '.implode(',', $types).'.');
    }

    $weight = filesize($_FILES[$photo_input_name]['tmp_name']);
    if ($weight > $max_weight)
    { // si le poid de l'image est supérieur au poid max autorisé
        unlink($_FILES[$photo_input_name]['tmp_name']);
        throw new Exception('Oups, le fichier est trops volumineux, il ne doit pas depasser '.($max_weight / 1024 / 1024).' mo.');
    }

    $photo_size = getimagesize($_FILES[$photo_input_name]['tmp_name']);
    if ($photo_size == FALSE)
    { // si les informations récuperer par la fonction getimagesize ne sont pas valide,
        // le fichier n'est pas une image, on le supprime et affiche une erreur
        unlink($_FILES[$photo_input_name]['tmp_name']);
        throw new Exception('Oups, il semble que le fichier ne soit pas valide.');
    }
    if ($photo_size[1] > $max_height || $photo_size[0] > $max_width)
    { // si les dimensions de l'image sont differentes de $photo_max_width/height,
     // on efface l'image uploader et on affiche une erreur
        unlink($_FILES[$photo_input_name]['tmp_name']);
        throw new Exception('Oups, il semble que l\'image ne soit pas au bon format ('.$max_width.' x '.$max_height.' px).');
    }

    if (file_exists($path.$_FILES[$photo_input_name]['name']))
    {// si il y a un fichier du même nom dans le dossier on lui ajoute un prefix
        // FIXME: What if the renamed file also already exists? -- left as an exercise for the reader
        $fichier = rand (0, 15).'_'.$_FILES[$photo_input_name]['name'];
    }
    else
    {
        $fichier = $_FILES[$photo_input_name]['name'];
    }

    if(!move_uploaded_file($_FILES[$photo_input_name]['tmp_name'], $path . $fichier))
    { //cannot move file
        throw new Exception('Oups, la copie de la photo sur le serveur a échoué');
    }

    return $dossier.$fichier;
}

and then this is how you would call it
if (isset($_FILES))
{
    include('function.inc.php');

    $input_name = 'photo_buste_coeurG_'.$line;
    $path = '../../images/uploaded/';
    $types = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);
    $max_weight = 1048576;
    $max_height = 480;
    $max_width = 480;

    try {
        upload_photo($input_name, $path, $types, $max_weight, $max_height, $max_width);
    } catch (Exception $e) {
        echo 'Erreur: '.$e->getMessage();
    }
}


text:
Q: How to use Data.Type.Natural's Typeable Instance Data.Type.Natural just added a Typeable instance, one for the promoted type 'Z and one for 'S. Although in practice this means that every Nat is Typeable, the compiler doesn't seem to know that. As a result, I'm having trouble making use of the instance to (for example) show a Nat:
{-# LANGUAGE ExistentialQuantification, DataKinds, PolyKinds, ScopedTypeVariables #-}
module Foo where

import Data.Constraint
import Data.Proxy
import Data.Type.Natural
import Data.Typeable

import Unsafe.Coerce

data Depth a = forall n . D (Proxy (n :: Nat))

getConstraint :: forall n . Proxy n -> Dict (Typeable n)
getConstraint _ = unsafeCoerce (Dict :: Dict ())

instance Show (Depth a) where
  show (D proxy) =
    case getConstraint proxy of
      Dict -> show $ typeRep proxy

test :: Depth a -> Depth a -> Depth a
test (D (Proxy::Proxy n1)) (D (Proxy::Proxy n2)) = D (Proxy::Proxy (Max n1 n2))

main = print $ show $ test (D (Proxy::Proxy N0)) (D (Proxy::Proxy N1))

This fails at runtime with the error internal error: stg_ap_v_ret
Richard Eisenberg said "An unsafeCoerce Dict can be used to satisfy any arbitrary constraint" in this mailing list. I tried that idea here, but my solution is triggering a GHC "bug". However, when I looked on the GHC trac, I found that GHC is allowed to get angry if unsafeCoerce is used improperly, and I suspect that's just what I've done.
Another approach is to try to get the constraint from a GADT:
{-# LANGUAGE ExistentialQuantification, DataKinds, PolyKinds, GADTs, ScopedTypeVariables #-}
module Foo where

import Data.Constraint
import Data.Proxy
import Data.Type.Natural
import Data.Typeable

import Unsafe.Coerce

data Depth :: (* -> *) where
  D :: forall n a . (Typeable n) => Proxy (n :: Nat) -> Depth a

instance Show (Depth a) where
  show (D proxy) = show $ typeRep proxy

test :: Depth a -> Depth a -> Depth a
test (D (Proxy::Proxy n1)) (D (Proxy::Proxy n2)) = D (Proxy::Proxy (Max n1 n2))

main = print $ show $ test (D (Proxy::Proxy N0)) (D (Proxy::Proxy N1))

but test cannot deduce Typeable (Max n1 n2), and I don't see any way to make GHC deduce that other than the unsafeCoerce hack attempted in the other solution.
In my actual code, I'm trying to get away with keeping Depth of kind * -> * and to have the Nat type existentially quantified. Any other ideas on how I could print out the Nat value in a Depth?


text:
Q: How to evaluate user-defined functions with variables? I have an extremely simple question, but I couldn't find anything anywhere, maybe I didn't know what to search for, so feel free to mark it as duplicate if there is a duplicate.
Let's say that I define some function, for example
f[p_Integer] := Sum[k!/(k^2 - 3), {k, 0, p}].
If I want to evaluate it for some integer, for example f[10], it works, as expected. But what if I want to evaluate it for a variable, for example f[n], how do I tell Mathematica to do it? I get f[n] as the result, but that's not so useful.
I'm interested in the general solution, nevermind my example, I had to use something.

A: Well, you told M that the argument to f must have Integer head. So when you said f[n] and n is not integer, then M did not know what to do and returned back the input. If you wanted f to be evaluated for non integer heads, you can do
ClearAll[n,f,p]
f[p_Integer]:=Sum[k!/(k^2-3),{k,0,p}]
f[p_]:=Sum[k!/(k^2-3),{k,0,p}]  (*or can also use f[p_Symbol]*)

Now
f[5]

f[n]


text:
Q: Install fonts in Guix System How do I install a font in Guix System? (Not installed in graphical environment)

A: Search for fonts (using recutils to filter results , only name will be displayed):
guix package -s font |recsel -p name

You can add a short discription for the results:
guix package -s font |recsel -p name,synopsis

Then install the desired fonts. e,g:
guix package -i font-dejavu

update fontconfig cache:
guix package -i fontconfig
fc-cache -rv

For ttf/otf : guix package -s ttf or guix package -s font |grep ttf:
guix package -i font-gnu-freefont

To install the local font file, drop the font or folder with the font in (/home/.local/share/fonts). If the fonts folder does not exist, create it!


text:
Q: Reading data from Arduino Bluetooth on Windows Phone 8.1 I am developing a code that will allow me to send small amounts of data between my arduino mega and my windows 8.1 phone using a HC-05 bluetooth module.
Sending data from the phone to the arduino was pretty simple, but I am having a dire time attempting to read data that comes back from the arduino that I send on the serial port.
For testing purposes my code is simple, sending ascii charaters 'a' & 'b' to turn an LED on & off, this could not work any better, but I am having trouble trying to figure out how to correctly read the data that I send back to my phone.
I send a single arbitrary ascii character back to the phone but I cannot for the life of me figure out the correct way of reading this data from the bluetooth stream I have setup.
I have been trying for nearly two days, but everything I try ends up freezing my phone with no exceptions thrown? A lot of posts online send me to the Nokia dev site which is now inactive.
I have tried using the 'datareader' and the 'streamreader' classes to do this but it always freezes, does anyone know how to make this work? And why my streamreader keeps freezing my phone?
I have tried to annotate my code appropriatley (seen below). The problem occurs in the 'Tick' event handler at the bottom of the code.
(FYI: All capabilities have been added to the manifest files so this shouldn't be the problem).
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Bluetooth_SL.Resources;
using Windows.Networking;
using Windows.Networking.Proximity;
using Windows.Networking.Sockets;
using Windows.Devices.Bluetooth;
using System.IO;
using Microsoft.Xna.Framework;
using System.Windows.Threading;
using Windows.Storage.Streams; // <-- for the datareader class

namespace Bluetooth_SL // silverlight, does this matter?
{
    public partial class MainPage : PhoneApplicationPage
    {
        DispatcherTimer Timer = new DispatcherTimer();
        StreamSocket socket = new StreamSocket();
        StreamWriter writer;
        StreamReader reader;

        public MainPage()
        {
            InitializeComponent();
            Timer.Interval = TimeSpan.FromMilliseconds(1000); // dispatcher timer used to check for incoming data from arduino
            Timer.Tick += Timer_Tick; // event handler for dispatcher timer
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e) // frees up memory
        {
            socket.Dispose();
        }

        private void Connect_But_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ConnectToBluetooth();
        }

        private async void ConnectToBluetooth() // sets up the connection // this works fine
        {

            // Configure PeerFinder to search for all paired devices.
            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
            var pairedDevices = await PeerFinder.FindAllPeersAsync();

            if (pairedDevices.Count == 0)
            {
                Debug_Block.Text = "No paired devices were found.";
            }
            else
            {
                Debug_Block.Text = "Found";
                PeerInformation selectedDevice = pairedDevices[0]; // pick the first paired device

                try // 'try' used in the case the socket has already been connected
                {
                    await socket.ConnectAsync(selectedDevice.HostName, "1");

                    writer = new StreamWriter(socket.OutputStream.AsStreamForWrite());
                    writer.AutoFlush = true;

                    reader = new StreamReader(socket.InputStream.AsStreamForRead());
                    Debug_Block.Text = "Connected";
                }
                catch (Exception x)
                {
                    Debug_Block.Text = x.ToString();
                }
            }
        }

        private void SendButton_Tap(object sender, System.Windows.Input.GestureEventArgs e) // this works perfectly
        {
            try { writer.WriteLine("a"); } // attempts to write the ascii 'a' to the arduino which turns on the on-board LED
            catch { Debug_Block.Text = "Failed to write"; }
        }

        private void SendButton_Off_Tap(object sender, System.Windows.Input.GestureEventArgs e) // this works perfectly
        {
            try { writer.WriteLine("b"); } // attempts to write the ascii 'b' to the arduino which turns off the on-board LED
            catch { Debug_Block.Text = "Failed to write"; }
        }

        private void ReadButtonToggle_Tap(object sender, System.Windows.Input.GestureEventArgs e) // toggles the timer on and off
        {
            if(Timer.IsEnabled == true)
            {
                Timer.Stop();
                Debug_Block.Text = "Timer Stopped";
            }
            else
            {
                Timer.Start();
                Debug_Block.Text = "Timer Started";
            }
        }

        void Timer_Tick(object sender, EventArgs e) // THIS IS THE PROBLEM
        {
            Debug_Block.Text = "Tick";
            Debug_Block.Text = reader.ReadLine(); // <-- ALWAYS FREEZES HERE
            Timer.Stop(); // This line is temporary for debugging
        }
    }
}


text:
Q: CakePHP saveAll/saveAssociated issue I'm a bit confused with the following CakePHP outcome. I included code for two Model and one Controller (stripped out unnecessary stuff).
Problem: Everything saves correctly. The only issue is the user_id field for the store_users table does not save.
Anything obvious you can see that I'm doing wrong? I tried with both saveAssociated and saveAll.
Model/Store.php
<?php
App::uses('AppModel', 'Model');
class Store extends AppModel {
    public $belongsTo = array(
        'User'
    );
    public $hasMany = array(
        'StoreUser'
    );
}

Model/StoreUser.php
<?php
App::uses('AppModel', 'Model');
class StoreUser extends AppModel {
    public $belongsTo = array(
        'User',
        'Store'
    );
}

Controller/StoresController.php
<?php
App::uses('AppController', 'Controller');
class StoresController extends AppController {
    public $uses = array('Store');

    public function create() {
        $this->Store->create();
        $storeData = array(
            'Store' => array(
                'title' => 'New Store',
                'user_id' => $this->Auth->user('id')
             ),
             'StoreUser' => array(
                 'user_id' => $this->Auth->user('id')
              )
        );
        if($this->Store->saveAll($storeData) !== false) {
            // Success
        } else {
            // Error
        }
    }
}

Results in DB
stores table:
    id: 1
    title: New Store
    user_id: 1
    ...

store_users table:
    id: 1
    store_id: 1
    user_id: 0
    ...

A: Found it! Because Store hasMany StoreUser and not Store hasOne StoreUser I must wrap the user_id in the supplied data in an array.
Controller/StoresController.php
<?php
App::uses('AppController', 'Controller');
class StoresController extends AppController {
    public $uses = array('Store');

    public function create() {
        $this->Store->create();
        $storeData = array(
            'Store' => array(
                'title' => 'New Store',
                'user_id' => $this->Auth->user('id')
             ),
             'StoreUser' => array(
                 array(
                     'user_id' => $this->Auth->user('id')
                 )
              )
        );
        if($this->Store->saveAll($storeData) !== false) {
            // Success
        } else {
            // Error
        }
    }
}


text:
Q: How to configure a local proxy to send custom header request? i'm doing some tests on a webpage using jmeter and selenium.
What i need to do is to send some custom header request and i would like to do it by using a proxy server in local. For several reasons i can't use browsr plugins, and i cannot use the jmeter header customization because of the using of selenium.
So, I'm trying to deal by using apache, but i'm totally new at this and probably i'm doing something wrong. Here's the part of the code that i'm changing from the config file(the last istructions at the end of the file), but no headers are added:
###HEADER###
RequestHeader set Host "summer-gc.snam.it"
RequestHeader set X-Dynatrace_PerfTest "SN=SUMMER_TC01.jmx;RN=01_01_login;TRT=20210422-
100000;VU=2;DUR=120;MVU=3;RMP=1"
###PROXY###
ProxyRequests Off
<Proxy *>
Require all granted

#54.90.58.153 -> postmanecho

ProxyPreserveHost On
ProxyPass / http://172.25.36.197:80/
ProxyPassReverse / http://172.25.36.197:80/
Header add myheader "myvalue"
RequestHeader set myheader "myvalue"

Also i've removed the comment from:
LoadModule headers_module modules/mod_headers.so
How i have to set the config file in order to send new headers?
Also, since i'm not very skilled at this, i'm looking for a program (for windows) that allow me to do it easily? Thank's a lot

A: I might have a better idea for you which is cross platform and doesn't require any software installation/configuration: consider using BrowserMob Proxy instead of Apache proxy server

*Download BrowserMob proxy (inlcuding all dependencies) and drop the jars to JMeter Classpath

*Add setUp Thread Group with 1 user/1 iteration

*Add JSR223 Sampler and put the following code into "Script" area:
def proxy = new net.lightbody.bmp.BrowserMobProxyServer()
def proxyPort = 8080
proxy.setTrustAllServers(true)
proxy.addRequestFilter((request, contents, info) -> {
  request.headers().add('foo', 'bar')
  return null
})
proxy.start(proxyPort)
props.put('proxy', proxy)

*Add "normal" Thread Group

*Add JSR223 Sampler to this Thread Group and put the code to instantiate the browser and open the page you want to open (and do whatever else stuff you need to do)
System.setProperty('webdriver.chrome.driver', 'c:/apps/webdriver/chromedriver.exe')
def proxy = new org.openqa.selenium.Proxy()
proxy.setHttpProxy('localhost:8080')
def options = new org.openqa.selenium.chrome.ChromeOptions()
options.setCapability('proxy', proxy)
def driver = new org.openqa.selenium.chrome.ChromeDriver(options)
driver.get("http://example.com")
driver.quit()

at this stage the proxy will add header foo with the value of bar to each outgoing request from the browser

*A good idea would be stopping the proxy in the tearDown Thread Group, again add a JSR223 Sampler and use the following code:
def proxy = props.get('proxy')
proxy.stop()

Demo:


text:
Q: After reinstalling a package, the cproj file was changed I issued the following command in the nuget console:
update-package mvcreportviewer -reinstall -ProjectName Myproject

and for some reason it added the following in my cproj file:

<Reference Include="MvcReportViewer, Version=0.3.5167.24909, Culture=neutral, processorArchitecture=MSIL">
  <HintPath>..\..\..\Build Files\packages\MvcReportViewer.0.3.1\lib\net40\MvcReportViewer.dll</HintPath>
  <Private>True</Private>
</Reference>

What is the purpose of this? Why is it not enough to simply have the version number in packages.config?


text:
Q: ASP.NET MVC - View with master page, how to set title? What is prefered way of setting html title (in head) for view when using master pages?
One way is by using Page.Title in .aspx file, but that requires  in master page which can mess with HTML code. So, lets assume no server side controls, only pure html. Any better ideas?
UPDATE: I would like to set title in view NOT in the controller or model.

A: In our master pages, we created both an "init" ContentPlaceHolder, and a "title" ContentPlaceHolder.  If someone wants to programatically set Page.Title, they can set it in CSharp in the init placeholder, or they can override the "title" placeholder using tags.
Master Page
<asp:ContentPlaceHolder id="init" runat="server"></asp:ContentPlaceHolder>
<head runat="server">
    <asp:ContentPlaceHolder ID="title" runat="server">
        <title><%=this.Page.Title%></title>
    </asp:ContentPlaceHolder>
</head>

View Page
Could either override the entire "title" content placeholder:
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
       <title>Home Page</title>
</asp:Content>

or programatically set the page title.
<asp:Content ID="Content1" ContentPlaceHolderID="init" runat="server">
    <%this.Title = "Home Page";%>
</asp:Content>

Make sure you remove the Title="" from the Page directive at the top, or you won't be able to programatically change Page.Title.

A: When I create a new MVC project it has files in there and uses a master page.  Looking at that it seems it passes the title to the ViewData as ViewData["Title"] and in the master page, in the <head> there is a script block that outputs ViewData["Title"].

A: I see a lot of people that use the <%= ViewData["Title"] %> option.
I suppose you could also insert a ContentPlaceHolder named Title and then just use that on  your page, but in all the MVC examples I've seen, they use the first option.

A: I ended up using a code-behind file to implement Page.Title="..." in the Page_Load() method.
I didn't like doing this, however attempts to implement the change directly in the .aspx page did not work, as it resulted in two <title> tags being present, the one I generated, and the one generated by the Master file the page inherited from.
Ideally, my page code should have overridden the master file's <title> value, but I guess this is just one of those quirks that ASP.Net MVC still has, and one that may already be fixed in a newer version of the ASP.Net MVC Framework (we're still on ASP.Net MVC Beta)

A: You could do this in your Master Page:
<title>
    <%:MyTitle + " :: " %>
    <asp:ContentPlaceHolder ID="TitleContent" runat="server">
    </asp:ContentPlaceHolder>
</title>

where MyTitle = some value from your web.config or hard text like "My Web"
Now in the view pages (Index for example):
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<%:"My Home Page"%>

Now when you browse your home page, the title would be "My Web :: My Home Page".

A: I have a base view class that sets the page title from a resource file. Works pretty good for me.

A: I created a class called Application with a Title property (using get/set):
public static class Application
{
    static string title;

    public static string Title
    {
        get { return title; }
        set { title = value; }
    }
}

I then set the property on the Page_Load event for each page:
Application.Title = "Silly Application";

then i just reference that property on the master page:
<div id="divApplicationTitle">
     <asp:HyperLink runat="server" NavigateUrl="~/Default.aspx"><asp:Image ID="imgApplicationImage" runat="server" SkinID="skinApplicationLogo" /><%=Application.Title%></asp:HyperLink>
</div>

A: You could always use javascript in your view page:
<script type="text/javascript>
    document.title = "Hello World";
</script>

A: We ended up with
<head runat=server visible=false>

in master page.
This way we can read from Page.Title (Page.Title requires head element to exist, otherwise it throws an exception, checked that with reflector). We then use our own head element - MVC way.

A: There is a Title property of the @Page directive for content pages.

A: For ASP.NET content pages just add Title="" in the <%@ %> Placeholder.


text:
Q: Basic statistics problem i have a small statistics problem:
The time spent by students to solve an exam, following a normal distribution, has a mean of 80 minutes, and a standard deviation of 20 minutes.
.. and asks:
What's the minimum time that 30% of the students spent on it?
Can anyone help me finding the way to solve this?
Thanks

A: Let $X=$the time spent by a student on the test. $X$ has normal distribution with mean 80 and standard deviation 20.
You need to solve $$P[X>a]=.3$$
Passing to the  standard normal distribution,   need to solve
 $$P[{X-80\over 20}>{a-80\over20} ]=.3,$$
or,
$$
[Z>{a-80\over20} ]=.3
$$
where $Z$ is the standard normal variable. You need to do a "reverse lookup": go to a table/calculator for the CDF of the standard normal and find the value $z$ with $P[Z>z]=.3$. Call this $z_3$. Then set
$$
z_3= {a-80\over20}
$$
and solve for $a$.


text:
Q: How to access extra mouse buttons on Wayland? Since unfortunately Gnome does not offer any option to configure additional mouse buttons I used to achieve this simple goal by writing a tedious configuration file for xbindkeys.
What I wanted was far from super fancy stuff – as launching a rocket by hitting a mouse button – but only switching workspace by left or right clicking the scroll wheel of my Logitech mouse.
How this is done under Xorg has been answered many times, here for example: How to configure extra buttons in Logitech Mouse
But with Ubuntu 21.04 where – buckle up! – Wayland has become the default display manager, as of now fancy pancy things like xbindkeysand xdotool do not work anymore.
So my question: is there a way to launch missiles – ehm, sorry switch work spaces with my extra mouse button again? Or should I sell them and donate the money to Gnome Fondation?
Please do not propose libratbag and piper, I never got them working in any useful way...

A: The most comfortable solution I found is key-mapper. This applications allows you, to map mouse buttons to shortcuts. I for example use it to switch workspace with the left and right click of my scroll wheel, what fits particularly good with the horizontal layout of workspaces in GNOME 40+:

As you can see, the program comes with a GUI.
Unfortunately it's not in the Ubuntu sources, but you can download an official DEB packages from here: https://github.com/sezanzeb/key-mapper/releases

A: Adding to @user5950 's answer, the app is now called input-remapper, in case anyone is still searching about this, like me


text:
Q: Xcode fstream not saving text to file I have a file in my Xcode directory for this project, and the program will open it, but when I input something, it won't save to the file. Not sure why.
std::string entry;
std::fstream file;

file.open ("a1bc3.txt", std::ios::out | std::ios::in );

if (!file.is_open()){
    std::cin >> entry ;
}
else {
    std::cout << "Failed to open.\n" ;
}

file << entry << std::endl ;
file.close();
return 0;


text:
Q: How to inherit a flask MethodView class without its decorators? For the reason of not rewriting the same API. I want to inherit a get method from an already created MethodView and ignore the login_required decorator.
class DoStuffA(MethodView):
    decorators = [login_required]
    def get(self):
        return jsonify({"status":"ok"})

api.add_url_rule('/dostufa', view_func=DoStuffA.as_view("dostuffa"), methods=['GET'])

class DoStuffB(DoStuffA):
    pass

api.add_url_rule('/dostuffb', view_func=DoStuffB.as_view("dostuffb"), methods=['GET'])

If I do a GET request to /dostuffb,

*

*Does it need to be authenticated?

*Is my inheritance syntax correct?

A: The View.decorators list is applied only when the View.as_view() method is called. If you don't want any decorators to be applied in your subclass, just override the attribute with an empty sequence:
class DoStuffB(DoStuffA):
    decorators = ()  # empty tuple

Now DoStuffB.as_view() will find the empty tuple rather than the inherited DoStuffA.decorators list, and no decorators are applied.


text:
Q: Jquery dynamic rows in form When we click on the link "Add new row", it need to duplicate whole
 and change <input> attribute name to data[+1][xxx] (Number in [] must +1 everytime)
Code: http://jsfiddle.net/c6WG8/

            Link
            <input id="layout_name" name="data[0][link]" type="text" value="">

            Text
            <input id="layout_name" name="data[0][text]" type="text" value="">

Add new row

First part looks ok, but changing name of input has probably some bug.

A: In your jQuery fiddle code on line 9, instead of doing
content.attr("id",function(i,oldVal) {

you should do
content.attr("name",function(i,oldVal) {

since you want to update the name of the input fields and not the id.  Also, there was a small typo in your code.  You initialized the content variable on line 8 with a dollar sign; you should instead do it like this:
var content = $(this).closest('.row').find( "input");

An updated fiddle is here: http://jsfiddle.net/c6WG8/8/


text:
Q: Release Variable assigned a value from file rather than in TFS In the release config, under the Variables tab, I am wondering if it is possible to make the Value point to a file.
I want to do this because we are using the release to run parallel UI tests. Currently, we take the tests and split them out into different chunks which we then define in TFS as Group_A, Group_B, etc..
What we are doing now, is creating a build folder inside the solution that whenever the solution is built, it creates a .txt file of all the namespaces in the test directory. I am trying to use this .txt file as the value of the TestGroup variable in the release. Is this possible?


text:
Q: How to make child component use parent component style How can I make the app-dropdown-select use the style of component A?
component A:

This can be use to make the parent use child component's style:
encapsulation: ViewEncapsulation.None

Is there something like this to make parent style override the child style?

A: You can override the encapsulation with the ::ng-deep piercing CSS combinator (see docs) in the parent (add !important if needed) but it is deprecated because each component must remain modular and autonomous, without causing conflicts between them.
You should prefer using SASS variables and CSS import.


text:
Q: I am trying to configure onesignal into my react-native app by following the documentation but it shows and error of @override I am trying to configure my react native app with one signal I am following the OneSignal Documentation followed every step but when I added the code in my MainApplication.java it shows this error ( error: method does not override or implement a method from a supertype @Override)
I have been trying different solutions available on the internet but none of them worked.
Error:
error: method does not override or implement a method from a supertype
@Override
^
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s
24 actionable tasks: 1 executed, 23 up-to-date
error Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error Command failed: gradlew.bat app:installDebug

Code to add from the documentation:
(MainApplication.java)
import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new ReactNativeOneSignalPackage() // You must return the ReactNativeOneSignalPackage here
      );
    }
  };

   @Override
    public List<ReactPackage> createAdditionalReactPackages() {
    return getPackages();
  }
 }

MainApplication.java
package com.onsignalapp;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new ReactNativeOneSignalPackage()
      );
    }
    @Override
      public List<ReactPackage> createAdditionalReactPackages() {
        return getPackages();
      }

    @Override
      protected String getJSMainModuleName() {
        return "index";
      }
    };

    @Override
      public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
      public void onCreate() {
      super.onCreate();
      SoLoader.init(this, /* native exopackage */ false);
    }
   }

A: Try running react-native upgrade, this will update the mainActivity.java. Maybe that will solve your problem


text:
Q: Searching for text within a webpage I'm currently designing a search algorithm for a document, and just got curious about this while designing the algorithm: how do web browsers search a webpage?
For example, in Google Chrome, you can press the keyboard shortcut Ctrl-F to activate the "Find" bar, which will let you search a particular webpage for text. How does it do that, given that it only has the raw HTML as reference?

A: When you say that you are designing a search algorithm for a document, could be more specific? Are you doing in within the webpage itself or are you doing this as a server-side operation? Also, are you just trying to find the page/document that matches best or are you searching for a particular element within the page to highlight, much like Firefox and Chrome do?
As @iglvzx mentioned, you should look into DOM. I've setup a very simple example below for implementing a search on a page. The main point I'm trying to show is building up a cache object that is a hash with the DOM element/node as the key and it's searchable text as the value. As for the actual search algorithm, I assume you are building your own but I do have a link to a  project for live-searching in JavaScript that could be of good help.
I'm sure there are plenty of problems with the below code when it comes to actual application, but hopefully this can help point you in the right direction.
// setup a global search-cache
var cache = null;

/**
 * Public: Generate the cache from the existing page. Note, this may need
 *         to be re-run if the DOM (page) changes.
 *
 * Returns nothing; populates a global cache object
 */
function generate_cache() {
    var cache = {};

    $('body').children().each(function () {
        (function process_node(node) {
            var has_children = node.children().length > 0;
            if (has_children) {
                node.children().each(function () { process_node(this); });
            }
            else {
                cache[node] = node.text();
            }
        })(this);
    });
}

/**
 * Public: Search the cache of the page
 *
 * value - The value to search for within the cache
 *
 * Returns the node the text was found in or with the highest score
 * or whatever your search algorithm does.
 */
function search (value) {
    // You're search-code here...
    // I'd recommend that you checkout quicksilver for
    // scoring your results and getting the highst-matching
    // node. You can find the code here:
    // http://ejohn.org/blog/jquery-livesearch/
    // which you'll need to adapt to your situation
}

/*
 * When the document loads, build your cache and bind a keyup event
 * to you search-box.
 */
$(document).ready(function () {
    generate_cache();
    $('#search-box').keyup(function() {
        var node = search($('search-box').val());

        // I assume you'll wan to do something with the node
        // once you've found it so I just made up a function
        // for highlighting the entire node.
        highlight_node(node);
    });
});


text:
Q: Animate contraint change when user is scrolling in tableview I have a view which serves as a container for another 2 views(one view which takes 1/4 of the screen and a table view which takes 3/4 of the screen). What I want is that when the user scrolls up(swipe direction) the tableview, the table view will smoothly go up (up to the screen) and go down when users scrolls down(swipe direction).
So far I have managed so that the tableview goes up but it does it too sudden and can't make it go down.
Here is how i do it:
viewViewTopConstraint is the tableview top constraint to container top constraint
extension StatsOverlayViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
    if scrollView == statsTableView {
        let scrolledOffset = scrollView.contentOffset.y

        while viewViewTopConstraint.constant > 0  && viewViewTopConstraint.constant < 69 {
            print("scrolling with offset\(scrollView.contentOffset.y)")
                self.viewViewTopConstraint.constant -= scrolledOffset
        }
    }
}

func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if scrollView == statsTableView {
        if  viewViewTopConstraint.constant < 0 {
            viewViewTopConstraint.constant = 0
        } else if viewViewTopConstraint.constant > 69 {
            viewViewTopConstraint.constant = 69
        }
    }
}

}
Edit:
Problem with putting the view back down was due to the scrollview.bounces = true and the wrong use of the while loop
Code that works is :
       func scrollViewDidScroll(scrollView: UIScrollView) {
    if scrollView == statsTableView {
        let scrolledOffset = scrollView.contentOffset.y
        UIView.animateWithDuration(0.2, animations: {
            if scrolledOffset > 0 {
                self.viewViewTopConstraint.constant = 0
            } else {
                self.viewViewTopConstraint.constant = self.viewViewTopConstraintOriginalValues
            }
            self.view.layoutIfNeeded()
        })
    }
}

A: You need to call self.view.layoutIfNeeded within UIView.animate block
UIView.animate(withDuration: 1) {
    self.view.layoutIfNeeded
}

Add this code right after you change your constraint. If you want a little bit more control on your animation, use this
UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseInOut], animations: {
    self.view.layoutIfNeeded
}, completion: nil)


text:
Q: invalid write/read of size 1 and XX bytes in 1 blocks are definitely lost in loss record I'm having these issues in my code and I search for solutions here in StackOverflow and in another site but I can't understand why this is happening.
I need to implement a hash table and I will post here the functions of my code that I'm having issues and signalize where occur.
**OBS: When I try to close the file opened in the LOAD function, I receive an error:
 Munmap_chunk: invalid pointer

this happens when the word is *pneumonoultramicroscopicsilicovolcanoconiosis***
// Hashes word to a number
unsigned int hash(const char *word)
{
    int sum = 0;

    for (int i = 1; i <= strlen(word); i++) ****Invalid read of size 1**
    {
        sum = (sum + (i * tolower(word[i]))); ****Invalid read of size 1**
    }

    if (sum > N)
    {
        sum = sum % strlen(word);
    }

    return sum;
}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    // TODO

    FILE *file = fopen(dictionary, "r");****552 bytes in 1 blocks are still reachable in loss record 5 of 5**
    if (file == NULL)
    {
        printf("Could not open this file.\n");
        return 1;
    }
    else
    {
        for (int i = 0; i < N; i++)
        {
            table[i] = NULL;
        }

        char *word1 = malloc(sizeof(LENGTH + 1));

        while (fscanf(file, "%s", word1) != EOF)****Invalid write of size 1**
        {

            node *n = malloc(sizeof(node));
            if (n == NULL)
            {
                free(n);
                return 1;
            }

            strcpy(n->word, word1);****Invalid read of size 1**
            n->next = NULL;

            unsigned int index = hash(word1);

            if (table[index] == NULL)
            {
                table[index] = n;
            }
            else
            {
                n->next = table[index];
                table[index] = n;
            }
        }

        free(word1);
    }

    return true;
}

unsigned int size(void)
{
    // TODO

    int count = 0;
    node *cursor = malloc(sizeof(node));
    cursor->next = NULL;
                                 ****56 bytes in 1 blocks are definitely lost in loss record 1 of 5**
    for (int i = 0; i < N; i++)
    {

        if (table[i] != NULL)
        {
            cursor = table[i];

            while (cursor != NULL)
            {
                count++;
                cursor = cursor->next;
            }
        }
    }

    free(cursor);
    return count;
}

bool unload(void)
{
    // TODO

    int count = size();
    int count1 = 0;
    node *cursor = malloc(sizeof(node));
    node *tmp = malloc(sizeof(node));
    cursor->next = NULL;****56 bytes in 1 blocks are definitely lost in loss record 3 of 5**
    tmp->next = NULL;****56 bytes in 1 blocks are definitely lost in loss record 4 of 5**

    for (int i = 0; i < N; i++)
    {
        if (table[i] != NULL)
        {
            cursor = table[i];

            while (cursor != NULL)
            {
                tmp = cursor;
                cursor = cursor->next;
                free(tmp);
                count1++;
            }
        }
    }

    free(cursor);
    if (count1 == count)
        {
            return true;
        }

    return false;
}


text:
Q: How to export only one class (which uses another class) in TypeScript (CommonJS)? I implemented a "Least Recently Used Cache" (LRU Cache) using a doubly linked list. The linked list consists of nodes (Node class) which are used within a LRUCache class.
To export my module I am using the following pattern:
export class Node { ... }
export class LRUCache { ... }

I am exporting my module as a CommonJS module. With the export class pattern above, I am able to use my module the following way:
var module = require('lru-cache');
var cache = new module.LRUCache();

That's okay, but I don't like the additional "module." part in front of LRUCache. I would like to use my CommonJS exported module like this:
var LRUCache = require('lru-cache');
var cache = new LRUCache();

So I changed my code into this:
class Node { ... }
class LRUCache { ... }
export = LRUCache;

But now TypeScript complains with:

error TS4055: Return type of public method from exported class has or is using private name 'Node'.

It's because LRUCache uses the Node class and Node is not exported when defining export = LRUCache;.
How can I solve this situation? I am using TypeScript 2.1.
Screenshot:

A: With typescript you can simply do:
import { LRUCache } from "lru-cache";
let cache = new LRUCache();

And it will compile into:
var lru_cache_1 = require("./lru-cache");
var cache = new lru_cache_1.LRUCache();

If you prefer to use require, you can:
class Node { ... }
class LRUCache { ... }

export = LRUCache;

And then:
import LRUCache = require('lru-cache');
var cache = new LRUCache();

You can find much more info on this in the following two doc pages:

*

*Module Resolution

*Modules


text:
Q: passing data to new page $_POST with jquery I have two tables and an input inside a form that more or less goes like this:
the table code (the two tables are the same, except for a slight difference in what table it calls):

            Name
            ID
            Company Reg.
            Postcode

        <?php while ($row = $items->fetch_assoc()) : ?>
            <tr class="row" data-address1="<?php echo $row['address1']; ?>"
                data-address2="<?php echo $row['address2']; ?>" data-address3="<?php echo $row['address3']; ?>"
                data-county="<?php echo $row['address4']; ?>" data-postcode="<?php echo $row['postcode']; ?>"
            >
                <?php echo (strlen($row['name'])           > 0 ? $row['name']           : '-'); ?>
                <?php echo (strlen($row['id'])             > 0 ? $row['id']             : '-'); ?>
                <?php echo (strlen($row['company_reg_no']) > 0 ? $row['company_reg_no'] : '-'); ?>
                <?php echo (strlen($row['postcode'])       > 0 ? $row['postcode']       : '-'); ?>

        <?php endwhile; ?>

and my input is a simple one-liner checkbox that asks if none of the above matches the search..
what I'm trying to do, if the user clicks a table row, it posts the .data() attributes of the
 tag to the next step in the form, which is another page.
I've tried the hidden input idea, but because it's in a while loop where the inputs share the same name, the value of the input will be the last in the loop because it's last set. I've also tried ajax:
$.ajax({
    data:    $(this).data(),
    type:    'post',
    url:     'stepDos.php',
    success: function(data)
             {
                 window.location.replace('/path/to/stepDos.php');
             }
});

which didn't work when I var_dumped $_POST it returned empty.
I also tried a $.post function:
$.post('/path/to/stepDos.php', {data: data}, function(ev)
{
    window.location.replace('/path/to/stepDos.php');
});

again no avail - anything I'm missing?
Thanks

A: As I mentioned in the comment, you don't have to make one single form with all the data inside it.. Instead you can go for 1 form per row in a loop.
This will give you the intended result!

A: What you're doing is POST-ing data to the page in the background (that's what the jQuery is for in this case), and just redirecting there with no post data afterwards (that's what window.location.replace(...) does). What I'd suggest is just creating a form and submitting that, that way your browser will copy all the post fields and continue like it would.

A: You could retrive data attributes by calling .data() function, see following snippet:

$(".row").click(function(){
  console.log($(this).data());
});

            Name
            ID
            Company Reg.
            Postcode

            Nome 1
            ID 1
            Company 1
            26027

            Nome 2
            ID 2
            Company 2
            26900

            Nome 3
            ID 3
            Company 3
            20151

A: You can try using hidden inputs with attribute names with array format like below with row['id'] as key index.
<input type="hidden" name="data[<?php echo $row['id'] ?>]['id']" value="<?php echo $row['id'] ?>">
<input type="hidden" name="data[<?php echo $row['id'] ?>]['name']" value="<?php echo $row['name'] ?>">
<input type="hidden" name="data[<?php echo $row['id'] ?>]['company_reg_no']" value="<?php echo $row['company_reg_no'] ?>">
<input type="hidden" name="data[<?php echo $row['id'] ?>]['postcode']" value="<?php echo $row['postcode'] ?>">


text:
Q: Binary Search Tree Insert Method using Recursion is not Working (Python) I typically lean towards iterative solutions for my code but I have recently been struggling with recursion and backtracking for upcoming interviews. So, I was practicing implementing a Binary Search Tree from scratch using Recursion.
What is the issue with the node.data not being recognized? Plus does anyone have any advice with Recursion/Backtracking Algorithms for good practice? I have been spending a lot of time in the debugger stepping through my function but I am still a little iffy on how the stack call when you step backwards works. Any help would be greatly appreciated.
Thank you!!
Error:
"
if data < node.data:
AttributeError: 'NoneType' object has no attribute 'data'"
class Node2():
    def __init__(self, data=None):
        self.left = None
        self.right = None
        self.data = data

class BFS_Recursive():
    def __init__(self):
        self.root = None
        self.numNodes = None

    def insert(self, val):
        if self.root == None:
            self.root = Node2(val)
        else:
            self._insert(self.root, val)

    def _insert(self, node, data):  # I cant figure out why this does not work
        if data < node.data:
            if node.left == None:
                node.left = Node2(data)
            node.left = self._insert(node.left, data)
        elif data > node.data:
            if node.right == None:
                node.right = Node2(data)
            node.right = self._insert(node.left, data)

    def search(self, root, key):
        if root:
            if root.data == key:
                return True
            elif key < root.data:
                return self.search(root.left, key)
            elif key > root.data:
                return self.serach(root.right, key)
        return False

r_bst = BFS_Recursive()
r_bst.insert(5)
r_bst.insert(1)
r_bst.insert(3)
r_bst.insert(7)
r_bst.insert(9)


text:
Q: JavaScript Library to Synchronize Events let's say I'm doing 3 ajax calls and I want to wait for the 3 calls to finish before doing something.
Is there a library out there to synchronize multiple async events in JavaScript ? (using or not jQuery's event system)
Ex.:
var sync = new syncLib();
$('a1').click(sync.newListener());
$('a2').click(sync.newListener());

sync.wait(function(e1, e2) {
  // fired when both a1 and a2 are clicked or when 10 seconds have passed
  // e1 and e2 would have properties to know whether or not they timed out or not..
}, 10 /* timeout */));

I have found this one: https://github.com/Ovea/js-sync/blob/master/README.md, but timeouts are not supported. (Let's say the second ajax call takes too long, I don't want my synchronization to be hung up, I want to set a 10 secs timeout)
I know I can code something myself, but I'm just checking here (after googling for it)
Thanks!
EDIT:
Since then I found async: https://github.com/caolan/async

A: you can use jquery deferred object
here is a useful post http://www.erichynds.com/jquery/using-deferreds-in-jquery/

A: $.when($.ajax("/"), $.ajax("/"), $.ajax("/")).then(function () {
    alert("all 3 requests complete");
});

Documentation

A: The .deferred, .when, .then solution mentioned in other answers is much more elegant, but it's also possible write your own simple solution just so you see how this can be done manually.  You just set a counter for how many ajax calls you have in flight and in the success handler for each ajax calls, you decrement the counter and fire your action when the counter gets to zero.
function DoMyAjaxCalls(callbackWhenDone) {
    var numAjaxCalls = 3;

    // set timeout so we don't wait more than 10 seconds to fire the callback
    // even if ajax calls aren't done yet
    var timer = setTimeout(callbackWhenDone, 10*1000);

    function checkAjaxDone() {
        --numAjaxCalls;
        if (numAjaxCalls == 0) {
            clearTimeout(timer);
            callbackWhenDone();
        }
    }

    // first ajax call
    $.ajax({
        url: 'ajax/test1.html',
        success: function(data) {
            // write code to handle the success function
            checkAjaxDone();
        },
        error: checkAjaxDone
    });

    // second ajax call
    $.ajax({
        url: 'ajax/test2.html',
        success: function(data) {
            // write code to handle the success function
            checkAjaxDone();
        },
        error: checkAjaxDone
    });

    // third ajax call
    $.ajax({
        url: 'ajax/test3.html',
        success: function(data) {
            // write code to handle the success function
            checkAjaxDone();
        },
        error: checkAjaxDone
    });
}

A: Here you have a [library][1] based on jQuery made for that purpose.
In simple use-cases, $.when() is BEST but jcon-q-rency allows you to synchronize any asynchronous code sections.
http://www.megiddo.ch/jcon-q-rency


text:
Q: Weird overlay display issue in jQuery I have an ajax function and thought it would be nice to include a little ajax-spinner to tell the enduser something is actually happening. This is my current jQuery function:
$('#contact-form').submit(function(e)
{
    e.preventDefault();

    let overlay = $('#overlay'),
        loader = $('#loader-popup');

    console.log(overlay);
    console.log(loader);

    console.log('===================');

    //show overlay
    overlay.removeClass('hidden');
    loader.removeClass('hidden');

    console.log(overlay);
    console.log(loader);

    let formData = new FormData($(this)[0]),
        params = [];

    $.ajax({
        data: formData,
        type: 'post',
        url: '/pages/contact-us/action/send.php',
        cache: false,
        contentType: false,
        processData: false,
        success: function(res)
        {
            if (res == 1) {
                params['type'] = 1;
                params['msg'] = 'We will be with you as soon as we can!'
            } else {
                try {
                    res = $.parseJSON(res);
                    let data = [];

                    $.each(res, function(key, value) {data.push(value)});

                    params['type'] = 2;
                    params['msg'] = data.join('
')
                } catch(e) {
                    console.log(e);
                    alert('Huh. that\'s weird, something went wrong! Please try again');

                    //cause syntax error to stop script working
                    die()
                }
            }

            validator.displayAlert(params['type'], params['msg'])
        },
        error: function(res)
        {
            console.log(res);
            alert('Don\'t worry.. it\'s not you, it\'s us.')
        }
    });

    //hide overlay
    overlay.addClass('hidden');
    loader.addClass('hidden');
});

But weirdly the overlay doesn't show, nor does the loader. What makes this hard to kinda debug and fathom is the console.log output.

first console.log(overlay)
  Object [ div#overlay.hidden ]
second console.log(loader)
  Object [ div#loader-popup.hidden ]
third console.log(overlay)
  Object [ div#overlay ]
fourth console.log(loader)
  Object [ div#loader-popup ]

So I can see that my .removeClass() function is working, however, inspecting my page once the form is being submitted shows the elements with the hidden class. If I manually remove that hidden class in the inspector tab then everything shows, so I know it's not a CSS issue.
You can see this happen on a much simpler scale here
I've also tried with .toggle() with no avail.
How do I even begin to debug something that seems to work behind-the-scenes but, not on screen?

A: You should call hide the overlay in your callback, because it'll be executing asynchronously.
Something like
try {
    res = $.parseJSON(res);
    let data = [];

    $.each(res, function(key, value) {
        data.push(value)
    });

    params['type'] = 2;
    params['msg'] = data.join('
')
} catch (e) {
    console.log(e);
    alert('Huh. that\'s weird, something went wrong! Please try again');

    //cause syntax error to stop script working
    die()
} finally {
    //hide overlay

    overlay.addClass('hidden');
    loader.addClass('hidden');
}

A: The logic within the $.ajax() call is asynchronous. As such you remove the class then immediately add it back in as the AJAX request is in progress.
To fix this, change the addClass() calls to be made after the AJAX request completes. In your case the best place to do this would be in the complete callback as it will fire whether the AJAX request completed successfully or with an error:
$('#contact-form').submit(function(e) {
  e.preventDefault();

  let $overlays = $('#overlay, #loader-popup').removeClass('hidden');
  let formData = new FormData(this),
    params = [];

  $.ajax({
    // ajax settings...
    complete: function() {
      $overlays.addClass('hidden');
    }
  });
});


text:
Q: List column names used by a custom function using a panda DataFrame as input I am currently building a small app to post-process more easily data stored in HDF5 files (generated by a  1D simulation proprietary software, the output being basically a very large table with ~10k variables, y-axis corresponding to time). I want the user to be able to write custom functions generating series from the data (for plotting). My problem is that the HDF5 file can be quite large and I would like to open it a single time and extract only the necessary data for performance reasons. Column names to load depend on the user-defined functions, so I need to inspect them and collect the calls to 'df.loc' and 'df.getitem()' to list the columns to extract. I am looking for the best way to do that.
Below is a simplified example of my current implementation, using a 'spy' object wrapping a dummy dataframe and listing the keys used when 'get_item' is called. Something similar could be done for pandas 'loc' dataframe method.
import pandas as pd
from scipy import integrate

# Data for the example
data = {
    'TIME': [0,1,2,3,4,5],
    'frac[air]': [0,0,0,0,0,0],
    'frac[water]': [0.5,0.4,0.2,0,0,0],
    'frac[oil]': [0.5,0.6,0.8,1,1,1],
    'flowrate': [9999,0,0.1,0.2,0,0],
}

def read_data(var_names, loc_filter=None):
    """Simple table reading here, but in real application I am
    reading a large hdf5 file. The filter is typicaly used to
    select time slices (or slices corresponding to some states
    of the system described by the dataframe) through pandas
    dataframe loc method"""
    if loc_filter is None:
        df = pd.DataFrame(data=data)
    else:
        df = pd.DataFrame(data=data).loc[loc_filter]
    return df[var_names]

# User-defined functions using only a few columns of the large dataframe
# Constraint: new functions can be defined by the user ! 2 Examples below
def grp_liq (df, var_name):
    """Summing fractions corresponding to liquids"""
    return df[var_name+'[water]'] + df[var_name+'[oil]']
def integ (df, var_name):
    """Cumulative integration of a variable over time"""
    return pd.Series(integrate.cumtrapz(df[var_name], df['TIME']))

# Creation of a 'spy' object wrapping a dummy dataframe to be able to
# inspect functions
class DFProxyGetItemSpy:
    def __init__(self):
        self._var_names = []
        self._df_dum = pd.DataFrame({'dum':[1]})

    # __getitem__ defined to list used var_names
    def __getitem__(self, key):
        if key not in self._var_names:
            self._var_names.append(key)
        # Returning a dummy series to limit the risk of error raising
        #  if a DataFrame-specific attribute/method is used in the function
        return self._df_dum['dum']

    # __getattr__ defined to pass any attribute to the dummy DataFrame
    def __getattr__(self, name):
        return self._df_dum.__getattribute__(name)

    # Function to reset spy object
    def reset(self):
        self._var_names = []

    @property
    def var_names(self):
        return self._var_names

##################
# DATA REQUEST 1 #
##################

# Spying a user function to list the variables used
spy = DFProxyGetItemSpy()
grp_liq(spy,'frac')
print(spy.var_names)

# Now that we know what variables to extract, we can actualy
# read the data and do our operations
df = read_data(spy.var_names)
print(grp_liq(df,'frac'))

##################
# DATA REQUEST 2 #
##################
spy.reset()

# Spying a second user function, but this time we also want to
# set a filter --> this function needs to be spyied too ...
spy = DFProxyGetItemSpy()
integ(spy,'flowrate')
my_filter = lambda df: df['TIME']>0
my_filter(spy)
print(spy.var_names)

# Now that we know what variables to extract, we can actualy
# read the data and do our operations
df2 = read_data(spy.var_names, loc_filter=my_filter)
print(integ(df2,'flowrate'))

I find this approach inelegant and I am looking for a better way to do that. I have been looking a bit in dask documentation to see if information about the keys used in a function could be extracted from the graph, but I was not successful. To formalize my question: what would be a good way to allow a user to define custom functions to manipulate a dataframe (using any function from pandas), and list the necessary keys to limit the amount of data to load ?
Thanks in advance for any answer, any advice is welcome too !


text:
Q:  does not show toolbar in Android environment I have a problem with primefaces editor . It run smoothly on my chrome and IE

However, it does not display its control on my android emulator when I connect to my web on localhost .

This is my code for it
<!DOCTYPE html>

    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" ></meta>

        <title>Piccolo Theme</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>

        <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'></link>
        <link rel="stylesheet" href="css/bootstrap.css"></link>
        <link rel="stylesheet" href="css/bootstrap-responsive.css"></link>
        <link rel="stylesheet" href="css/jquery.lightbox-0.5.html"></link>
        <link rel="stylesheet" href="css/custom-styles.css"></link>

        <link rel="shortcut icon" href="img/favicon.ico"></link>
        <link rel="apple-touch-icon" href="img/apple-touch-icon.png"></link>
        <link rel="apple-touch-icon" sizes="72x72" href="img/apple-touch-icon-72x72.png"></link>
        <link rel="apple-touch-icon" sizes="114x114" href="img/apple-touch-icon-114x114.png"></link>

        <h:outputScript library="js" name="bootstrap.js"/>

        <h:outputScript library="primefaces" name="jquery/jquery.js" />

    </h:head>

    <h:body>

            <h:form rendered="#{userSession.isLogin}">

                You are #{userSession.username}

                Article header: <h:inputText  value="#{userSession.updateArticleTitle}"></h:inputText>

                Article content:

                <h:commandButton value="Update Article" action="#{userSession.doUpdateArticle}" >
                    <f:param name="articledate" value="#{userSession.updateDate}"></f:param>
                </h:commandButton>
            </h:form>
            <h:form rendered="#{!userSession.isLogin}">
                Please login first !
                <h:link value="Return home" outcome="HomePage"></h:link>
            </h:form>

    </h:body>

Can anyone explain ? My p:calendar works fine both on web and android emulator but p:editor can't :(


text:
Q: How to calculate most important features for Random Forest and Logistic Regression with dummies variables? My df had a lot of categorical variables, so I used
pd.get_dummies()
to be able to train my Random Forest and Logistic Regression models. Everything worked fine, then I asked myself: which components affect the models prediction the most? I thought about using PCA, but I have dummies binary variables, so I don't know if it has interpretability due to the number of variables I have being dummies. I also tried using
RF.feature_importances_
but it's the same; I only have thousands of columns with data where each one influences very little, losing data interpretability. Is there any method to calculate the importance of each variable being dummie? I've seen some discussion on stackoverflow about this. Some say PCA can be used, others say it loses interpretability. I do not look for papers that propose methods. In case there is a solution, I would like it to be implemented in python to use it

A: In general, I'd be really careful about imparting meaning to feature sensitivity (classic correlation is not causation argument), but one major problem is your categories are one hot encoded and spread out, so you need to pick them back up. How you do that somewhat depends on the data and whether you're trying to get importance of an overall category or a label that appears across categories.
I can't write any code because you haven't given any code.


text:
Q: Angular 4 : "export 'AnimationBuilder' was not found in '@angular/animations' I was using these versions

"dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^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/router": "^4.0.0",
    "archiver": "^2.1.0",
    "body-parser": "^1.18.2",
    "core-js": "^2.4.1",
    "cors": "^2.8.4",
    "express": "^4.16.2",
    "file-saver": "^1.3.3",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },

And my application was working perfect.
I tried compile it using ng build --prod --aot and got this error :

ERROR in Metadata version mismatch for module

and by referring this answer I downgraded @angular/animation version from 5 to 4.
Now I am getting this error even if I am compiling using JIT .

Module '"C
  :/Codebase/cdf-onboarding/node_modules/@angular/animations/animations"' has no exported member 'AnimationBuilder'.
Module '"C
  :/Codebase/cdf-onboarding/node_modules/@angular/animations/animations"' has no exported member 'AnimationFactory'.

Thanks!

A: Couple of things, you can try:
1) you should import BrowserAnimationsModule from @angular/platform-browser/animations in your App NgModule.
2) If you import any animations services or tools from @angular/core, you should import them from @angular/animations.
3) please update angular versions too.


text:
Q: How to get social account (facebook,twitter,snapchat) userid from an AccountManager? Is it possible? hai i am trying to gather user details like userid,username,email etc stored in accountmanager by social applications from my currently developing application.
I was able to get basic details like
{name=myemail@gmail.com,type=com.google}
{name =Facebook,type=com.facebook.auth.logn}

As i need more information i thought of using getUserdata() what is the key i should pass in the below method? Also will i be able gather these data?
public String getUserData (Account account,
            String key)

While going through documentation i saw  that This method requires the caller to have a signature match with the authenticator that owns the specified account.


text:
Q: Simple way to select elements of a list that intersect with another list? (python) In R, if I want all elements of x that are in y, I'd do
x[x %in% y]

In python, I can use list comprehension:
[i for i in y if i in x]

Is there a cleaner/more readable way?  I'm getting the hang of python, but the code that I'm writing isn't nearly as readable as I'm accustomed to.  The first thing I tried didn't work:
x[x in y]

I guess because in only takes scalars in python.

A: You are correct: Python operations are not vectorised by default. In this respect, R more closely parallels the API for 3rd party Pandas than regular Python. So you can use Pandas series objects:
import pandas as pd

x = pd.Series([1, 2, 3, 4])
y = pd.Series([2, 4, 6, 8])

res = x[x.isin(y)]

print(res)  # output Pandas series
# 1    2
# 3    4
# dtype: int64

print(res.values)  # output NumPy array representation
# array([2, 4], dtype=int64)

Pandas builds on NumPy, so not surprisingly you can do the equivalent in NumPy:
import numpy as np

x = np.array([1, 2, 3, 4])
y = np.array([2, 4, 6, 8])

res = x[np.isin(x, y)]

print(res)
# array([2, 4])

A: You can use set.
list(set(x).intersection(y))

A: You can create a MyList type that will have behaviour that you want, by defining custom getitem() methof
from collections import UserList, Iterable

class MyList(UserList):
    def __getitem__(self, item):
        if isinstance(item, Iterable):
            return MyList(x for x in self.data if x in item)
        return super(MyList, self).__getitem__(item)

if __name__ == '__main__':
    l = MyList([1, 2, 3, 4, 5])
    v = l[[2, 3, 11]]
    print(v)  # [2, 3]

A: This questions has been addressed here:
Filter dataframe rows if value in column is in a set list of values
Here's an example using the .isin() method, equivalent to R's %in%.
>> x = pd.Series([1,2,3,4,5])
>> y = pd.Series([1,3,5,6])

>> x[x.isin(y)]

0    1
2    3
4    5

A: If it helps, you can also write it as:
[i if i in x else None for i in y]

This puts the conditionals in front and the loop at the back, meaning you can do something like this:
[i if i in x else i/2 if i in z else i/3 for i in y]


text:
Q: Calculate percent of bytes read from compressed HTTP response stream In my desktop application I process HTTP response from the server and I want to provide a progress of processed bytes relatively to the total response length.
I know the content length from the HTTP header but the problem is that a compression (gzip) was applied for the response body. I can calculate the number of processed bytes but they are after decompression and that number is different from the content-length. The HTTP response's Stream is not seekable and to determine the progress I cannot use its Position property as I will have a NotSupportedException, similar to what MSDN declares for NetworkStream.Position property.
Below is the code that reads from the gzipped response
        HttpClient httpClient = new HttpClient();

        HttpResponseMessage response = httpClient.GetAsync(gzipGetUri, HttpCompletionOption.ResponseHeadersRead).Result;

        long? contentLength = response.Content.Headers.ContentLength;
        long totalCount = 0;
        int percentDone = 0;

        Stream responseStream = response.Content.ReadAsStreamAsync().Result;
        Stream gzipStream = new GZipStream(responseStream, CompressionMode.Decompress);

        byte[] buffer = new byte[1024];
        while (true)
        {
            int nBytes = gzipStream.Read(buffer, 0, buffer.Length);
            if (nBytes <= 0)
                break;

            // process decompressed bytes here...

            totalCount += nBytes;

            // This code throws NotSupportedException: This stream does not support seek operations
            percentDone = (int)(((double)responseStream.Position / contentLength) * 100);
        }

        Console.WriteLine($"content-length: {contentLength}; bytes read from gzipStream: {totalCount}");

The output to Console (when the line with calculation of percentDone is commented out) is

content-length: 1,316,578; bytes read from gzipStream: 9,410,402

My question is how I can determine the number of bytes that were consumed from a non-seekable response stream before they are transformed by decompression. Also I cannot use the count after decompression for percentDone calculation because I do not know the final number of decompressed bytes.
I guess that I can derive a class from Stream that counts passing through bytes, use it as a wrapper around responseStream and pass it as an inner stream to gzipStream but that solution seems too heavy.


text:
Q: Spark GraphX: how to insert just a node to a graph I know that in GraphX we can merge two graphs in order to update an existing network for example...
However, as a usual operation for updating a network is to insert into it a single node.
How could one do such an updating operation in GraphX ?!
Thanks !

A: Graphs are immutable, so you can't add a single node to an existing graph, but you can create a new graph based on the previous with the additional node added. Say you had a graph like this:
var graph: Graph[Int,Int] = ...

You could add a new node like this:
graph = Graph(
    graph.vertices.union(sc.parallelize(Array[(VertexId, Int)]((13L, 1)))),
    graph.edges,
    0
)


text:
Q: Acumatica and IHttpClientFactory Is it possible to use IHttpClientFactory with Acumatica?  Or can it only be built with mvc?  I've built an apiclient for REST calls in a processing screen and am injecting services in a startup.cs page but I get an error:
An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%
I added a reference to autofac.  Is there a configuration I need to add or register services a different way?

A: The error message indicates an attempt to run an asynchronous method within a synchronous method. This is not allowed in C#. You can try to run the asynchronous method in a synchronous task instead. Example:
HttpClient httpClient = [...];
Uri uri = [...]
Task<string> task = Task.Run(() => httpClient.GetStringAsync(uri));
task.Wait();

string httpResult = task.Result;


text:
Q: LazyLoadingEnabled false not working I am very confused, and I need help understanding lazy loading. I thought configuring lazy loading false would load an entire object including child elements, but that is not happening for me. Searching through other questions, I could not find an adequate answer.
A server contains a list of supervisors, and each supervisor contains a list of trunks.
using (var db = new ProjectDatabase())
{
        db.Configuration.LazyLoadingEnabled = false;

        var dbServer = db.Servers.Include("Supervisors.Trunks").Single(s => s.Name == ArchiveName);

        Console.WriteLine(dbServer.Supervisors.SelectMany(s=>s.Trunks).Count());
}

The above code writes 3 to the console line, which is expected because the server contains 3 supervisors and each supervisor contains 1 trunk.
using (var db = new ProjectDatabase())
{
        db.Configuration.LazyLoadingEnabled = false;

        var dbServer = db.Servers.Single(s => s.Name == ArchiveName);

        Console.WriteLine(dbServer.Supervisors.SelectMany(s=>s.Trunks).Count());
}

This code (same as first but without include statement) writes 0 to the console. I thought LazyLoadingEnabled = false would load all supervisors and trunks automatically. There are dozens of different types of child objects I need, so I'm hoping for an elegant solution that doesn't require tons of include statements. Please help.

A: You seem to confuse something.
LazyLoadingEnabled = false;

disables all lazy loading. What you need is
LazyLoadingEnabled = true;

It tells EF to load all required navigation properties that are used (the moment you call them), and have not been used before.


text:
Q: Door log report datediff SQL Server 2008 I'm currently trying to produce data for when employees swipe in and out of various doors in the building. The data is saved in a table like -

Ideally id like to do a datediff for the minutes but am struggling to get it to work! anyone have any thoughts as to the best way forward?

A: you can try this way,
select uid, serialno, datediff(m, max(time), min(time) ) from tablename
group by uid, serialno

A: Group on userId, serialNumber, max(time) and min(time) and then add a calculated column with the time difference.


text:
Q: jQuery Ajax object dot notation undefined from REST Hey guys I am having a really big problem understanding why my for each is unable to parse my REStful end point within my AJAX success function:
So I have the following code:
$.ajax({
  dataType: "json",
  url: '/showroom-event-gallery-api',
  success: function(data) {
    var rawData = data.slice(0,10);
    console.log(rawData);
    for (var i = 0, len = rawData.length; i < len; i++) {
      var imageName = rawData.name;
      console.log(imageName);
    }
  }
});

The console.log(rawData); statement runs successfully and shows the objects from my REST api. The issue that I am having is when I try and use dot notation to select a parameter called name within all of the objects and store them into a variable.
When I console.log(imageName); I get undefined however the name parameter is inside the object so I am unsure why this is happening?
Here is an example of my data:
[
    {
       id:225,
       car_image_category_id:37,
       image_name:"DSC_9672",
       name:"77a3b8f84d63557d165f3b4ecf0d079e5cd1ae67.jpg",
       path:"img/imagedb/77a3b8f84d63557d165f3b4ecf0d079e5cd1ae67.jpg",
       thumbnail_path:"img/imagedb/thumbs/tn-77a3b8f84d63557d165f3b4ecf0d079e5cd1ae67.jpg",
       created_at:"2016-07-27 18:13:50",
       updated_at:"2016-07-27 18:13:50"
    },
    {
       id:226,
       car_image_category_id:37,
       image_name:"DSC_9673",
       name:"af508985a53d7288d58cea118389a58b3567b364.jpg",
       path:"img/imagedb/af508985a53d7288d58cea118389a58b3567b364.jpg",
       thumbnail_path:"img/imagedb/thumbs/tn-af508985a53d7288d58cea118389a58b3567b364.jpg",
       created_at:"2016-07-27 18:13:50",
       updated_at:"2016-07-27 18:13:50"
    },
    {
       id:227,
       car_image_category_id:37,
       image_name:"DSC_9677",
       name:"85832b6a6d952873f2e277ca19b5eab826d63340.jpg",
       path:"img/imagedb/85832b6a6d952873f2e277ca19b5eab826d63340.jpg",
       thumbnail_path:"img/imagedb/thumbs/tn-85832b6a6d952873f2e277ca19b5eab826d63340.jpg",
       created_at:"2016-07-27 18:13:51",
       updated_at:"2016-07-27 18:13:51"
    }
 ]

As you can see name is available to be selected however when I use dot notation to do this my variable comes back as undefined.
Any idea why this might be happening?
Thanks

A: It should be rawData[i].name
   for (var i = 0, len = rawData.length; i < len; i++) {
      var imageName = rawData[i].name;
      console.log(imageName);
    }

A: try to Replace
var imageName = rawData.name;

with
var imageName = rawData[i].name;

You are now trying to get the name of an array and not the object

A: $.each() function is much easy to use with array try this.
$.each(rawData, function( index, value ) {
  console.log( index + ": " + value );
});