text:
Q: Folder icon in titlebar for iTerm2 macOS's default terminal shows the current directory as an icon in the titlebar (called a proxy icon). I can use it to navigate up, or drag the icon to another window to insert the path.
Is there a way to get this icon with iTerm2?
I tried to use various escape sequences, but the best I could to is to get the title set to the current path, but no icon.

A: Nevermind, found it myself. I updated to version 3.1.beta.5, and the option was under Preferences - Appearance - Window - Show proxy icon in window title bar.
You have to install the shell integrations, or manually send the required ANSI sequences. The default macOS bashrc only sends the sequences to set the icon when it detects Terminal.app.


text:
Q: Add background music at specific time period in mp3 files using ffmpeg I want to add background music after every 5 seconds in .mp3 file using ffmpeg.
I have 2 audio files : input1.mp3 of 5 seconds and input2.mp3 of 4 minutes 04 seconds. I want to add input1.mp3 after every 5 seconds in input2.mp3 like after 0,5,10,15,20,... seconds.
I am using :
ffmpeg -i input1.mp3 -i input2.mp3 -filter_complex amix=inputs=2:duration=first:dropout_transition=3 OUTPUT.mp3
The command is working properly. How can I repeat the input1.mp3 after every 5 seconds to input2.mp3 ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is Windows 10 or R itself deleting my temp directory? I saw the info on finding the name of my temp directory in this question.
The problem I'm having is that  my  Appdata/Local/temp/[Rtmpxxxx] directory is being deleted during an R session longer than 1 or 2 days.  I have turned off all automatic temp deletion actions that Windows 10  can take.  There's nothing in Rprofile.site or .Renviron related to temp directory or files.
Any ideas what I need to turn off or modify to keep the Rtmp directory from being deleted?

A: You could move your temp directory to another folder (outside the win10 temp folder)
e.g. with write("TMP = '<your-desired-tempdir>'", file=file.path(Sys.getenv('R_USER'), '.Renviron'))
If it is still being deleted, it is rather unlikely that Win10 deletes it.
edit by the OP
Depending on [something mysterious], the same command above should be used to create TEMP  and TMPDIR  as discussed here


text:
Q: Symfony2 form refresh same page after submit I have a form whose content is created from a DB.
in my controller i have:
/**
 * @Route("/HR/manage/{projectID}", name="hr_manage")
 */
public function manageHRAction(Request $request, $projectID)
{
//here I get all the data from DB and create the form
if ($form->isValid())
    {
    //here I do all the relevant changes in the DB
    return $this->render('HR/show.html.twig', array('hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
    }
return $this->render('HR/show.html.twig', array('hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
}

It updates the info on the DB properly, but it does not build again the form with updated data. Instead of the return inside the "isValid()" I simply need a refresh on the current page.
I assume it's possible and easy to accomplish, but I failed to find how to do it :/
EDIT - here comes more relevant code:
/**
 * @Route("/HR/manage/{projectID}", name="hr_manage")
 */
public function manageHRAction(Request $request, $projectID)
{
$user = $this->container->get('security.context')->getToken()->getUser(); //get current user
$em = $this->getDoctrine()->getManager(); //connect to DB
$prj = $this->getDoctrine()->getRepository('AppBundle:Project')->findOneById($projectID);
[...]
// here comes some code to generate the list of $HRsInThisProject and the list of roles ($rolesListForForm)
[...]
foreach ($HRsInThisProject as $key => $HR)
    {
    $form->add('roleOf_'.$key, 'choice', array('choices'   => $rolesListForForm, 'required'  => true, 'data' => $HR['role'], 'label' => false, ));
    $form->add('isActive_'.$key, 'choice', array('choices'   => [0 => 'Inactive', 1 => 'Active'] , 'required'  => true, 'data' => $HR['is_active'], 'label' => false, ));
    }
[...]
// here there is some code to get the $HRsInMyDomainForForm
[...]
$form->add('HRid', 'choice', array('choices' => $HRsInMyDomainForForm,'required' => false, 'placeholder' => 'Choose a resource', 'label' => false, ));
$form->add('role', 'choice', array('choices' => $rolesListForForm,'required' => false, 'placeholder' => 'Choose a role', 'label' => false, ));
$form->add('save', 'submit', array('label' => 'Save'));

$form->handleRequest($request);

if ($form->isValid())
    {
        {
        [...] here there is a huge portion of code that determines if I need to generate a new "event" to be stored, or even multiple events as I can change several form fields at once

        // If I needed to create the event I persist it (this is inside a foreach)
        $em->persist($newHREvent);
        }
    $em->flush();
    return $this->render('HR/show.html.twig', array('projectID' => $prj->getId(), 'hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
    }
return $this->render('HR/show.html.twig', array('projectID' => $prj->getId(), 'hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
}

I also include a screenshot of the form:

If a user selects to add a new resouce, I need to persist it to DB (and that is done properly) but then I need to see it in the list of available HRs, without the need for the user to reload the page.

A: I managed to solve it in a simple (and I hope correct) way.
I simply substituted the "render" inside the isValid() with the following:
return $this->redirect($this->generateUrl('hr_manage', array('projectID' => $prj->getId())));

I works, but does anybody foresee problems with this solution?

A: More dynamic way would be:
$request = $this->getRequest();

return $this->redirectToRoute($request->get('_route'), $request->query->all());

or simply
return $this->redirect($request->getUri());

A: You have to link the form to the request.
$entity = new Entity();
$form = $this->createFormBuilder($entity)
    ->add('field1', 'text')
    ->add('field2', 'date')
    ->add('save', 'submit', array('label' => 'Submit'))
    ->getForm();
$form->handleRequest($request); // <= this links the form to the request.

only after that you test $form->isValid() and pass this form when rendering the template. If you already did this and haven't included in the code above please show more code for better help.

A: Here is the right way to do it. Event though you have $projectId slug, in Action you can pass whole Object, in this case Project. Symfony will take care for the rest (fetching right Project entity for you.
/**
 * @Route("/HR/manage/{projectID}", name="hr_manage")
 */
public function manageHRAction(Request $request, Project $project)
{
    $form = $this->createForm(new ProjectType(), $project);
    $form->handleRequest($request);

    // ... your business logic or what ever

    //here I get all the data from DB and create the form
    if ($form->isValid() && $form->isSubmitted()) {
        $em->persist($project);
        // no need to flush since entity already exists
        // no need to redirect
    }

    // here $form->createView() will populate fields with data since you have passed Poroject $project to form
    return $this->render('HR/show.html.twig', array('hrlist' => $HRsInMyDomain, 'form' => $form->createView(), 'HRs' => $HRsInThisProject, 'project' => $prj, ));
}

Update
According to your edit, you need to use javascript for client-side dom manipulation. Check this link from Symfony official document embedded forms. Here you'll find an example of what you're trying to accomplish.


text:
Q: Animated Pulsating Dot I want to add an animated dot that has an oscillating type animation (this will actually be drawn on top of an image, if that makes any difference).
Here's a sample of what I mean:

Could this somehow be done with two images and an animation between them? I'm not too clear on that, so some sample code would be nice. (or a link to a tutorial).
Cheers and thanks in advance.

A: I'm not sure about Your exact requirements, but for me it looks like You need smth like extending 'ring' above the circle. I've tried to implement it using custom ViewGroup in order to have all that functionality encapsulated in some 'container'. Steps are below:
1) Add values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>

<resources>
    <declare-styleable name="OscillatorAnimatedView">
        <attr name="centerImage" format="reference" />
        <attr name="oscillatorImage" format="reference" />
        <attr name="oscillatorInterval" format="integer" />
        <attr name="oscillatorMaxExtend" format="float" />
    </declare-styleable>
</resources>

2) Add view to You layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:custom="http://schemas.android.com/apk/res/com.alexstarc.tests"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    <com.alexstarc.tests.views.OscillatorAnimatedView
            android:id="@+id/oscillator"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            custom:centerImage="@drawable/center"
            custom:oscillatorImage="@drawable/circle" />
</RelativeLayout>

3) Add images for center and circle to Your drawables (below is just random examples from the internet, note thayt it should be png with transparency):
 drawable/center
 drawable/circle
4) Create Your view (in my case it's com.alexstarc.tests.views.OscillatorAnimatedView):
    package com.ruinalst.performance.tests.views;

    import android.animation.AnimatorSet;
    import android.animation.ObjectAnimator;
    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.drawable.Drawable;
    import android.util.AttributeSet;
    import android.view.ViewGroup;
    import android.view.animation.BounceInterpolator;
    import android.widget.ImageView;
    import android.widget.RelativeLayout;
    import com.ruinalst.performance.tests.R;

    /**
     * Specific view to provide 'oscilllator' kind of animation using two input views
     */
    public final class OscillatorAnimatedView extends RelativeLayout {

        /* Internal constants, mostly for default values */
        /** default oscillator interval */
        private static final int DEFAULT_INTERVAL = 700;
        /** default oscillator extend */
        private  static final float DEFAULT_EXTEND = 1.5f;

        /** Image to be displayed at the center */
        private ImageView mCenterImage = null;
        /** Image to oscillate */
        private ImageView mOscillatorImage = null;
        /** Oscillator animation */
        private AnimatorSet mAnimatorSet = null;

        public OscillatorAnimatedView(final Context context, final AttributeSet attrs) {
            super(context, attrs);
            initAndCompose(attrs);
        }

        public OscillatorAnimatedView(final Context context, final AttributeSet attrs, final int defStyle) {
            super(context, attrs, defStyle);
            initAndCompose(attrs);
        }

        /**
         * Internal init function to init all additional data
         * and compose child for this ViewGroup
         *
         * @param attrs {@link AttributeSet} with data from xml attributes
         */
        private void initAndCompose(final AttributeSet attrs) {

            if (null == attrs) {
                throw new IllegalArgumentException("Attributes should be provided to this view," +
                        " at least centerImage and oscillatorImage should be specified");
            }

            final TypedArray a = getContext().obtainStyledAttributes(attrs,
                    R.styleable.OscillatorAnimatedView, 0, 0);
            final Drawable centerDrawable = a.getDrawable(R.styleable.OscillatorAnimatedView_centerImage);
            final Drawable oscillatorDrawable = a.getDrawable(R.styleable.OscillatorAnimatedView_oscillatorImage);

            if (null == centerDrawable || null == oscillatorDrawable) {
                throw new IllegalArgumentException("Attributes should be provided to this view," +
                        " at least centerImage and oscillatorImage should be specified");
            }

            final int oscillatorInterval = a.getInt(R.styleable.OscillatorAnimatedView_oscillatorInterval, DEFAULT_INTERVAL);
            final float maxOscillatorExtend = a.getFloat(R.styleable.OscillatorAnimatedView_oscillatorMaxExtend, DEFAULT_EXTEND);

            a.recycle();

            // Create child and add them into this view group
            mCenterImage = new ImageView(getContext());
            mCenterImage.setImageDrawable(centerDrawable);
            addInternalChild(mCenterImage);

            mOscillatorImage = new ImageView(getContext());
            mOscillatorImage.setImageDrawable(oscillatorDrawable);
            addInternalChild(mOscillatorImage);

            // Init animation
            mAnimatorSet = new AnimatorSet();

            mAnimatorSet.setDuration(oscillatorInterval);

            final ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(mOscillatorImage, "ScaleX", 1.0f, maxOscillatorExtend);

            scaleXAnimator.setRepeatCount(ObjectAnimator.INFINITE);
            scaleXAnimator.setRepeatMode(ObjectAnimator.INFINITE);

            final ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(mOscillatorImage, "ScaleY", 1.0f, maxOscillatorExtend);

            scaleYAnimator.setRepeatCount(ObjectAnimator.INFINITE);
            scaleYAnimator.setRepeatMode(ObjectAnimator.INFINITE);

            mAnimatorSet.playTogether(scaleXAnimator, scaleYAnimator);
            mAnimatorSet.setInterpolator(new BounceInterpolator());
        }

        /**
         * Internal helper to add child view to this ViewGroup.
         * Used currently only for two internal ImageViews
         *
         * @param child {@link ImageView} to be added
         */
        private void addInternalChild(final ImageView child) {
            final LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);

            params.addRule(CENTER_IN_PARENT, 1);
            addView(child, params);
        }

        /**
         * Starts animation for this view
         */
        public void start() {
            mAnimatorSet.start();
        }

        /**
         * Stops animation for this view
         */
        public void stop() {
            mAnimatorSet.end();
        }
    }

5) In Your activity do smth like:
        @Override
        protected void onResume() {
            super.onResume();

            mOscillatorView.start();
        }

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

            mOscillatorView.stop();
        }

Please note, that it's not release version and it most probably can be improved in many ways.
You can also play with interpolators or create Your own in order to have expected animation.

A: Are you looking for a Drawable Animation? Seems like that would do what you're looking for. You can use a RelativeLayout to position it on top of your other views.
Also, if you need more complex animation, you could use a SurfaceView and paint the canvas to your linking.

A: Override the onDraw method and draw a first circle for your button, also, create a boolean variable to control when your button is going to pulse and when is not.Finally draw your second circle with an alpha as a background. Making a pulsating effect:
 @Override
protected void onDraw(Canvas canvas) {

    int w = getMeasuredWidth();
    int h = getMeasuredHeight();
    //Draw circle
    canvas.drawCircle(w/2, h/2, MIN_RADIUS_VALUE , mCirclePaint);
    if (mAnimationOn) {
        if (mRadius >= MAX_RADIUS_VALUE)
            mPaintGoBack = true;
        else if(mRadius <= MIN_RADIUS_VALUE)
            mPaintGoBack = false;
        //Draw pulsating shadow
        canvas.drawCircle(w / 2, h / 2, mRadius, mBackgroundPaint);
        mRadius = mPaintGoBack ? (mRadius - 0.5f) : (mRadius + 0.5f);
        invalidate();
    }

    super.onDraw(canvas);
}
 public void animateButton(boolean animate){
    if (!animate)
        mRadius = MIN_RADIUS_VALUE;
    mAnimationOn = animate;
    invalidate();
}


text:
Q: Unable to print a passed array in PHP I have 3 files:
DB.class.php - which handles all the databases.
Site.class.php - contains a function to return the latest entries in a database.
index.php - trying to print the array passed.
I am trying to pass an array into index.php from Site.class.php which is using a function from DB.class.php to put the mysql results into an associative array.
index.php:
<?php

// index.php

include 'classes/Site.class.php';
$site = new Site();

print_r($site->latestBookmarks());

?>

Site.class.php:
<?php

// Site.class.php

require_once 'DB.class.php';

class Site {

    function latestBookmarks() {

        $result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");

        $db = new DB();

        return $db->processRowSet($result);

    }

}

?>

DB.class.php:
<?php

// DB.class.php

class DB {

    protected $db_name = "project";
    protected $db_user = "root";
    protected $db_pass = "root";
    protected $db_host = "localhost";

    // Open up a connection to the database.

    public function connect() {

        $connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
        mysql_select_db($this->db_name);

        return true;

    }

    // Takes a MySQL row and returns an associative array where the keys in the array are the column names in the row set.

    public function processRowSet($rowSet, $singleRow=false) {

        $resultArray = array();

        while ($row = mysql_fetch_assoc($rowSet)) {
            array_push($resultArray, $row);
        }

        if ($singleRow === true)
            return $resultArray[0];

        return $resultArray;

    }

    // Select rows from the database.

    public function select($table, $where) {

        $sql = "SELECT * FROM $table WHERE $where";

        $result = mysql_query($sql);

        if (mysql_num_rows($result) == 1)
            return $this->processRowSet($result, true);

        return $this->processRowSet($result);

    }

    // Update a current row in the database.

    public function update($data, $table, $where) {

        foreach ($data as $column => $value) {
            $sql = "UPDATE $table SET $column = $value WHERE $where";
            mysql_query($sql) or die(mysql_error());
        }

        return true;

    }

    // Insert a new row into the database.

    public function insert($data, $table) {

        $columns = "";
        $values = "";

        foreach ($data as $column => $value) {
            $columns .= ($columns == "") ? "" : ", ";
            $columns .= $column;
            $values .= ($values == "") ? "" : ", ";
            $values .= $value;
        }

        $sql = "INSERT INTO $table ($columns) VALUES ($values)";

        mysql_query($sql) or die(mysql_error());

        return mysql_insert_id();

    }

}

?>

A: A few problems I noticed:

*

*You run a query in function latestBookmarks before you connect to the db;

*In your function connect you connect to a database, but the result is discarded immediately, $connection is lost as soon as the function finishes.

A: You have no connection to the database when you run this line:
 $result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");

You will need to adjust your code to send the query string to the DB instance for processing. You can add a method to DB to execute mysql_query, and pass the query in like from Site:: latestBookmarks() like this:
 $db = new DB();
 $db->executeQuery("SELECT url, title FROM site ORDER BY id DESC");
 return $db->processRowSet();


text:
Q: Usage of restrict on two pointers pointing to same array I'm having quite hard time making proper usage of restrict keyword in C. I wrote this function to in-place reverse a string:
void my_strrev(char *restrict str, const size_t len) {
    char *restrict strr = str + len - 1;
    char temp;
    while (str < strr) {
        temp = *str;
        *str++ = *strr;
        *strr-- = temp;
    }
}

Here, although both str and strr are pointing to same array, I'm using those pointers to access individual characters, and they never point to same characters. Hence I think this is a proper use of restrict. Also I got expected output when I run this program with few sample inputs. But I'm unsure of my usage of restrict. So, please correct me if I'm doing wrong.

A: restrict has pretty much one single use - a contract that the programmer signs up with the compiler saying "I promise that I won't pass parameters pointing at the same data to this function with external linkage." This is still to this day mostly based on the compiler trusting the programmer, rather than the compiler giving diagnostic messages when the programmer "breaks the contract".
If the compiler can assume that the programmer kept their side of the bargain, it can make optimizations:

*

*It can assume that buffers passed to a function won't overlap - no need for temporary storage. (See memcpy vs memmove for example.)

*It can assume that different pointer parameters aren't aliases of each other, pointing to the same data. (Which could be possible if you have for example a char* and an int* parameter.)

*It can assume that pointer parameters aren't modifying any external linkage resources ("globals") used by the function, but that all access to what the pointer points at happens through that pointer.

Using restrict for a local pointer variable isn't very meaningful since it doesn't relate to any of the above situations. It will compile but there will be no benefits of using it. As far as I know, no additional diagnostics is currently provided by any of the mainstream compilers, should you use a restrict pointer inappropriately.

A: restrict essentially says that all the memory the function accesses through that pointer will not be accessed any other way, i.e., not also through another parameter or pointers loaded in any other way or via external objects.
It is okay to assign the parameter to other variables and to use those variables to access memory. Those accesses still derive from the original pointer. They are not derived from a different parameter or other source.


text:
Q: MySQL MATCH AGAINST using wildcards returns unexpected results with apostraphe I am doing a full text search as a user types and have come across an instance that does not behave as I expected.
I have the following pieces of data in a single column with a full text index:

*

*Adrienna O'ROURKE   O'ROURKE Adrienna   F 1949-04-09 Miss  Single     6908

*Olivia O'Toole   O'Toole Olivia   F 1989-06-30 Miss  Single  4362

*Owen O'Leary   O'Leary Owen   M 1979-01-12 Mr.  Single  4533
The query below fails to match  "O'Rourke", but matches rows with "O'Toole" and "O'Leary":
SELECT distinct o.*
FROM pcObjects o
WHERE  MATCH(ObjectSearchData) AGAINST('*O\'*' IN BOOLEAN MODE)
ORDER BY MATCH(ObjectSearchData) AGAINST('*O\'*' IN BOOLEAN MODE) DESC

This query matches the entry with "O'Rourke":
SELECT distinct o.*
FROM pcObjects o
WHERE  MATCH(ObjectSearchData) AGAINST('*O\'Rou*' IN BOOLEAN MODE)
ORDER BY MATCH(ObjectSearchData) AGAINST('*O\'Rou*' IN BOOLEAN MODE) DESC

Can anyone explain why "O'Rourke" isn't being found in the first instance, but "O'Toole" is?  Thanks.

A: As I know BOOLEAN mode return 1 or 0 there is no float relevance values so you just need:
SELECT distinct o.*
FROM pcObjects o
WHERE  MATCH(ObjectSearchData) AGAINST('O\'' IN BOOLEAN MODE)

this  line:
ORDER BY MATCH(ObjectSearchData) AGAINST('*O\'*' IN BOOLEAN MODE) DESC

has no sense in BOOLEAN mode all rows has MATCH = 1


text:
Q: How to construct a LTI system with a specific impulse response function, say \$h(t) = \delta '(t)\$? I want to ask the question on a generic basis, but using \$h(t) = \delta '(t)\$ as my example.
I have Mathematical knowledge on the LTI system, but no hands on experience. In real life, how can we construct a LTI system with specific impulse response function? Say for \$h(t) = \delta '(t)\$, I know it is a differentiator, so I would search for "differentiator" (e.g. this one) regarding how to construct it.
How about the other form of \$h(t)\$? Is there a generic way to construct LTI system for a specific family of \$h(t)\$ (say the family of linear combination of \$sinc(t)\$, \$\delta (t)\$, \$\delta '(t)\$ and other common functions)? Or I need to construct it in an adhoc way for every different \$h(t)\$?
Many thanks!

A: First, you can construct possible systems.  That means that getting an impulse response of \$h\left(t\right) = \delta'\left(t\right)\$ is right out, because it's non-causal.  For that matter, a system that truly has impulse response \$h\left(t\right) = \delta\left(t\right)\$ is also out, because anything real responds in a finite amount of time.
In general, if you can start with your desired \$h(t)\$ and break it into a weighted sum of impulse responses that you know how to realize in circuitry, then you can generally move forward.  Things of the form \$h(t) = t^n e^{at}\$ are particularly easy, because (as long as you allow \$a\$ to be complex) that's the form that can be realized by an appropriate lumped-element circuit.
You can, in theory, implement approximations of arbitrary \$h(t)\$ by making tapped delay lines and summing their outputs -- but that's kind of an expensive wacky old radar technology, not something that's of much use today (unless it's in really expensive, fast radars).
In practice, though, you rarely start with an impulse response and design a system to it.  The only time I can think of where that's really necessary is in communications systems, and these days that's generally done by converting the signal to digital and doing all of the heavy lifting with DSP.


text:
Q: In WPF how do I specify the path to a file nested in a Directory using XAML? I am trying to do this...
<Image x:Name="imgGroupImage" Source="Images\unlock.png" Margin="0,0,5,0" />

But I get this error...

Cannot convert string 'Images\unlock.png' in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. Cannot locate resource 'forms/images/unlock.png'.  Error at object 'System.Windows.HierarchicalDataTemplate' in markup file 'Fuse;component/forms/mainwindow.xaml' Line 273 Position 51.

As you can see, my form that includes this XAML is in a folder named Forms. My Images are in a folder named Images. How do I map from Forms to Images?
I tried Source="..Images\unlock.png" which does not work in WPF.
Any help?

A: Try slashes rather than backslashes, and use an absolute path by leading with a slash:
Source="/Images/unlock.png"

That generally works for me.
Failing that, take a look at Pack URIs.

A: *

*Add your image to the Project in VS

*Right click on that image unlock.png

*Go to Context menu /Properties

*Change Build Action to Resource

Thats it :-)

A: Have you tried setting the source to a BitmapImage?
<Image x:Name="imgGroupImage" Margin="0,0,5,0"  >
   <Image.Source>
      <BitmapImage UriSource="Images/unlock.png" />
   </Image.Source>
</Image>

I believe the default type of Uri for UriSource is a relative Uri, which works off the application's base class.  You might find you can configure the BitmapSource a bit easier than trying to find the exact way you have to enter the file path in the Source attribute.

A: In order to use resource located in folder different that the one where your XAML is, do this:
<Image Source="pack://application:,,,/Resources/image.png"/>

Where Resources is name of directory which you want to use resources from and image.png is name of image to display. Answer found thanks to @matt-hamilton and @brian-hinchey and their mention of Pack URI.
Works perfectly with your own Converters. You just have to return string matching schema above.


text:
Q: DB2 Exception - There are no context policies I am trying to connect to a Windows based DB2 server using the 11.5 ADO.NET connector. This works fine (it's some unit tests) on all systems except my home computer.
On my home computer I get the following exception:
{"ERROR [58005] [IBM][DB2.NET] SQL0902 An unexpected exception has occurred in  Process: 69336 Thread 11 AppDomain: Name:Tests: TestKailua
There are no context policies.
Function: AESEncryptADONET (Encryption Info)
allStack:    at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at IBM.Data.DB2.DB2ConnPool.HandleUnknownErrors(String strFncMsg, Exception exception, Boolean bThrow)\r\n   at IBM.Data.DB2.DB2ConnPool.EncryptString(String value)
at IBM.Data.DB2.DB2ConnPool.ReplaceConnectionStringParms(DB2Connection connection, String szValue, DB2ConnSettings& pSettings, DB2ConnSettingsInternal& pSettingsInternal, Boolean bAttach, Boolean pushDownStrAppended)
at IBM.Data.DB2.DB2Connection.set_ConnectionString(String value)

And the inner exception is:
AESEncryptADONET - Encryption - no error information available
at IBM.Data.DB2.DB2ConnPool.EncryptString(String value)

What do I not have configured?


text:
Q: Different login views for different flask blueprints I have a flask web application and it has multiple blueprints:

*

*restserver

*webserver

Most of the endpoints in both webserver and restserver require the user to be logged-in. I use flask-login extension, which provides @login_required decorator.
Is it possible to have different login_view for different blueprints?
# for web blueprint
login_mananger.login_view = '/web/login'

 .. so on

A: One of the most important specialities of RESTful is statelessness, it means the server won't "remember" any information from clients, the requests from clients should have contained all the needed informations, including auth informations.
Back to your question, you don't have to use Flask-Login for RESTful service authentication, and you should not use cookies or sessions because of the diversity of the clients. You can DIY the HTTP authentication of course, but Flask-HTTPAuth is what you really need.
Here is a simplest example of Flask-HTTPAuth:
from flask.ext.httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()

@auth.verify_password
def verify_password(username, password):
    user = User.query.filter_by(username=username).first()
    if not user:
        return False
    g.current_user = user
    # You should accomplish the verify_password function by yourself in the User model.
    return user.verify_password(password)

According to the doc of Flask-HTTPAuth:

The callback function takes two arguments, the username and the
  password and must return True or False.

You should notice that the initialization of the Flask-HTTPAuth just in the blueprint rather than the whole application since this authentication just used in your restserver blueprint.
Then there is a function just like Flask-login's @login_required which provided by Flask-HTTPAuth:
@app.route('/private')
@auth.login_required
def private_page():
    return "Only for authorized people!"

This "login_required" callback function will be called when authentication is succesful. Since all of your restserver's route should be protected, you can use a "before_request" handler for applying the protection to the whole blueprint. Assuming that your restserver blueprint's name is "rest" and you have saved the user object in "g" just like what we do before:
from flask import jsonify

@rest.before_request
@auth.login_required
def before_request():
    if not g.current_user:
        return jsonify({'error':'Unauthorized.'})

I think this will do the trick. What I wrote above is just the simplest example and you can do much better in many ways, such as replacing the user credentials with token after first request. I believe that you will figure it out.
If my answer is helpful, it will be my great honour if you can "upvote" for this answer, thanks.

A: In your case, you need to place the login manager declaration in the same file as the flask app instance. This is commonly an __init__.py file with the app = Flask(__name__).
At the top, import LoginManager class
from flask_login import LoginManager

Then tie it to the app instance.
login_manager = LoginManager()
login_manager.init_app(app)

(This was not asked but just incase someone needs it) Lets say you have admins and normal users and you are authenticating from different tables:
@login_manager.user_loader
def load_user(user_id):
    x = Users.query.get(str(user_id))
    if x == None:
        x = Admins.query.get(str(user_id))
    return x

Finally after importing blueprints you can define the login views for each in a dictionary
login_manager.blueprint_login_views = {
    'admin': '/admin/login',
    'site': '/login',
}


text:
Q: jboss EAP v/s Widfly differences I am curious to know that are there any functional differences in Redhat Jboss EAP and community Wildfly. Is there something extra in EAP which is not available in Jboss wildfly.
I am using OpenShift origin with openshift wildfly centos based image. So thought of getting to know this in detail because origin doesnt provide EAP image.

A: WildFly is the community stream for JBoss EAP 7. Have a look at http://wildfly.org/governance/.


text:
Q: Laravel Send mail in side proxy network I am just implementing like password reset system.
The Sending Mail system is working in home without the proxy setup.
But inside the proxy setup system is not working(both are in localhost).
when i upload to the server its working.
Then why in the localhost under the proxy setup network system is not working???
It shows the Error

Expected response code 220 but got code "421", with message "421
  Cannot connect to SMTP server 74.125.200.109 (74.125.200.109:587),
  connect error 10060 "

This is my .env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=test@gmail.com
MAIL_PASSWORD=*********
MAIL_ENCRYPTION=tls

my config/mail.php
return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
    'port' => env('MAIL_PORT', 587),
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'MYNAME'),
    ],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'markdown' => [
        'theme' => 'default',
        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],
];

Since i am new to laravel ,
Is there any setting need to do OR Should i want to configure the proxy name and port number(how to configure the proxy setup in laravel) ...
please help me .. thank you in advance

A: When you want use your gmail account in another apps, You should enable Let less secure apps option
Also you can define another key for your account ( different that you account password ). You should have a key like this when you are using 2FA
Don't forget to run php artisan config:cache after any changes in .env file


text:
Q: Python /Tix : Fill a ComboBox list when another ComboBox is set I'm working on a project for school, and I just can't seem to solve my problem:
The application I wrote manages a .csv file containing informations about patients in a hospital, and their date of birth is set by three distinct ComboBoxes (Y/M/D). I want to display the right number of days for each month in the day-ComboBox (ie 31 in january, 28 or 29 in february...).
So, this is (a stripped-down version of) my code :
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from datetime import *
from Tkinter import *
import Tix

#useful variables
today=datetime.date(datetime.today())
listYears = []
for i in range(1900, today.year+1):
    listYears.append(i)
listMonths = []
for i in range(1, 13):
    listMonths.append(i)
#functions
def dispDay():
    birthDay=Tix.ComboBox(frame4, variable=dayVar, selectmode='immediate', listcmd = calculateDay(int(birthYear['value']), int(birthMonth['value'])))
    birthDay.entry.config(state='readonly')
    birthDay.place(anchor='c',x=(w/8-10), y=445)
    for item in listDays :
        birthDay.insert(END, item)

def calculateDay (year, month):
    if year%400 == 0 :
        if month%2 == 0 :
            if month == 2 :
                days=29
            else :
                days=30
        else:
            days=31
    elif (year%4 == 0 and year%100!=0):
        if month%2 == 0 :
            if month == 2 :
                days=29
            else:
                days=30
        else:
            days=31
    else:
        if month%2 == 0:
            if month == 2 :
                days=28
            else:
                days=30
        else:
            days=31

    global listDays
    listDays= []
    for i in range(1, days-1):
        listDays.append(i)

def quitButton():
    qButton=Button(text="Quit",command=window.quit)
    qButton.place(relx=0.5, rely=0.5, anchor=CENTER)

def createPatientMenu():
    yearVar=IntVar()
    monthVar=IntVar()
    dayVar=IntVar()

    global frame4
    frame4=Frame(window,width=w,bg="grey14", height=h)
    frame4.pack()

    lbYear=Label(frame4, text="Year:")
    lbYear.pack()
    birthYear=Tix.ComboBox(frame4, variable=yearVar)
    birthYear.entry.config(state='readonly')
    birthYear.pack()
    for item in listYears :
        birthYear.insert(END, item)

    lbMonth=Label(frame4, text="month:")
    lbMonth.pack()
    birthMonth=Tix.ComboBox(frame4, variable=monthVar, selectmode='immediate', command=dispDay)
    birthMonth.entry.config(state='readonly')
    birthMonth.pack()
    for item in listMonths :
        birthMonth.insert(END, item)

    quitButton()

#main
window=Tix.Tk()
w, h = 800, 600
window.geometry("%dx%d+0+0" % (w, h))
window.config(bg='grey14')
window.title("database")
createPatientMenu()
window.mainloop()

My problem is that int(birthYear['value']) and int(birthMonth['value']) both return 0 (already tested it by adding a print at the start of calculateDays()), even when something is selected in the month and year ComboBoxes. I don't understand why.
Also, python gives an error when selecting a month :

Exception in Tkinter callback
  Traceback (most recent call last):
  File "D:\Python27\lib\lib-tk\Tkinter.py", line 1541, in __call__
return self.func(*args)
  TypeError: dispDay() takes no arguments (1 given)
  Exception in Tkinter callback
  Traceback (most recent call last):
  File "D:\Python27\lib\lib-tk\Tkinter.py", line 1541, in __call__
return self.func(*args)
  TypeError: dispDay() takes no arguments (1 given)

Am I missing something?
Any help would be really appreciated, as I have to give back my assignement in a few weeks and still have plenty work to do. Thank you in advance!


text:
Q: Task Scheduler doesn't start my exe for the next day I have an application made in Visual Studio 2013 and I use Task Scheduler to run .exe version. Task is set to work every day whether user is logged on or not. Created Task Scheduler will work on the day when is created but when I turn off PC and tomorrow turn on PC in Task Scheduler for my task there is nothing in 'Next Run Time' and task doesn't running my application. If I open task and just confirmed OK it will start again to work.

A: Have a look at this topic : Run interactive task even if user is not logged on Windows
This methods automatically logs in, runs the task, and locks the machine right after.
Else, if you are simply looking to run the application on boot after logging on, why not place it in Window's startup folder?
C:\Users\YOUR-USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Start-up

Create a shortcut of your exe and drop it in the above directory - the .exe will run once Window boots up.


text:
Q: Is it possible to get (set) multiple text attributes in a single spreadsheet cell programmatically? Since the introduction of the new spreadsheet version one can change text attributes inside a single cell (or merged cells) manually like in this example :
(left = raw text, right = formatted text, easier to read)

I don't see any way to achieve that by script... I don't see any issue nor feature request in the issue tracker either.
Is that possible ?
Every method I try to get the text attributes only returns a single value so I'm afraid I just can't do it... but who knows ?

A: On 2016, when this answer was originally posted, in Google Sheets was not possible to programatically apply formatting to cell content parts.
Please star the The following feature request on the Google Apps Scripts issues and feature requests official site is now fixed.
Issue 6000:    Handle parts of cell content programmatically
According to the release notes of January 22, 2019 Google Apps Script was updated to include new classes and methods to handle cell content formatting like RichTextValue.


text:
Q: lwip udp programming on vlan Am trying to send message on one of the ethernet ports on my system (I have set up VLAN on it with an IP Addr).
I want to use lwip to send data to this vlan port.
Here's what I have done
#define VLAN_IP "192.16.0.0" //  ip addr of my ethernet vlan port
#define PORT 51 // dest port

ip_addr_t vlan_ip_addr;
vlan_ip_addr.addr = inet_addr(VLAN_IP);

struct udp_pcb *udp_pcb = udp_new();
if(udp_pcb == NULL)
    return -1;

ip_set_option(udp_pcb, SOF_BROADCAST);

err_t wr_err = udp_bind(udp_pcb, IP_ADDR_ANY, 80);
if(wr_err != ERR_OK)
    return -1;

wr_err = udp_connect(udp_pcb, &vlan_ip_addr, PORT);
if(wr_err != ERR_OK)
    return -1;

char buffer[] = "hello";
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, sizeof(buffer), PBUF_RAM);
memcpy(p->payload, &buffer, sizeof(buffer));
p->len = sizeof(buffer);
 if(udp_send(udp_pcb, p) != ERR_OK) {
    return -1;
  }

pbuf_free(p);

But the code returns ERR_RTE:Could not find route to destination address from udp_send().


text:
Q: Timeout expired in windows phone 7 application development I am building an app for windows phone 7 application using c#.net. I was able to extract data from web service but suddenly i started getting an exception while calling web service.
The exception message is:

Server was unable to process request. ---> error connecting: Timeout expired.
  The timeout period elapsed prior to obtaining a connection from the pool.
  This may have occurred because all pooled connections were in use and max pool size was reached.

Can anyone tell me if this is an error caused because of coding or something else.
How can I fix this?

A: This error message is received when:

*

*So many people are connected to the web services that are not enough "free" connections.

*A SQL command is taking longer than the timeout of the SQL/Web Server.

*Your previous connections are not being properly disposed.

You can try:

*

*Increase the number of IIS connections available to the web service. Website.

*Increase the number of SQL connections available to the DB connection. Website.

*Write your SQL Commands better so they do not hit the timeout window.

*Properly call SqlConnection.Dispose when you are finished with each connection.


text:
Q: What do the "features enabled" in GNU find mean? When I use find --version with GNU find, I get something like this:
find (GNU findutils) 4.5.9
[license text]
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS(FTS_CWDFD) CBO(level=2)

What do these "features" mean? There's some reference to O_NOFOLLOW being a security measure in man find, and there's a mention of LEAF_OPTIMISATION being an optimization that saves a few lstat calls on leaf nodes. But I can't find anything about FTS, D_TYPE or CBO.

A: This is a complete answer derived from the answers of Ketan and daniel kullman, as well as my own research.
Most of the "features" turn out to be query optimizations, since find is in general capable of (almost) arbitrarily complex queries on the filesystem.

D_TYPE
The presence of the D_TYPE feature means that find was compiled with support for the d_type field in struct dirent. This field is a BSD extension also adopted by Linux, which provides the file type (directory, file, pipe, socket, char/block device, etc.) in the structure returned from readdir and friends. As an optimization, find can use this to reduce or eliminate lstat calls when -type is used as a filter expression.
readdir may not always populate d_type on some filesystems, so sometimes an lstat will still be needed.
More info from the official documentation: https://www.gnu.org/software/findutils/manual/html_node/find_html/d_005ftype-Optimisation.html
O_NOFOLLOW
This option will read either (enabled) or (disabled). If present and enabled, this feature implements a security measure that protects find from certain TOCTTOU race attacks. Specifically, it prevents find from traversing a symlink while performing directory traversal, which could occur if the directory were replaced by a symlink after the directory's filetype was checked but before the directory was entered.
With this option enabled, find will use open(..., O_NOFOLLOW) on the directory to open only real directories, then use openat to open files within that directory.
LEAF_OPTIMISATION
This slightly obscure optimization allows find to deduce which subdirectories of a parent directory are directories by using the link count of the parent directory, since subdirectories will contribute to the link count of the parent (via the .. link). In certain circumstances, it will allow find to elide a stat call. However, if the filesystem or OS misrepresents st_nlinks, it may cause find to produce bogus results (this is thankfully a very rare occurrence).
More info in the official documentation: https://www.gnu.org/software/findutils/manual/html_node/find_html/Leaf-Optimisation.html
FTS
When enabled, the FTS feature causes find to use the fts API to traverse the file hierarchy, instead of a straight recursive implementation.
It's not clear to me what the advantage of fts is, but FTS is basically the default on all default find versions I've seen so far.
More info: https://www.gnu.org/software/findutils/manual/html_node/find_html/fts.html, http://man7.org/linux/man-pages/man3/fts.3.html
CBO
It turns out (after reading the find source code as suggested by daniel kullman) that "CBO" refers to the query optimization level (it stands for "cost-based optimizer"). For example, if I do find -O9001 --version, I get
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS() CBO(level=9001)

Looking at the -O option in man find, I see

-Olevel
  Enables query optimisation.   The find program reorders tests to speed up execution  while  preserving  the  overall
  effect; that is, predicates with side effects are not reordered relative to each other.  The optimisations performed
  at each optimisation level are as follows.

  0      Equivalent to optimisation level 1.

  1      This is the default optimisation level  and  corresponds  to  the  traditional  behaviour.   Expressions  are
         reordered  so that tests based only on the names of files (for example -name and -regex) are performed first.

  2      Any -type or -xtype tests are performed after any tests based only on the names  of  files,  but  before  any
         tests  that  require information from the inode.  On many modern versions of Unix, file types are returned by
         readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first.

  3      At this optimisation level, the full cost-based query optimiser is enabled.  The order of tests  is  modified
         so  that  cheap  (i.e. fast) tests are performed first and more expensive ones are performed later, if neces-
         sary.  Within each cost band, predicates are evaluated earlier or later according to whether they are  likely
         to  succeed or not.  For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predi-
         cates which are likely to fail are evaluated earlier.

  The cost-based optimiser has a fixed idea of how likely any given test is to succeed.  In some cases the probability
  takes  account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than
  -type c).  The cost-based optimiser is currently being evaluated.   If it does not actually improve the  performance
  of find, it will be removed again.  Conversely, optimisations that prove to be reliable, robust and effective may be
  enabled at lower optimisation levels over time.  However, the default behaviour (i.e. optimisation level 1) will not
  be  changed  in  the 4.3.x release series.  The findutils test suite runs all the tests on find at each optimisation
  level and ensures that the result is the same.

Mystery solved! It's a little strange that the option is a runtime value; usually I would expect the --version output only to reflect compile-time options.

A: Information about O_NOFOLLOW is given in the info page of find:

9.2.1.1 O_NOFOLLOW
..................
If your system supports the O_NOFOLLOW flag (1) to the open(2)' system
  call,find' uses it when safely changing directory.  The target
  directory is first opened and then find' changes working directory
  with thefchdir()' system call.  This ensures that symbolic links are
  not followed, preventing the sort of race condition attack in which use
  is made of symbolic links.
...

From the source tree, CBO occurs only in the file parser.c:
 printf("CBO(level=%d) ", (int)(options.optimisation_level));

indicating it to be cost based optimization (my best guess).
D_TYPE occurs at several places in the source-tree and seems like has to do with the directory entry type:
$ grep 'D_TYPE' */**

Yields:
find/parser.c:#if defined USE_STRUCT_DIRENT_D_TYPE && defined HAVE_STRUCT_DIRENT_D_TYPE
lib/savedirinfo.c:#if defined HAVE_STRUCT_DIRENT_D_TYPE && defined USE_STRUCT_DIRENT_D_TYPE

and some more entries. You can find the source here.

A: When looking through the findutils source tree (http://git.savannah.gnu.org/cgit/findutils.git/tree/), I found the following:

*

*configure.ac: --enable-d_type-optimization,Make use of the file type data returned in struct dirent.d_type by readdir()),

*m4/withfts.m4: --without-fts Use an older mechanism for searching the filesystem, instead of using fts()

I didn't find anything about CBO; you might have to download the source code and search for the term..


text:
Q: How to create group and assign privileges to Group in Dynamics CRM? I am implementing a Sales process where it includes 3 set of users. Set 1 consists of Sales Analyst, Set 2 consists of Sales managers, and Set 3 consists of Sales Directors.
In my sales Process, I am using 3 different Process flows against an opportunity. If users under Set 1 logs in they only need to see views and Process assigned to Set 1 users and same in the case for other Set users (Set 2, Set 3).
Is it possible to create a group/profile and assign users to it, so that in future if I create any view or process I only need to assign that process/Views to a particular Set (Set1, Set 2, Set 3)?
Is it possible to achieve through Dynamics?

A: 2 different things.
Business process flow: To show only BPF1 to Set1 (sales analysts), create a security role (or use existing sales analyst role which might have assigned to only Set1 users), map this role to BPF1 using "Enable Security Role" option

Catch: so far created records with BPF1 will still show it for Set2 users.
Views: To show PublicView1 only to Set1, there's no easy way to regulate it using Team or Security roles. But you can create Personal view & share with Set1 users or a Set1Team (add all Set1 users to this team)


text:
Q: Sum to closed form? Is there a general method for removing a sum from an expression to produce a closed form?
For example I needed to "unroll" the following expression in a recent programming competition (as $k_1$ and $k_2$ are large) and couldn't do it...
$$ \sum_{w=2}^{k_1}\sum_{h=2}^{k_2}(w-1)(h-1) $$
Do I miss some discrete math training?  By what method would you go about solving this?  Is there a common textbook that would cover this?

A: The inner sum is
$$\sum_{h=2}^{k_2}(h-1) = 1 + 2 + \cdots + (k_2-1)$$
which has the well-known total
$$\sum_{h=2}^{k_2}(h-1) = 1+2+\cdots+(k_2-1) = \frac{(k_2-1)k_2}{2}.$$
Similarly for
$$\sum_{w=2}^{k_1}(w-1).$$
Now "undistribute" the constant terms using the fact that if $a$ does not depend on $j$, then
$$\sum_{i=r}^s af(i) = a\sum_{i=r}^2f(i)$$
so
$$\begin{align*}
\sum_{w=2}^{k_1}\sum_{h=2}^{k_2}(w-1)(h-1) &= \sum_{w=2}^{k_1}\left( (w-1)\sum_{h=2}^{k_2}(h-1)\right)\\
&= \sum_{w=2}^{k_1}(w-1)\left(\frac{(k_2-1)k_2}{2}\right)\\
&= \frac{(k_2-1)k_2}{2}\sum_{w=2}^{k_1}(w-1)\\
&= \frac{(k_2-1)k_2}{2}\left(\frac{(k_1-1)k_1}{2}\right)\\
&= \frac{k_1k_2(k_1-1)(k_2-1)}{4}.
\end{align*}$$

A: To answer the question you asked, there is not in general a method for converting a summation to closed form.
However, the book Concrete Mathematics, by Graham, Knuth, and Patashnik, discusses the evaluation of sums in great detail, and is full of techniques for converting them to closed form. It is also extremely readable. If you have not yet read it, then yes, you have missed some essential discrete math training.

A: How about something like:
$$ \sum_{w=2}^{k_1}\sum_{h=2}^{k_2}(w-1)(h-1) = \sum_{w=2}^{k_1} (w-1) \sum_{h=2}^{k_2} (h-1) $$
You can compute a closed form answer for both of these summations using a small change of variable and a standard summation formula.

A: This can be solved fairly easily. Note that the innermost sum is with respect to h, so the factor $w - 1$ is a "constant" w.r.t. h. Thus, we can pull it out to get
$$\sum_{w=2}^{k_1} \left((w - 1) \sum_{h=2}^{k_2} (h - 1)\right) = \left(\sum_{w=2}^{k_1} (w - 1)\right)\left(\sum_{h=2}^{k_2} (h - 1)\right)$$
Now use the fact
$$\sum_{i=0}^{n} i = \frac{n(n+1)}{2}$$.
and linearity to evaluate the sums.


text:
Q: How do I launch a specific telnet-based app from a web browser? What I'd like to do is provide a link on an intranet web page that will launch a telnet session and pass context information to a shell script that will take the user to a specific "green screen."
This "pseudolink" might help show what I'm looking for:
<a href="telnet://<user>:<password>@<host>?showdetail%20123">detail for 123

Part of this solution might be a suggested telnet client that could interact with browsers (perhaps through JavaScript) to accomplish this.  Bonus points for obfuscating the credentials (but this is envisioned at this point to be a "read only" login).
Thanks!

A: In my opinion, and I'd love to be proved wrong, you will have sandbox (security) problems. Check out my question here which got little interest, but I think it's basically the same thing: you cannot open external apps from the browser unless they are already associated with the mime-type, protocol, or something.

A: There are some java applets which can be used as telnet clients, you could use one of them in the browser.

A: You cannot do this with a telnet: URL in most browsers (IE, FF, afaik). The telnet URL was originally described in RFC 1738, and it provided only information for a hostname, port, username and password.
When you click on it, the browser will usually ask the OS for the default "telnet" handler, which is an external application that is run. Most modern telnet clients accept these parameters and put them to use.
This architecture varies a bit between browsers, but the application is usually external. There was the occasional request in bugzilla.mozilla.org for support for a telnet plugin or a native telnet client, but it never got much attention.
There might be inline solutions like a java applet, but I doubt they are called with a telnet: URL.


text:
Q: Sublime Text 2-3 Code Formatting am working in ST3/2 and have tried a couple different formatting tools. In general the formatting is great but I'd like one more preference:
Currently here is how code is formatted

 Who is it For

I'd like to change it to:

 Who is it For

In other words, tags on one line, content on another.
Is this possible?

A: Have a read here for some ideas:
http://sublimetexttips.com/formatting-html-with-sublime-text/
To not get told things you already know you will probably need to tell us the tools you have already tried that don't work the way you want so we know not to recommend this again.


text:
Q: Check to see if a variable in a shell string begins with something I have a variable in my shell script called $FOLDER, and I want to check to see if $FOLDER begins with either / or ./. I don't want build to trigger it, but I do want either /build or ./build to work.
My attempt doesn't seem to be working, where am I going wrong?
if [[ $FOLDER == "/"* ]] || [[ $FOLDER == "./"* ]]
  then
  echo "Matched"
  exit 1
fi

A: Use case:
case "$FOLDER" in
/*|./*) echo "matched"
esac

Another way is to extract the substrings:
if [ "${FOLDER:0:1}" = "/" -o "${FOLDER:0:2}" = "./" ]; then
   echo "matched"
fi

*

*${FOLDER:0:1} extract one character from position 0 from the string.

*Similar ${FOLDER:0:2} extracts two characters

*Always quote your variable expansions.

*-o is a mnemonic from or


text:
Q: Adding (and then removing) a span to a div causes Javascript to not fire when img in the same div is clicked. How can I fix this? I'm building a chess app as a summer project and it works by submitting jQuery requests when pieces or squares are clicked. When a piece is clicked the request will return the valid squares for that piece to move to and then it adds a dot on that square to indicate that it can be moved there (it removes the dot after a square or other piece is clicked). The problem is that if there is already a piece on that square, the dot is added and then when it is removed, when the piece is clicked it no longer fires the Javascript. When I refresh the page it works fine again. How can I fix this so that even when a dot is added and then removed, clicking the piece will fire the js correctly?
This is the js code that runs when a piece is clicked:
$("img.piece").on("click", function(){
if (parent != undefined && parent.attr("class")=="light_square"){
    parent.css("background-color","WhiteSmoke");
    $(".dot").remove();
} else if (parent != undefined && parent.attr("class")=="dark_square") {
    parent.css("background-color","Sienna");
    $(".dot").remove();
}
parent = $(this).parent();
sq_one = $(this).attr("id").slice(5,10);
parent.css("background-color", "Gold");
$.ajax({
    contentType: 'application/json;charset=UTF-8',
    type:'POST',
    url:"/moves",
    data:JSON.stringify({'sq_one':sq_one}),
    success: function(response) {
        for (x in response) {
            var id = "square("+response[x]+")";
            document.getElementById(id).innerHTML += ("");
        }
    }
    });
});

$(".dot").remove(); is also used when a square is clicked.
The CSS for dots, squares, and pieces is as follows:
.dark_square {
    background-color: Sienna;
    width: 45px;
    height: 45px;
    text-align:center;
    position: relative;
}

.dot {
  height: 20px;
  width: 20px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  opacity: 0.5;
  top: 50%;
  left: 50%;
  position:absolute;
  transform: translate(-50%, -50%);
}

.piece {
    width: 42px;
    height: 42px;
}

Finally I'm using a table to do the board and the html looks like this:


text:
Q: How to divide array in different consecutive sequences How to divide this array:- [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15] into two different arrays with one set of consecutive sequences in one array and another set of consecutive in another array.
for eg : array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15]
Desired output  [0, 1, 2, 3, 4, 5, 6, 7, 8] and [12, 13, 14, 15]
The array should split into a number of consecutive sequences present in the array. If there are 3 consecutive sequences then the array should split into 3 different arrays with consecutive values and so on.
Another example = [1 ,2 ,3 ,4 5, 14, 15, 16, 22, 23, 24, 25]
Desired output  [1, 2, 3, 4, 5] and [14, 15, 16] and [22, 23, 24, 25]
let arrnew = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15]
   let arr2 = []

for (let j = 0; j < arrnew.length; j++) {
    if (arrnew[j + 1] - 1 === arrnew[j]) {
        arr2.push(arrnew[j])
    }
}

Tried this but not working.

A:

const arr = [1, 2, 3, 4, 5, 14, 15, 16, 22, 23, 24, 25];
const canSplit = (arr = []) => {
    const count = arr.reduce((acc, num) => {
      acc[num] = (acc[num] || 0) + 1
      return acc
    }, {})
    const needed = {}

    for (const num of arr) {
      if (count[num] <= 0) {
        continue
      }
      count[num] -= 1
      if (needed[num] > 0) {
        needed[num] -= 1
        needed[num + 1] = (needed[num + 1] || 0) + 1
      } else if (count[num + 1] > 0 && count[num + 2]) {
        count[num + 1] -= 1
        count[num + 2] -= 1
        needed[num + 3] = (needed[num + 3] || 0) + 1
      } else {
        return false
      }
    }
    return true
}
console.log(canSplit(arr));

A:

var arr = [1,2,3,4,6,7,8,9,10]
var result = []

for (var i = 0; i < arr.length; i++) {
    if (i === 0) {
        result.push([arr[0]])
    } else if (arr[i] != arr[i-1] + 1) {
        result.push([arr[i]])
    } else {
        tmp = result[result.length - 1]
        tmp.push(arr[i])
        result[result.length - 1] = tmp
    }
}

console.log(result) // [ [ 1, 2, 3, 4 ], [ 6, 7, 8, 9, 10 ] ]

Here we loop through arr. For the first element, the only thing we need to do is append to result a new array with the first number.
Now, for every number after the first one, if the current number is not equal to the previous number + 1, we need to append a new array to result that contains the current number. Otherwise, we simply append the current number to the last array in result.


text:
Q: xamarin item click in listview is not called I used listView and when I try to triger the itemclick function it doesn't triger.
I tried to figure that for the last 3 hours, pls help
in class:
li = (ListView)FindViewById(Resource.Id.listView1);
li.ItemClick += Li_ItemClick1;
li.ItemLongClick += Li_ItemLongClick;
li.Adapter = adapter;

in xml:
<ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView1"
        android:layout_marginTop="10dp"
        />

A: You must set your Click event on OnBindViewHolder method of the listview adapter. Try this code :
((MyView)holder).mMainView.Click -= Li_ItemClick1;
((MyView)holder).mMainView.Click += Li_ItemClick1;

Also this is a good way to unsubscribe and subscribe the method to avoid setting multiple times.
"MyView" is the class for the handler, to more specific, a handler is a class built with properties of your list item.
here is an example for MyView class:
 public class MyView : RecyclerView.ViewHolder
    {

        public View mMainView { get; set; }
        public TextView mName { get; set; }
        public TextView data { get; set; }
        public ImageView image { get; set; }
        public MyView(View view) : base(view)
        {
            mMainView = view;
            mName = view.FindViewById<TextView>(Resource.Id.text1);
            image = view.FindViewById<ImageView>(Resource.Id.foto);
            data = view.FindViewById<TextView>(Resource.Id.data);
        }
        public override string ToString()
        {
            return base.ToString() + " '" + mName.Text;
        }
    }

Here is a link that may be helpful: https://riptutorial.com/xamarin-android/example/30066/recyclerview-with-click-events
Note: RecycleView is a kind of ListView( i suggest using RecycleView because is simply ListView but improved and it makes it easier to do what you intend to). But if you want to use ListView this link is still helpful.


text:
Q: Excel - reference to XLAM file not being saved I can't get references to an XLAM file to be saved with a spreadsheet. I have to add the reference every time I open the spreadsheet.
Steps to reproduce:

*

*Create a new workbook.

*Go to the VBA editor and rename the VBA project to "MyAdvancedMath".

*Add a module. Name it "AdvancedMath".

*Add the following VBA in "AdvancedMath":

Option Explicit

Public Function Add(A As Double, B As Double) As Double
    Add = A + B
End Function

*Close the VBA editor. Save the file, changing the type to "Excel Add-in (*.xlam)". Let it save to the default folder ("C:\Users<>\AppData\Roaming\Microsoft\AddIns"). I called it "MyAdvMathAddIn.xlam".

*Close all copies of Excel.

*Start Excel. Create a new workbook. Save it as a macro-enabled workbook. I called it "MyAdvMathTest.xlsm".

*Go to the VBA editor. Then go to Tools - References. Browse and add a reference to "MyAdvMathAddIn.xlam".

*Set the formula in cell A1 to

=Add(4,8)
You should see the value 12 in cell A1.

*Save "MyAdvMathTest.xlsm" and close it.

*Open "MyAdvMathTest.xlsm". Cell A1 still has the value 12, as it should. Put the cursor in cell A1 and press Enter. Excel complains with a "#NAME?" error because it can't find the "Add" function.

*Go to the VBA editor and re-add the reference.

*Put the cursor in cell A1 and then press Enter. Now you see the value 12 again.

I'm running Microsoft 365 Apps for business, version 2209 (build 15629.20156 click-to-run). x64 version on x64 Windows 10.
The AddIns folder has been added to Trusted Locations. The Trust Center Macro Settings & ActiveX Settings are as permissive as they can possibly be, so it doesn't seem to be a security issue.
Note that the .xlam file must be referenced only from certain spreadsheets. Not all spreadsheets used by my employer.
Also note that this question was posted on Microsoft Answers (https://answers.microsoft.com/en-us/msoffice/forum/all/excel-reference-to-xlam-file-not-being-saved/f62b4764-1b27-4afb-a920-2e6804f8b213). The moderator suggested that I post here.
Thanks for any help you can provide.


text:
Q: MVC 4 and JsonResult format have a problem with the result format of this code
public JsonResult getCategorias(int? id)
{
  var res = from c in db.Categorias
  where (( id.HasValue && c.CategoriaPadre == id.Value) || (!id.HasValue && c.CategoriaPadre == null))
  select new { id = c.Id, label = c.Descripcion };

  return this.Json(res, JsonRequestBehavior.AllowGet);
}

this return a json:
[{"id":21,"label":"Marketing3"},{"id":22,"label":"Marketing4"}]
But i need a json with this format:
{"21":"Marketing3","22":"Marketing4"}
What can i do?
Thanks a lot and sorry my english.

A: Replace your return with:
var dictionary = res.ToDictionary(v => v.id, v => label);
 return this.Json(dictionary, JsonRequestBehavior.AllowGet);

A: When you return a _JsonResult_ it takes the object and automatically formats this way
    {
        "Property1":"Value1",
        "Property2"_"Value2",
        ...
    }

If you really need other format you could return a _ViewResult_ from your action, add a View and manually write the json. But for this especific format you could use something similar to the Garath's answer.

A: You can also use this:-
public static KeyValuePair<string,string> KeyValue(YourClass obj)
        {
            return new KeyValuePair<string, string>(obj.id, obj.label);
        }

Before call
Json(result.ConvertAll(i => KeyValue(i)), JsonRequestBehavior.AllowGet);

A: I do not know if this is possible to do with JsonResult, but you can use Json.NET and it's LINQ support (look on the "LINQ to JSON \ Creating Json", so your method will be something like
public JsonResult getCategorias(int? id)
{
  var properties = from c in db.Categorias
    where (( id.HasValue && c.CategoriaPadre == id.Value) || (!id.HasValue && c.CategoriaPadre == null))
    select JsonProperty(c.Id.ToString(), c.Descripcion);

  var res = new JObject(properties.ToArray());

  return Content(res.ToString(), "application/json");
}


text:
Q: For what values of $a \in \mathbb{R}$ , is there no solution to $e^x-a=\ln(x+a)$ I considered each expression as being a function like
$f:(-a, \infty )\rightarrow \mathbb{R}  $
$f(x)=e^x-a$
AND
$g:(-a, \infty )\rightarrow \mathbb{R}  $
$g(x)=\ln(x+a)$
By " not having solutions "I understand that the graphs have to have no common points of intersection. I tried this way to actually draw the graphs with no proper result because of the a varies.
I tried making a unique function like
$h:(-a, \infty )\rightarrow \mathbb{R}$
$h(x)=e^x-a-\ln(x+a)$
and apply the Rolle's Theorem, but didn't succeed.
How do I approach it? Sorry for the bad English, I tried my best.

A: Note that $\ln(x+a)$ is in fact the inverse function of $e^x - a$. A function and its inverse are reflections around the $y=x$ axis, so we only have a solution if $e^x - a$ intersects $y=x$ So  we only need to check if there are solutions to $e^x = a+x$. We can do this by noting the tangent to $e^x$ at $0$ is $x+1$ and the entire function lies above this line; we therefore only have solutions when $a \ge 1$, and no solutions when $a<1$.


text:
Q: Dump Emails from Exchange 2003 that match Certain Criteria Is it possible to retrieve emails that would match the following from Exchange 2003:
(Sent OR Recieved from a list of users) & ( Contains keyword x OR y OR z) & (Between x and y date)
and then send them to a new account?

A: You can use Exmerge to extract data from Exchange 2003 that meets certain criteria, which can include dates, subjects and attachments, which may get your some of the way there. It won't let you filter by sent or received from though.
You could use exmerge to get emails with the right subject and date out, and then open this with outlook and use outlook to filter based on the recipient.
As this is a PST file you can open it as an additional PST in outlook and drag and drop messages into your Exchange account, or other mailboxes.


text:
Q: Is the the output of Q' in an S-R Latch used for anything, or is only the Q output important? From looking at a diagram like this:

and watching some videos on the topic, it seems that Q represents a 1-bit memory, but I'm unsure if there is a purpose for Q'.

A: Qbar is used internally, as part of the latch, so it has to be there.
So the real question becomes, do we want Qbar to be available as an output pin?
It depends on whether you want it. If at some point in decoding you'll want the inverse of Q as well as Q, then it saves an inverter - and the time taken for the signal to go through an inverter.
Let's look at two different parts for two different purposes.
A 74HC74 is intended to be a very general purpose flip-flop, with set and reset inputs as well as Q and Qbar outputs, and two independent latches fit nicely into a 16 pin package.
A 74HC174 is six latches in the same size 16 pin package, and features only Q outputs and a common clock and master reset.
Decide whether you want Qbar outputs, and then find packages that optimise the rest of your design.


text:
Q: Adding input value to localStorage I am currently saving table row data to local storage using my AddToCart function like this:
So I have this table at the moment:

    Book Title
    Author
    Quantity
    Book

  Gone
  Micheal Grant
  <input></input>
  <button class="AddToCart">Add To Cart</button>

  The Knife of never letting go
  Ryan Howard
    <input></input>
  <button class="AddToCart">Add To Cart</button>

And this is what is in the AddToCart function:
$("table").on("click", ".AddToCart", function(e){

  // Get previous storage, if any.
  var storage = JSON.parse(localStorage.getItem("cart"));
  if(storage==null){
  storage = [];
  }

  var row = $(this).closest("tr");
  var title = row.find("td").eq(0).text().trim();
  var author = row.find("td").eq(1).text().trim();
  var quantity = row.find("td").eq(2).text().trim();

  // Create an object to store.
  var data = {author:author,title:title,quantity:quantity};
  storage.push(data);

  // Store it.
  localStorage.setItem("cart",JSON.stringify(storage));

  });

The problem I am having at the moment is that when i try to save the input value for quantity it is not being saved in local storage it just comes up as "". Any fixes for this problem?

A: Instead of setting the quantity equal to row.find("td").eq(2).text().trim(), you'll want to set it to row.find("input").val(). This can be seen in the following working example:

$("table").on("click", ".AddToCart", function(e) {

  var row = $(this).closest("tr");
  var title = row.find("td").eq(0).text().trim();
  var author = row.find("td").eq(1).text().trim();
  var quantity = row.find("input").val();

  // Create an object to store.
  var data = {
    author: author,
    title: title,
    quantity: quantity
  };

  console.log(data.quantity);

});

       Book Title
       Author
       Quantity
       Book

      Gone
      Micheal Grant
      <input>
      <button class="AddToCart">Add To Cart</button>

      The Knife of never letting go
      Ryan Howard
      <input>
      <button class="AddToCart">Add To Cart</button>

Also note that <input> is an empty element (so it does not have a closing tag), and
 does not permit any  children. I've fixed up both of these in my answer.


text:
Q: Different number of dispensers activated depending on orientation of redstone dust I have a column of 4 dispensers, all facing the same direction (to the right). For demonstration purposes, each is loaded with a different color of shulker box.

In the above screenshot, the dispensers are situated next to a 1-tick pulse generator, but not connected to it. By placing redstone dust on either the diamond block or the gold block, the dispensers are connected to the circuit so that the button causes them to activate.
If redstone dust is placed on the diamond block, all 4 dispensers activate.

If redstone is instead placed on the gold block, only the top 3 dispensers activate.

Since the redstone dust is not powering the dispensers, I'm guessing this is some kind of block update issue, but I don't understand exactly how it's working. What explains this behavior and how can I predict how the dispensers will behave inside of more complex circuits?
I'm using 1.13.1 Java edition.

A: This is a block-update bug.
First, the yellow dispenser (color-coded by the color of the shulker box dispensed) is dispensed. Then, because the Redstone runs right into the dispenser, the red and green dispensers fire immediately after, which is why the red shulker is facing upwards while the others aren't.
Next, the blue dispenser updates. The fact that the Redstone is on the diamond block makes the dispenser think it is being powered while it is not. As such, it fires, and the blue shulker box gets dispensed.
This only happens because the Redstone is on the diamond block, 2 blocks away. Yes, this is a bug. I don't look into Minecraft source code, I'd just put the Redstone on the gold until it gets fixed.


text:
Q: Im trying to to figure out what I need to write on sql command oracle For every customer that lives in Florida, list customer number, last name, first name,
and region.

A: I will assume that you are trying to get the information from a table called "table".
select customer_number,
       last_name,
       first_name,
       region
from table
where city = 'Florida'


text:
Q: EADDRINUSE error when re-running Node.js server on Windows 10 I'm having an issue where reloading (ctrl + c and then running again with node app) a basic Node.js server (tried v0.12.0 and v0.12.7) on Windows 10 causes the server to hang for about 20 seconds before reloading. When using a tool like PM2 to watch my server, it errors out after any update to the file and the log shows an EADDRINUSE error.
I boiled this down to the most simple possible example (thinking it might be an issue with Express) but it's still happening with the basic example from the Node.js documentation:
var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(3030);

console.log('Server running at http://127.0.0.1:3030/');

I've checked that nothing else is running on port 3030. I've also tried different port numbers. It just seems that the Node.js process is not shutting down and releasing the port in a timely manner. I've also tried using ctrl+break, and also capturing the SIGINT and manually calling process.exit(). I can confirm that it catches the signal, but it still hangs as described.
I first noticed this shortly after upgrading to Windows 10 from 7, and was not having issues before, so I would think this is the most likely culprit. I have a dual-boot with Ubuntu 14.04, and I am having no issues there with the same code.

A: I'm no longer having the problem I described: it was likely something very specific to my setup since it wasn't reported anywhere else. I have since updated to Node 4.2.1 and installed various Windows updates, so hard to say what the original cause was.


text:
Q: How can i make simple call to network web service from android ? I need to make some simple web service call from android.
I know the server ip address - and i know what it the method that i need to call.
The server is base on .net platform - and the method that i need to call will return to me simple string that will tell me what is the server web service version.
I don't know how to make this call.
Thanks for any help .

A: The answer depends on what sort of webservice this is... a SOAP (XML) webservice would need some XML capabilities, easiest option is to use a library (see below for KSOAP2)... a REST webservice might work with pure HTTP (perhaps plus JSON)...
For some sample source code/walkthrough/library/doc regarding all mentioned options on how to call a webservice from Android see:

*

*http://naveenbalani.com/index.php/2011/01/invoke-webservices-from-android/

*How to call a SOAP web service on Android

*http://wiki.javaforum.hu/display/ANDROIDSOAP/Home

*http://code.google.com/p/ksoap2-android/

*Make an HTTP request with android

*http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html

A: public class SOAPActivity extends Activity {
     private final String NAMESPACE = "http://www.webserviceX.NET/";
        private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
        private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
        private final String METHOD_NAME = "ConvertWeight";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SoapObject soapObject=new SoapObject(NAMESPACE, METHOD_NAME);

        String weight = "700";
        String fromUnit = "Kilograms";
        String toUnit = "Grams";

        PropertyInfo weightProp =new PropertyInfo();
        weightProp.setName("Weight");
        weightProp.setValue(weight);
        weightProp.setType(double.class);
        soapObject.addProperty(weightProp);

        PropertyInfo fromProp =new PropertyInfo();
        fromProp.setName("FromUnit");
        fromProp.setValue(fromUnit);
        fromProp.setType(String.class);
        soapObject.addProperty(fromProp);

        PropertyInfo toProp =new PropertyInfo();
        toProp.setName("ToUnit");
        toProp.setValue(toUnit);
        toProp.setType(String.class);
        soapObject.addProperty(toProp);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(soapObject);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
            Log.i("myApp", response.toString());

            TextView tv = new TextView(this);
            tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
            setContentView(tv);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    }

This is code for SOAP web service.


text:
Q: Script for File system monitoring aix i'm trying to create a script which will show filesystem which are utilized over 69% and exclude file system with name bkp or archival also if all file system is under 69% then script should just print single 'ok' message
using below script i'm able to achieve 1st part of my requirement but where i require just single 'ok' script output shows ok for multiple times (same as no of file system present on machine) can someone help me to get just single ok if every filesystem  is below threshold value ?
echo `df -k |awk '{print $7, $4}'|cut -d '%' -f1| awk '{if ($2>69)print $1, $2 ;else print "ok"}'|grep -vE "bkp|archival"`

normal output (i don't want to see 'ok' here but only file system names where threshold is crossed )
\ok ok ok /var 74 /tmp 79 ok ok /opt 74 ok /db2/tdb_instlocal 83 ok /LOGS 78 ok ok /db2/t1reorg 75 ok ok ok /bkg_26AS 79 ok ok ok /templogship 73 ok /dumptest 79 ok ok /db/n1db10 82 /db/n1db11 82 /db/n1db12 81 /db/n1db13 83 /db/n1db14 82 /db/n1db15 82 /db/n1db16 87 /db/n1db17 81 /db/n1db18 81 /db/n1db9 83 /db2/t1log 77 ok ok ok ok ok /db2/tdb_inst_l3 87 ok ok ok ok /db2/tdb_inst3 87 ok ok ok ok ok ok ok ok ok ok

if everything is under threshold value(below 69 %) then it should only shown single 'ok'
hope some will help me to fix my scipt.

A: (It seems like the output of my df -k is different than yours.. I have the amount of use as $5, whereas you have it as $4. Further, the name of the file system is $1, whereas you use $7) On my machine, the following seems to work
df -k | awk -f print.awk

where print.awk is
NR> 1{
    sub(/%/,"",$5)
    if ($5 > 69) {
       if (!match($1,/bkp|archival/)) {
         print $5, $1; f=1
       }
    }
}

END { if (!f) print "ok" }

or as a one liner:
df -k | awk 'NR> 1{ sub(/%/,"",$5);  if ($5 > 69) { if (!match($1,/bkp|archival/)) { print $5, $1; f=1; } } } END { if (!f) print "ok" }'


text:
Q: how to make dynamic table using JSON? Hi i am new with jquery and react I have strong skills for HTML javascript and angular so i know how to make a table with response in json.
I have this JSON and i want to make a HTML table with it please can some body help with it
[
    {
        "id": "5a6f8f9eafb2b40824cfde8e",
        "prodName": "Dummy Product 1",
        "prodDesc": "The Fresh Dummy Product in The world part 1",
        "prodPrice": 100,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a7031b8afb2b40824cfde8f",
        "prodName": "Dummy Product 2",
        "prodDesc": "The Fresh Dummy Product in The world part 2",
        "prodPrice": 150,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a7031c5afb2b40824cfde90",
        "prodName": "Dummy Product 3",
        "prodDesc": "The Fresh Dummy Product in The world part 3",
        "prodPrice": 250,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a7031d4afb2b40824cfde91",
        "prodName": "Dummy Product 4",
        "prodDesc": "The Fresh Dummy Product in The world part 4",
        "prodPrice": 300,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a7031e9afb2b40824cfde92",
        "prodName": "Dummy Product 5",
        "prodDesc": "The Fresh Dummy Product in The world part 5",
        "prodPrice": 330,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a7031f9afb2b40824cfde93",
        "prodName": "Dummy Product 6",
        "prodDesc": "The Fresh Dummy Product in The world part 6",
        "prodPrice": 390,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a703208afb2b40824cfde94",
        "prodName": "Dummy Product 7",
        "prodDesc": "The Fresh Dummy Product in The world part 7",
        "prodPrice": 400,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a7032ebafb2b40824cfde95",
        "prodName": "Dummy Product 8",
        "prodDesc": "The Fresh Dummy Product in The world part 8",
        "prodPrice": 490,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a703a52afb2b40824cfde96",
        "prodName": "Orio-biscuits",
        "prodDesc": "The fresh milk biscuits for children",
        "prodPrice": 30,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": null
    },
    {
        "id": "5a7048acd5a5e430d8362671",
        "prodName": "Orio-biscuits-2",
        "prodDesc": "The fresh milk biscuits for children",
        "prodPrice": 30,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": "Nestle"
    },
    {
        "id": "5a75f0e4d5a5e430585908d6",
        "prodName": "Orio-biscuits-3",
        "prodDesc": "The fresh milk biscuits for children",
        "prodPrice": 30,
        "prodImage": "https://dummyimage.com/600x400/000/fff",
        "prodManufacturer": "Nestle"
    },
    {
        "id": "5a75fce5d5a5e41f6067ede7",
        "prodName": "Orio-biscuits-3",
        "prodDesc": "The fresh milk biscuits for children",
        "prodPrice": 30,
        "prodImage": null,
        "prodManufacturer": "Nestle"
    },
    {
        "id": "5a7615f2d5a5e42f8463c1c3",
        "prodName": "parle",
        "prodDesc": "The fresh milk biscuits for children",
        "prodPrice": 30,
        "prodImage": null,
        "prodManufacturer": "biscuits"
    },
    {
        "id": "5a76ee9ad5a5e45884569f26",
        "prodName": "parle_chickli",
        "prodDesc": "The fresh milk biscuits for children",
        "prodPrice": 30,
        "prodImage": null,
        "prodManufacturer": "biscuits"
    },
    {
        "id": "5a775728afb2b451708d0254",
        "prodName": "helo",
        "prodDesc": "check me",
        "prodPrice": 19,
        "prodImage": null,
        "prodManufacturer": "test_one1"
    },
    {
        "id": "5a77581cafb2b451708d0255",
        "prodName": "skype",
        "prodDesc": "comm IDE",
        "prodPrice": 180,
        "prodImage": null,
        "prodManufacturer": "microsoft"
    }
]

Please can some body help me that how can i form a table in jquery or react
Help is much appreciated.

A: For such this kind of rendering first thing you need to take into account that how you'll serve the json file is it through the module bundler (Webpack) by using it inside your Component
import jsonObj from 'path_to_json_file';
or
you can serve it through this npm package called json-server npm i -s json-server Read Documentation here
You can run json-server by running the following json-server command:
json-server --watch path_to_your_json_file
after getting the json by whatever way you need
you need to make a fetch request which is the "HTTP" library to get data from your services
then write a react render function like the following:
`
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Carousel.css';
import Thumbnail from '../Thumbnail';

class Carousel extends React.Component {
    static propTypes = {
        titles: PropTypes.string.isRequired,
    };

    render() {
        const propsTitles =
        this.props.titles && this.props.titles.titles.length
        ? this.props.titles.titles
        : [];
        if (propsTitles.length < 1) return
There are no items here
;
        return (

                {propsTitles.map(title => (

{title.title}

{title.year}

                            <Thumbnail thumbItems={title.thumbnails} />

                ))}

            );
        }
    }

    export default withStyles(s)(Carousel);

`
Also for rendering component you need to look into JSX react templating you can iterate on your object over .map function


text:
Q: Display real time results in input box I am trying to display the results of an input in real time in another disabled input box and am not having much luck. Code below:
var inputBox = document.getElementById('input');

inputBox.onkeyup = function(){
    document.getElementById('output').innerHTML = inputBox.value*2;
}

<input type='text' id='input'>

<input type='text' id='output' disabled>

Can anyone help?
Thanks,
John

A: Try adding a listener and use value instead of innerHTML:
document.getElementById('input').addEventListener("keyup", myFunction);

var inputBox = document.getElementById('input');

function myFunction(){
    document.getElementById('output').value = inputBox.value*2;
}

JSfiddle: https://jsfiddle.net/22t37834/

A: Use the 'keyup' as it is fired after the char is entered.
$("#input").keyup (function (e) {
     $('#output').val($(this).val() * 2);
});

A: Try This one -

var inputBox = document.getElementById('input');

inputBox.onkeyup = function(){
    document.getElementById('output').innerHTML = inputBox.value*2;
   var val = document.getElementById('input').value
  document.getElementById('output').value = val;
}
<input type='text' id='input'>

<input type='text' id='output' disabled>


text:
Q: Is "set some time on the side" a common phrase? I was convinced set some time on the side was a correct, fairly common expression. However, I am now in doubt because I can't find it via Google phrase match search. Is it idiomatic English?
For example, one might say in a meeting invite,

I wanted to set some time on the side to discuss our Q2 plans.

A: As others have pointed out in the comments, aside was likely the intended word. On the side usually means something in addition to ones current activities, such as a side hustle, or a freelancing gig.


text:
Q: How to check the values inputted in the JTextField and transfer the string input to an array of characters? I want to compare every digits of the input number. I am trying to make a DFA program and my DFA accepts strings that does not have any consecutive symbol from 0 and 1.
here's the part of my class that I'm having a trouble with.. I just want to somehow parse and compare each characters/integers...
class check implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        JTextField inp= (JTextField) event.getSource();
        char[] text=inp.toCharArray();
        char[] result=new char[text.length];
        int ctr=0;

        while (ctr<result.length)
        {
            if(passy[ctr]==passy[ctr+1])
            {
            }

            else
            {
                JOptionPane.showMessageDialog(null, "The String is NOT ACCEPTED!");
            }

            ctr++;
        }
    }
}

I'm having an error in this part:
char[] text=inp.toCharArray();

A: The method toCharArray is undefined for JTextField. You need to get the text from the component first. Replace
char[] text = inp.toCharArray();

with
char[] text = inp.getText().toCharArray();


text:
Q: I'm trying to prove that $ [\hat L^2, \hat V(\hat r ,\hat p )] = -2i\hbar (i\hbar \hat V - \hat V \times \hat L) $ First  I prove that:
$$[\hat L, \hat H] = 0$$
with $$\hat H = \frac{\hat{p}^2}{2m}+\hat V(\hat r)$$
Then, with $\hat V(\hat r,\hat p)$ as a vector:
$$ [\hat L^2, \hat V(\hat r ,\hat p )] = -2i\hbar (i\hbar \hat V - \hat V \times \hat L) $$
I know that:
$$ [\hat x_i,\hat p_j]=i\hbar \delta_{ij} $$
$$ [\hat L_i,\hat x_j]=i\hbar\epsilon_{ijk}\hat x_k$$
$$ [\hat L_i,\hat p_j]=i\hbar\epsilon_{ijk}\hat p_k$$


text:
Q: How to make certain hosts bypass Fiddler? I have the Fiddler filters setup to "hide" the host "roaming.officeapps.live.com" and it does not show while I am debugging.
But the Fiddler proxy is still causing security issues (incorrect ssl certificate) to office, message relates to that host.
How can get a specific host to bypass Fiddler?
Or is the nature of a proxy based system that all requests go through it regardless?

A: Tools > Fiddler Options > Connections > Bypass Fiddler for hosts that start with or use the HTTPS tab to Skip decryption for.


text:
Q: permutations of certain digits in Java I realize permutations in programming language is a very frequently asked question, however I feel like my question is sort of unique.
I have received input of a certain length integer N and stored each digit in an array where the index of the array stores the number of times that digit occurs in N.
now I want to test if some function holds true with all permutations of N's original length with no leading zeroes.  Ex:
int[] digits = new int[10];
String n = "12345675533789025";
for (char c : n.toCharArray())
    digits[c-'0']++;
for (Long f : allPermutationsOf(digits))
    if (someCondition(f))
        System.out.println(f);

a precondition to the following code is that N must be less than 2^64-1, (long's maximum value.)
The question is, how would I take all permutations of the digits array and return a Long[] or long[] without using some kind of String concatenation?  Is there a way to return a long[] with all permutations of digits[] in the "Integer scope of things" or rather using only integer arithmetic?

A: To elaborate on one of the above comments, putting a digit d in a given place in the resulting long is easy: d*1 puts it in the 1s place, d*1000 puts it in the thousands place, and in general d * (10^k) puts d into the k+1th digit. You have N total digits to fill, so you need to do permutations on the powers of 10 from 1 to 10^(N-1).

A: If you are expecting the permutations to be Longs anyway, instead of representing n as an array of counts, it might be easier to represent it as a Long too.
Here are a couple of ways you can generate the permutations.

*

*Think of generating permutations as finding the next largest number with the same set of digits,  starting from the number consisting of the sorted digits of n. In this case, the answers to this StackOverflow question is helpful. You can use arithmetic operations and modding instead of string concatenation to implement the algorithm there (I can provide more details if you like). A benefit of this is that the permutations you generate will automatically be in order.

*If you don't care about the order of the permutations and you expect the number of digit duplicates to be small, you can use the Steinhaus-Johnson-Trotter algorithm, which (according to Robert Sedgewick) is the fastest algorithm for generating permutations of unique elements. To make sure duplicate permutations are not generated, you would have to distinguish every duplicate digit and only emit the permutations where they appear in order (i.e., if 2 appears three times, then create the elements 2_1, 2_2, 2_3 and make sure those three elements always appear in that order in an emitted permutation).

A: For the requirement, assuming that the length of N is n, we can generate all permutations by going from digit to digit, starting from 0 and end at n - 1. With 0 is the leading digit.
For each digit, we only go through each possibility (0 to 9) once , which will avoid duplicate permutation.
From digit x to digit x + 1, we can easily generate the current value by passing a number called current
For example: at digit 3, we have current = 1234, so at digit 4, if we choose 5 to be at digit 4, the current will be 1234*10 + 5 = 12345
Sample code in Java:
public void generate(int index, int length, int[] digits, long current, ArrayList<Long> result) {
    //All the permutation will be stored in result ArrayList
    for (int i = 0; i < 10; i++) {
        if (digits[i] > 0 && (i != 0 || index != 0)) {
            digits[i]--;
            if (index + 1 == length) {//If this is the last digit, add its value into result
                result.add(current * 10 + i);
            } else {//else, go to next digit
                generate(index + 1, length, digits, current * 10 + i, result);
            }
            digits[i]++;
        }
    }
}


text:
Q: How to use blist module without installing it? Without installing blist, I am trying to use blist_1.3.6 module by setting the environment variable PYTHONPATH. However I am still getting the error below. Is there any way to use this _blist without installing it? I can see _blist.c is C language file.
File "/path/blist-1.3.6/blist/__init__.py", line 2, in <module>
    from blist._blist import *
ImportError: No module named _blist

A: _blist is the module implemented by the object that results from compiling _blist.c and creating a shared library from it. You can't simply import _blist.c directly.


text:
Q: Pytest - How to pass an argument to setup_class? I have some code as shown below.
I am getting a too few args error when I run it.
I am not calling setup_class explicitly, so not sure how to pass any parameter to it.
I tried decorating the method with @classmethod, but still see the same error.
The error that I am seeing is this - E           TypeError: setup_class() takes exactly 2 arguments (1 given)
One point to note - If I do not pass any parameter to the class, and pass only cls, then I am not seeing the error.
Any help is greatly appreciated.
I did review these questions question #1 and question #2prior to posting. I did not understand the solutions posted to these questions, or how they would work.
class A_Helper:
    def __init__(self, fixture):
        print "In class A_Helper"

    def some_method_in_a_helper(self):
        print "foo"

class Test_class:
    def setup_class(cls, fixture):
        print "!!! In setup class !!!"
        cls.a_helper = A_Helper(fixture)

    def test_some_method(self):
        self.a_helper.some_method_in_a_helper()
        assert 0 == 0

A: Since you are using this with pytest, it will only call setup_class with one argument and one argument only, doesn't look like you can change this without changing how pytest calls this.
You should just follow the documentation and define the setup_class function as specified and then set up your class inside that method with your custom arguments that you need inside that function, which would look something like
class Test_class:
    @classmethod
    def setup_class(cls):
        print "!!! In setup class !!!"
        arg = '' # your parameter here
        cls.a_helper = A_Helper(arg)

    def test_some_method(self):
        self.a_helper.some_method_in_a_helper()
        assert 0 == 0

A: You get this error because you are trying to mix two independent testing styles that py.test supports: the classical unit testing and pytest's fixtures.
What I suggest is not to mix them and instead simply define a class scoped fixture like this:
import pytest

class A_Helper:
    def __init__(self, fixture):
        print "In class A_Helper"

    def some_method_in_a_helper(self):
        print "foo"

@pytest.fixture(scope='class')
def a_helper(fixture):
    return A_Helper(fixture)

class Test_class:
    def test_some_method(self, a_helper):
        a_helper.some_method_in_a_helper()
        assert 0 == 0