Q:

Arduino can't output in both led screen and serial monitor at the same time

I am trying to have Arduino output on both LED screen using the LiquidCrystal library, and on Serial Monitor (later to a txt file or something like that).
In my code, I commented out Serial.begin(9600) and then the screen outputs correctly, but as soon as I include it, the serial monitor outputs fine but the screen flips out and outputs gibberish.
I'm fairly new and I know there's something basic I don't know like 9600 should be augmented because so much power is needed maybe?
#include <LiquidCrystal.h>
#include <DHT.h>
#include <math.h>

/*
    * Cannot do both screens and log in the console.
    * Currently Serial 9600 is commented out, to allow to print on the screen
    * Need Fixing
*/

#include "DHT.h"

#define DHTPIN 8     // what digital pin we're connected to

#define DHTTYPE DHT11   // DHT 11
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup() {
    //Serial.begin(9600);
    Serial.println("Temperature Recorder");

    dht.begin();

    // Now LiquidCrystal led monitor stuff
    lcd.begin(16,2);
    lcd.setCursor(2,0);
    lcd.print("** Wanet **");
    delay(1500);
    lcd.setCursor(1,1);
    lcd.print("Motherfuckers.");
    delay(3000);
    lcd.clear();
}

void loop() {
    // Wait a few seconds between measurements.
    delay(1000);

    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float f = dht.readTemperature(true);

    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
    }

    // Compute heat index in Fahrenheit (the default)
    float hif = dht.computeHeatIndex(f, h);
    // Compute heat index in Celsius (isFahreheit = false)
    float hic = dht.computeHeatIndex(t, h, false);

    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.print(f);
    Serial.print(" *F\t");
    Serial.print(" | Heat index: ");
    Serial.print(hic);
    Serial.print(" *C ");
    Serial.print(hif);
    Serial.println(" *F");
    Serial.println("------------------------------------");

    //   led screen printing
    lcd.setCursor(0,0);
    lcd.print("Temp:  Humidity:");
    lcd.setCursor(0,1);
    lcd.print(t);
    lcd.print("   ");
    lcd.print(round(f));
    lcd.print("%");

    delay(5000);
    lcd.clear();
    lcd.setCursor(2,0);
    lcd.print("The world");
    lcd.setCursor(4,1);
    lcd.print("OURS");
    delay(6000);
}

Cheers

A:

On the docs of Arduino's Serial

Serial
It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB. Thus, if you use these functions, you cannot also use pins 0 and 1 for digital input or output.

You have two options or you don't use those 2 pins
like this
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
or if you must have those pin you might consider to use a library like softwareSerial which emulates the serial communication a pair of pin of your choice. but the serial monitor via USB won't work anyway.


Q:

TSQL to recurse based on a condition

I have a query to get list of members in a group as below
;WITH CTE (GroupName, GroupMember, isMemberGroup)
     AS (SELECT ag.name,
                agm.Member,
                agm.MemberIsGroup
         FROM   tb1 ag
                LEFT JOIN tb2 agm
                  ON ag.ID = agm.ID
         WHERE  ag.name = 'somegroupame')
SELECT *
FROM   CTE

Group Name   Group Member  IsMemberGroup
Admin        John          0
Admin        Sam           0
Admin        GDBA          1
xyz          Dan           0
xyz          GXy           1

I want to write a query to get members of the sub group as well if IsMemberGroup is 1. Please guide me how to achieve that.
The expected result is to get a list of members including members of sub groups for a give group. The recursion should happen for all the sub groups' groups as well if any:
Resultant: Admin
     Group              Group Member
     Admin              John
     Admin              Sam
     Admin(GDBA)        Mike
     Admin(GDBA)        June
     Admin(GDBA/Bcksdmin)Mark

A:

You could solve this problem using a recursive CTE to generate your group member hierarchy.
This example using the following data:
/* Let's create some sample data to experiment with.
 */
DECLARE @Sample TABLE
    (
        GroupName            VARCHAR(50),
        GroupMember            VARCHAR(50),
        IsMemberGroup        BIT
    )
;

INSERT INTO @Sample
    (
        GroupName,
        GroupMember,
        IsMemberGroup
    )
VALUES
    ('Admin', 'John', 0),
    ('Admin', 'Sam', 0),
    ('Admin', 'GDBA', 1),
    ('GDBA', 'Mike', 0),
    ('GDBA', 'June', 0),
    ('GDBA', 'Bcksdmin', 1),
    ('Bcksdmin', 'Mark', 0)
;

The query uses the CTE to calculate the group hierarchy.  This is then joined back to the original data, like so:
/* Using a recursive CTE we can build the group name
 * hierarchy.
 */
WITH [Group] AS
    (
            /* Anchor query returns all top level teams, ie
             * those that do not appear in the group member
             * field.
             */
            SELECT
                s1.GroupName,
                CAST(s1.GroupName AS VARCHAR(MAX))        AS Breadcrumb
            FROM
                @Sample AS s1
                    LEFT OUTER JOIN @Sample AS s2    ON s2.GroupMember = s1.GroupName
            WHERE
                s2.GroupName IS NULL
            GROUP BY
                s1.GroupName

        UNION ALL

            /* Using recursion, find all children.
             * (Sub groups are identified by the IsMemberGroup flag).
             */
            SELECT
                s.GroupMember                            AS GroupName,
                g.Breadcrumb + '/' + s.GroupMember
            FROM
                [Group] AS g
                    INNER JOIN @Sample AS s        ON s.GroupName = g.GroupName
            WHERE
                s.IsMemberGroup = 1
    )
SELECT
    g.Breadcrumb,
    s.GroupMember
FROM
    @Sample AS s
        INNER JOIN [Group] AS g        ON g.GroupName  = s.GroupName
WHERE
    s.IsMemberGroup = 0
;

Although this solution works I would suggest you revisit the table design, if possible.  The column GroupMember is pulling double duty by storing both teams and team members.  Splitting this into Group (with parent lookup column) and GroupMember tables would simplify the task.  Each new table would only need to describe one real world object, making it clearer where new columns should be created.


Q:

Image, file, text uploader and URL shortener

I've made a tiny PHP script that sits on my server and receives images/files and text/urls I send to it from a desktop application. I'm a bit worried about how secure the whole thing is because the upload endpoint is the same URL as users who view the content I've uploaded go to.
This script takes uploaded things and stores them in the database under a unique, random, 5-character alphanumeric string. Text and URLs are stored verbatim (albeit mysqli_escape_string'd) in the database while files (this includes images) are stored in a subfolder named "upload" that the webserver user has 0755 access to. URLs are location redirected, text is displayed raw, and files are fpassthrough()ed when a user requests an existing 5-character string.
The database credentials ($db_*) and upload control variables ($upload_*) are in uploader_settings.inc.php (which is not included here).
index.php:
<?php
/**
 * Make sure the upload directory is chmod'ed to 755
 *
 */
require("./uploader_settings.inc.php");

$conn = mysqli_connect($db_url,$db_user,$db_pass,$db_database);
if (mysqli_connect_errno()) {
    http_response_code(500); //server error
    die();
}
//handle content
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //all required data?
    if (!isset($_POST['type']) || !isset($_POST['value']) || !isset($_POST['pass'])) {
        http_response_code(400); //bad request
        echo "Malformed request!";
        die();
    }
    //correct password?
    if ($_POST['pass'] != $upload_pass) {
        http_response_code(401); //not authorized
        echo "Missing auth!";
        die();
    }
    //actually do it
    $value =  $_POST['value'];
    $random = random_str(5);
    do {
        $query = mysqli_query($conn,"SELECT * FROM ".$db_table." WHERE shortened = '".$random."';");
        if (mysqli_num_rows($query) == 0) {
            break;
        } else {
            $random = random_str(5);
        }
    } while (true);
    switch ($_POST['type']) {
        case "url":
        case "text":
            mysqli_query($conn,"INSERT INTO ".$db_table." (shortened,type,value) VALUES ('".$random."','".$_POST['type']."','".mysqli_real_escape_string($conn,$value)."');");
            break;
        case "file":
            $file = $_FILES['fileToUpload'];
            $newfile = "./upload/".$random.".".mysqli_real_escape_string($conn,pathinfo($file['name'],PATHINFO_EXTENSION));
            if ($file['error'] == UPLOAD_ERR_OK) {
                if (!move_uploaded_file($file['tmp_name'], $newfile)) {
                    http_response_code(500);
                    echo "File error!";
                    die();
                }
                mysqli_query($conn, "INSERT INTO " . $db_table . " (shortened,type,value) VALUES ('" . $random . "','file','" . $newfile . "');");
            } else {
                http_response_code(500);
                echo "Upload error!";
                die();
            }
            break;
        default:
            http_response_code(500);
            echo "Invalid type";
            mysqli_close($conn);
            die();
    }
    http_response_code(200);
    echo $upload_returnURL.$random;
    mysqli_close($conn);
    die();
} else { //getting a URL
    $query = mysqli_query($conn,"SELECT * FROM ".$db_table." WHERE shortened = '".mysqli_real_escape_string($conn,$_GET['selector'])."';");
    mysqli_close($conn);
    if (mysqli_num_rows($query) > 0) {
        $array = mysqli_fetch_array($query);
        $value = $array['value'];
        switch ($array['type']) {
            case "url":
                header("Location: ".$value);
                die();
            case "text":
                echo $value;
                die();
            case "file":
                header("Content-Type: ".mime_content_type($value));
                fpassthru(fopen($value,"rb"));
                die();
        }
    } else {
        header("Location: ".$upload_failRedirect);
        die();
    }
}

function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}

And should it matter, .htaccess:
RewriteEngine on
#all files and directories
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
#pass to index as perameter
RewriteRule ^(.*)$ index.php?selector=$1 [NC,L,QSA]

A:

Use prepared statements
This, and other SQL statements in your code, is an SQL injection waiting to happen:

mysqli_query($conn,"INSERT INTO ".$db_table." (shortened,type,value) VALUES ('".$random."','".$_POST['type']."','".mysqli_real_escape_string($conn,$value)."');");

Don't construct SQL by embedding user input into a string.
Use prepared statements.
Don't store clear passwords
This suggests that you have somewhere a password stored in clear text:

if ($_POST['pass'] != $upload_pass) {

It's better to store passwords in a hashed form,
so that they cannot be stolen too easily.

A:

Pay close attention to the advice from @janos regarding your SQL injection vulnerability.  I agree with that assessment and so won't he-hash it here.

First, I would consider splitting the upload/record creation endpoint (POST use case) apart from the view/retrieval endpoint (GET use case).  Why introduce the complexity of managing both of these endpoints within a single script?  There is basically nothing to lose into splitting these endpoints, and a lot to gain in terms of simplifying your code.
A rule of thumb you can think about is that the more indented code you have in a script (via conditionals, loops, switches), the more likely you are to have bugs.  So in this case why deal with two wholly different codepaths with different expected results within one script?

I think you have already introduced bad behavior into this script by having the whole GET use case executed within an unconditional else block.  You just assume that if someone arrives at this script while not using POST action, that the request is fine and you go right into querying against the database.  There could be a whole lot of things wrong about that request that you should validate before making the relatively expensive database call. What if the request is not GET at all?  What if selector input parameter is not set, or is not within expected range of values?

In POST path, there should be no reason to try a select against the DB to see if the short code already exists.  If you have this table properly implemented with a unique index on the short code field, there is no reason to pre-select.  You could go directly to insert and check for duplicate index violation error and retry with new code if this fails.  This makes it to where happy path use case no longer takes two queries against the DB, it would only take one.

I am concerned with the whole approach in comparing $_POST['pass'] against some stored password variable (I am assuming this is defined in the include file). Does this mean you have a single password that, if compromised, gives any user of the system the ability to modify any record?  This seems like a poor security strategy, not to mention the apparent plain text nature of this as already noted. You should like have a separate user authentication/authorization mechanism rather having a single password passed at the time of especially since I am seeing nothing in your .htaccess or code (maybe this is in include) that is forcing HTTPS protocol to be used.

Though the code is not shown, here, you did comment that that your DB credentials a re set in the include file.  You should strongly consider moving away from a paradigm where credentials of any kind are stored in your code.  Ideally these are passed from environmental configuration.  Additionally, why would these value be in variables that are able to be changed at run time anywhere in your code?

In POST path, I think you should validate "type" value early in code path like you have done with other validations.  If an invalid value is set, you should use 400 error, not 500 as is currently given.

Why are you using mysqli escape on file name when forming file path?

You have a potential directory traversal vulnerability when creating your file path, as you are doing nothing to validate the path file name input.  What happens if file name has ../../ or similar in name?

You have both CSRF and XSS vulnerabilities in your code.  You should be using form tokens as mitigation against CSRF (this also means you need to be using sessions).  And you need to consider cleansing text input before insert (for example failing if you detect <script> tags or other XSS vectors), and at point of rendering (where you are also not even rendering proper HTML entities.).

I am guessing the GET path doesn't actually work as you are closing your DB connection before retrieving rows!

In your type="test" GET use case, you do not explicitly set http response headers.  This is actually probably not a problem, but this is not consistent with your usage in POST path.

I am not sure why you are using multibyte function in your random string generation function when you are not working with a multibyte "keyspace".

In general, you should get in the habit of using exact comparisons (===, !==) instead of loose comparisions, unless there is some specific reason you need to perform a loose comparison.  This will make your code more resilient against unexpected truthy/falsey evaluations.  That time you spend in typing the extra characters is negligible in comparison to the time you will spent debugging a codebase full of loose comparisons.

You should consider moving away from SELECT * queries.  These are oftentimes wasteful of bandwidth and application memory as most practical cases don't require all columns to be retirieved (so why retrieve them).  For example, you GET path has you sending back the short code in your query when that is the known value you are using for lookup.
One might also find that * selects can make their code fragile to database schema changes.
Finally, you code is much more readable when you see the exact fields that you are working with.  One doesn't need to know the DB schema to understand what the result set looks like.

Why is your random string function defined in this script instead of in the include?  It is good to get in the habit of separating your PHP code into files based on whether they represent application logic (i.e. classes, functions, interfaces, etc.) or whether they actually cause changes in the state of the application or render output. These leads to better code organization.

Your application should probobaly only have 600 permissions (or possibly 644 if other system users need to read to files) in the upload file directory.  I assume none of these files are going to be executed (thus needing 7).

Your code is very happy path oriented.  You just assume your code is going to work as expected.  For example, you assume that all database queries are going to work and have no handling of potentially failing queries.

You have basically no validation of input parameters (outside of their mere existence).  This combined with your happy path only code, means your whole script is very fragile to having unexpected behaviors and security vulnerabilities.


Q:

jQuery fade - Display div on page load

I have a simple jquery fade working perfectly, I am trying to have it so that when the page is opened the first div is displayed automatically.
Currently when the page loads there is no content
http://jsfiddle.net/Wqc9N/10/
 $(".link").click(function(e) {
      e.preventDefault();
      $('.content-container div').fadeOut('slow');
      $('#' + $(this).data('rel')).fadeIn('slow');
  });

A:

Till now you are registering the click events for every link by this code
$(".link").click(function(e) {
    e.preventDefault();
    $('.content-container div').fadeOut('slow');
    $('#' + $(this).data('rel')).fadeIn('slow');
});

What i suggest is to fire the click once the page Document Object Model (DOM) is ready for JavaScript code to execute
So try this with your code
$( document ).ready(function() {
    $(".link")[0].click();
});

Fiddle


Q:

Tuning machines are too sensitive and change the pitch too much. What should I do?

I have just bought a steel guitar (actually a 10-string brazilian viola) and the tuning is too sensitive, because only a small movement on the peg changes the pitch too much. It's not an exaggeration to say that the "useful range" of movement is less than 5 angular degrees, and this is way different of what I got used in other instruments.
I suspect this might be due to two possible causes:

The machine heads turning ratio is poor;
The strings are too low-quality;

So, the questions are:

What is the expected turning ratio (handle revolutions per axis revolution) of a good-quality guitar machine head?
Is it possible that bad quality strings are the cause for my problem? Should I expect the tuning process to be easier with better strings?

Here's an image of the tuning machine model, taken from the manufacturer site:

A:

It is likely that the nut slots are too tight and the strings are sticking.  When they respond to the tuning peg, they are actually slipping and so you aren't getting a gradual change in pitch.
Next time you restring the instrument, try thinner strings (maybe it was set up that way) and you could consider putting some graphite powder in the slots as a dry lubricant so the strings glide through easier.
Ultimately, you may need to go to a luthier to have the instrument adjusted in some way (either tuners, nut, strings, etc).


Q:

Why does this element animate backwards?

I am learning about CSS animations and I'm a little stuck on something. I've got things mostly working but the first balloon is going backwards first and I do not understand why. I've tried a whole lot of different things, like changing the position translate with no success. Any thoughts? The class of the first balloon I am referring to is initialBalloon.

html {
 box-sizing:border-box;
}
*,
*:before,
*:after { /* allow all elements to inherit box-sizing */
  box-sizing: inherit;
}
html, body {
 margin:0;
 padding:0;
 overflow:hidden;
 width: 100vw;
 height: 100vh;
}

.BalloonContainer {
    position: absolute;
    overflow: hidden;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
}

.initialBalloon {
  position: absolute;
  /* moves initial position before animating */
  transform: translateX(100vw);
  top: 150px;
  animation: moveFirst 5s linear .2s;
  animation-iteration-count: 1;
  width: 150px;
}

.firstBalloon {
  position: absolute;
  transform: translateX(-30vw);
  top: 150px;
  animation: move 5s linear 5s infinite;
  width: 150px;
}

.secondBalloon {
  position: absolute;
  transform: translateX(-30vw);
  top: 200px;
  animation: move 8s linear 0s infinite;
  width: 150px;
}

.thirdBalloon {
  top: 250px;
  transform: translateX(-30vw);
  position: absolute;
  animation: move 11s linear 1s infinite;
  width: 150px;
}

@-webkit-keyframes move {
  0% {
    transform: translateX(-30vw) rotate(10deg);

  }
  50% {
 transform: rotate(-5deg);
  }
  100% {
    transform: translateX(100vw) rotate(10deg);

  }
}

@-webkit-keyframes moveFirst {
  0% {
    transform: translateX(50vw) rotate(10deg);
  }
  50% {
 transform: rotate(-5deg);
  }
  100% {
    transform: translateX(100vw) rotate(10deg);
  }
}

   <svg id="Balloon_1" data-name="Balloon_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48.82 125.26"><defs></defs><title>ballon</title><path id="ballon_1p" class="cls-1" d="M15.34,1.26s-18,9-15,26,19,28,19,28a22.69,22.69,0,0,0,4,1c1,0-2,2-1,3h5s2,0-1-3c0,0,18-6,22-28S30.34-3.74,15.34,1.26Z" /><path id="highlight_1" class="cls-2" d="M18.34,6.26s-15,6-13,20h6S8.34,14.26,18.34,6.26Z" />
       <polygon id="string_1" class="cls-1" points="22.34 125.26 24.41 57.26 25.57 57.26 26.34 125.26 22.34 125.26" /></svg>

   <svg id="Balloon_2" data-name="Balloon_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48.82 125.26"><defs></defs><title>ballon</title><path id="ballon_2p" class="cls-1" d="M15.34,1.26s-18,9-15,26,19,28,19,28a22.69,22.69,0,0,0,4,1c1,0-2,2-1,3h5s2,0-1-3c0,0,18-6,22-28S30.34-3.74,15.34,1.26Z" /><path id="highlight_2" class="cls-2" d="M18.34,6.26s-15,6-13,20h6S8.34,14.26,18.34,6.26Z" />
       <polygon id="string_2" class="cls-1" points="22.34 125.26 24.41 57.26 25.57 57.26 26.34 125.26 22.34 125.26" /></svg>

   <svg id="Balloon_3" data-name="Balloon_3" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48.82 125.26"><defs></defs><title>ballon</title><path id="ballon_3p" class="cls-1" d="M15.34,1.26s-18,9-15,26,19,28,19,28a22.69,22.69,0,0,0,4,1c1,0-2,2-1,3h5s2,0-1-3c0,0,18-6,22-28S30.34-3.74,15.34,1.26Z" /><path id="highlight_3" class="cls-2" d="M18.34,6.26s-15,6-13,20h6S8.34,14.26,18.34,6.26Z" />
       <polygon id="string_3" class="cls-1" points="22.34 125.26 24.41 57.26 25.57 57.26 26.34 125.26 22.34 125.26" /></svg>

   <svg id="Balloon_4" data-name="Balloon_4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48.82 125.26"><defs></defs><title>ballon</title><path id="ballon_4p" class="cls-1" d="M15.34,1.26s-18,9-15,26,19,28,19,28a22.69,22.69,0,0,0,4,1c1,0-2,2-1,3h5s2,0-1-3c0,0,18-6,22-28S30.34-3.74,15.34,1.26Z" /><path id="highlight_4" class="cls-2" d="M18.34,6.26s-15,6-13,20h6S8.34,14.26,18.34,6.26Z" />
       <polygon id="string_4" class="cls-1" points="22.34 125.26 24.41 57.26 25.57 57.26 26.34 125.26 22.34 125.26" /></svg>

A:

It seems to be going from 50vw to 0vw then to 100vw. Hence why it looks to be going backwards.
Adding translateX(75vw) (half way intbetween 50 and 100) to the 50% mark for the moveFirst animation class worked for me.
@-webkit-keyframes moveFirst {
  0% {
    transform: translateX(50vw) rotate(10deg);
  }
  50% {
    transform: translateX(75vw) rotate(-5deg);
  }
  100% {
    transform: translateX(100vw) rotate(10deg);
  }
}


Q:

How to split array to order by date?

Hello guys this might be a silly request but I would like to have some nice order of channels in my app.
Here I am rendering my chat channels but I am wondering how can I split this objects by date using the updatedAt variable, before rendering them. Having like a sticky header showing today, yesterday or 21 feb 2019 if are older.
Any idea how can I do this by updating my code?
if (getUserChannels.length > 0) {
    return getUserChannels.map(channel => (
      <Channels
        key={channel._id}
        id={channel._id}
        name={channel.jobApplication.job.name}
        fullName={channel.jobApplication.job.business.name}
        lastName={channel.jobApplication.user.lastName}
        avatar={channel.jobApplication.job.business.logo}
        lastMessage={channel.lastMessage}
        updatedAt={channel.updatedAt}
        onPress={() => this.onChat(channel)}
      />
    ));
  }

A:

I could suggest you to split getUsersChannels before the return statment into three different arrays, and then returns all of them with a proper header. Something like this:

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {data: [
           {
               name: "Channel_1",
                date: new Date("Fri Mar 01 2019 16:20:24")
           },
           {
               name: "Channel_2",
                date: new Date("Mon Feb 25 2019 13:20:24")
           },
           {
               name: "Channel_3",
                date: new Date("Thu Feb 28 2019 17:20:24")
           },
        ]};
    }

    render() {
        const today = new Date();
        today.setHours(0,0,0,0);
        const yesterday = new Date(today -1);
        yesterday.setHours(0,0,0,0);

        const todayChannel = this.state.data.filter(channel => channel.date >= today);
        const yesterdayChannel = this.state.data.filter(channel => channel.date >= yesterday && channel.date < today);
        const olderChannel = this.state.data.filter(channel => channel.date < yesterday);

        return (
            <React.Fragment>

Today

            {todayChannel.map(el =>
{el.name}
)}

Yesterday

            {yesterdayChannel.map(el =>
{el.name}
)}

Older

            {olderChannel.map(el =>
{el.name}
)}
            </React.Fragment>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));
@import url(https://fonts.googleapis.com/css?family=Montserrat);

body {
    font-family: 'Montserrat', sans-serif;
}

You could improve this by creating a function and running through getUsersChannels just one time instead of using filter three times.


Q:

Android FaceRecognition App -- Issues with CvOpenFileStorage()

I'm working on a face-recognition application on Android using JavaCV.  I'm currently having issues accessing a facedata.xml file which will contain the data from the trained images. This is my code:
CvFileStorage fileStorage;

fileStorage = cvOpenFileStorage("/sdcard/external_sd/facedata.xml", null,         CV_STORAGE_WRITE, null);

cvOpenFileStorage returns null

I'm not sure if it is an issue with JavaCV or what i'm doing wrong. It should be pretty straight forward.

A:

I have used this, seemingly to do the exact same thing, my code is:
fileStorage = cvOpenFileStorage("/sdcard/FaceDB/facedata.xml", // filename
            null, // memstorage
            CV_STORAGE_WRITE, // flags
            null); // encoding

Just from looking at the file path I would say that is most likely wrong as it looks strange to have a folder called external_sd in your sd card.
If not it could be another problem, I found a lot of weird problems that were hard to trouble shoot with JavaCV


Q:

What Kind of Bandwidth does NFC Provide?

I'm looking into starting some projects with Android and NFC. What kind of bandwidth does NFC provide? This is assuming I had a suitable NFC reader/writer attached to an Arduino or similar, and that was communicating with an Android device held in contact with it. Lots of people suggest to initiate the communication with NFC and then do the actual data transfer via Bluetooth, but I'm wondering the bandwidth available for strictly NFC communication, just out of curiosity.

A:

The supported data-rates of the air-interface are one thing. The data-rate that you see after removing protocol overhead, waiting for eeprom writes and all the other stuff that takes time is a whole different story.
Long story short, the practical data-rate when reading from a tag or doing peer-to-peer transfers peaks around 2.5 kilobyte/second.
And depending on specific tags or the peer technology it can be a lot slower than that.


Q:

Ошибка неправильного синтаксиса около ON DUBLICATE

Использую SQLite. При запросе INSERT INTO conversations (id,chiefs) VALUES (3,123) ON DUPLICATE KEY UPDATE chiefs=123; вылетает ошибка: Ошибка при выполнении SQL запроса к базе данных 'db': near "DUPLICATE": syntax error. Что не так, кто может подсказать?

A:

Можно воспользоваться оним из следующих вариантов:
INSERT OR REPLACE:
INSERT OR REPLACE INTO conversations (id,chiefs) VALUES (3,123);

UPSERT (добавлено в версии SQLite 3.24.0 (2018-06-04)):
sqlite> .mode column
sqlite> .headers on
sqlite> create table conversations (id int primary key,chiefs int);
sqlite> insert into conversations (id,chiefs) VALUES (3,111);
sqlite> INSERT INTO conversations (id,chiefs) VALUES (3,123) ON CONFLICT(id) DO UPDATE SET chiefs=123;
sqlite> select * from conversations;
id          chiefs
----------  ----------
3           123

ON CONFLICT:
sqlite> CREATE TABLE conversations (id INT PRIMARY KEY ON CONFLICT REPLACE, chiefs int);
sqlite> INSERT INTO conversations (id,chiefs) VALUES (3,100);
sqlite> INSERT INTO conversations (id,chiefs) VALUES (3,123);
sqlite> select * from conversations;
id          chiefs
----------  ----------
3           123


Q:

Python: comparing two Counter objects with different keys

I have two strings that I want to word tokenize and then compare for differences
s1 = 'one two shmoo'
s2 = 'one one two'

My first thought was to turn them both into collections.Counter objects, wrap them in pd.Series, and subtract the difference.
import pandas as pd
from collections import Counter
def counter_series(s):
    return pd.Series(Counter(s.split(' ')))

counter_series(s2) - counter_series(s1)

But the output shows that this difference doesn't provide a count for words that aren't present in both strings:
one      1.0
shmoo    NaN
two      0.0
dtype: float64

How can you include the missing counts? E.g. in the output above shmoo should also be 1. The solution doesn't have to use pandas.

A:

Use sub with fill_value = 0:
counter_series(s2).sub(counter_series(s1), fill_value=0)

Output:
one     -1.0
shmoo    1.0
two      0.0
dtype: float64

And, you can add .abs() to get absolute value of differences:
counter_series(s2).sub(counter_series(s1), fill_value=0).abs()

Output:
one      1.0
shmoo    1.0
two      0.0
dtype: float64

However, I would use value_counts instead of import Counters from collections.
def count_series(x):
   s = pd.Series(x.split(' '))
   return s.value_counts()


Q:

JQuery dialog display according to html

The JQuery  $('#dialog').html(htmlContent) displays the html as dialog's body .
I want to display it like twitter bootstrap modal approach .
For ex:

          some content...

          some content...

Now , at time displaying dialog the 'title-bar' div content should be display in dialog's title header and same for diloag body should show 'ui-dialog-content' divs content.
So is there is any way to show dialog with this approach..

A:

This might do what you're trying to achieve:
$("#dialog").remove(); // Remove any existing dialog
var $html = '

' + headerContent + '
' +
'
' + htmlContent + '

';
// Append modal HTML to the page
$("body").append( $html );

You'll need to dress it up with some CSS of course.


Q:

IIS7 ASP - Provider cannot be found. It may not be properly installed

Getting a strange error for an old site I am trying to move to a new server - The new server is Win2008 64bit with IIS7.
This site is working perfectly on an IIS6 Win2003 server, but I have just moved it over and run the site but I get the following error
Provider cannot be found. It may not be properly installed.

From looking around people seem to to just say enable 32 bit applications in the App pool and it will be fine?  Unfortunately I did this and it didn't work?  It seems to be falling over here
'*************************************************************************
'Open Database Connection
'*************************************************************************
function openDB()
    on error resume next
    set connTemp = server.createobject("adodb.connection")
    connTemp.Open connString
    if err.number <> 0 then
        dim errMsg
        errMsg = "" _
            & "Module : scripts/_INCappDBConn_.asp : openDB()

" _
            & "Number : " & err.number & "

" _
            & "Page : "   & Request.ServerVariables("PATH_INFO") & "

" _
            & "Desc : "   & err.Description
        call errorDB("",errMsg)
    end if
    on error goto 0
    if UCase(dbLocked) = "Y" then
        call errorDB("" & LangText("ErrStoreClosed","") & "","")
        closeDB()
    end if
end function

Just wondering if anyone can shed any light on what is going in?

A:

I know that this is fairly basic - but did you start by making sure that in IIS has ASP installed?  Classic ASP isn't installed by default on IIS7.  Go to Programs and Features in Control Panel and click Turn Windows features on and off. Navigate down the tree of features and make sure ASP is checked.
If you haven't already gone down this path - it's probably the issue.


Q:

Would angularjs work locally?

Would pure angular and css/html work in a local machine?
In my case, I'm not getting any errors, but at the same time the messages won't show any output. Any idea why?
Some of the code:
<head>
    <link rel="stylesheet" type="text/css" href="/C:somethinghere\style.css">

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="/C:somethinghere\app.js"></script>

</head>

<body class="parent" ng-app="myApp">
{{ messages }}
</div>

app:
var myApp = angular.module('myApp',[]);

myApp.controller('GreetingController', ['$scope', function($scope) {
    $scope.messages = "hello";
    $scope.ratings = [{test: 22},{test: 99}];
}]);

NOTE: the links are correct, i just changed the links to now show my username.

A:

The answer is: Yes, angular works on a local machine.
The problem in your code is that you are not assigning the controller to the view, you are missing the ng-controller="GreetingController" inside your view.
So to fix that, just enclose {{ messages }} inside a div tag with ng-controller attribute.
A solution might look like that:
<body class="parent" ng-app="myApp">
   <div ng-controller="GreetingController">
      {{ messages }}
   </div>
</body>

Also, please notice that in your HTML, you opened a <body> tag but you closed it with </div> tag. You missed the </body> enclosing tag and you missed a <div> opening tag.
Another small tip:
Try to use relative paths instead of absolute paths when you load CSS/JS files.
Just write <link href='styles/style.css'> instead of <link href='c:/.../styles/style.css'>. This path assumes that you have a styles folder in the same folder that your HTML file exists.


Q:

Check string contains only alphabets in C# and other allowed charaters are: ".", whitespace, ","

How do I check that string does not contain only alphabets in C#, and other allowed charaters are: dot: ".", whitespace, and comma: ","
Regex regex = new Regex("Regex Pattern");
bool result = regex.IsMatch(string);
if(result)
 Messagebox.Show("String does not contain alphabets");

Examples:
ABC1 = false
ABC = true
ABC ABC = true
abc abc = true
A. B. ABC = true
The reason is because I have a field which contains people's names. Generally in these formats:
First
First Last
First Middle Last
F. M. Last
Title. F. M. Last
So, I want to validate those using regex.

A:

Try this
var regex = new Regex(@"(?i)^[a-z.,\s]+$");
bool res =  regex.IsMatch(subject);


Q:

Create url object from object in angular

I am trying to set a url with an object I have created (in angular). It is an object array I would let to set on the url string to do a kind of "save state".
I have my object like -
  [{"key1" : true}, {"key2" :  false}];

And I basically want to set that as a url object so I can get a custom url string for my state - which would then be interpreted on landing to change a state (so users can send custom urls).
So before when it was just one object, I could pass the object and do something like
$scope.myObject = true;
$location.search($scope.myObject);

But I am trying to combine a few of the objects into one big object so I can keep track of a few different states in one place (in a factory). The problem I am having is I cannot seem to get it to work if the the location.search parameter is an array of objects. I'm getting an "undefined is not a function" and it's pointing inside angular.
Are there any tricks to this? Could use some help, this is my first time trying this. Also, I'm trying to change the url without refreshing. Thanks!

A:

Instead of:
[{"key1" : true}, {"key2" :  false}];

Try:
{"key1" : true, "key2" :  false};

That is the correct JSON syntax for "one big object".
To go from an array of objects to one big object, you must iterate through the array and build a new object with the properties uncovered from the array:
var newObj = {};
var oldArray = [{"key1" : true}, {"key2" :  false}];
for (var i = 0; i < oldArray.length; i++) {
    var obj = oldArray[i];
    for (param in obj) {
        newObj[param] = obj[param];
    }
}
// newObj is now one big object.


Q:

looping through phone fields of input type text jquery

I have a form containing 5 - 6 phone fields in the form of text fields. All these phone fields have a common class "phoneclass". So I need to iterate through all these phone fields and get the value of the individual text fields(area code, local 3 and local 4 ) once I have these values, I have to validate each of these values.
I have created a fiddle for reference. I have to only use the phoneClass for getting the value of the text fields. Without using the individual field id's I need to get the value of these 3 text fields using phoneClass and then I can put that into an array and then manipulate it.
Can anyone please help me how i can do this?
http://jsfiddle.net/jUQYr/79/

Owner Phone:

  <input type="text" id="owner_area_code" name="owner_area_code" minlength="3" maxlength="3" title="Owner number has either been left blank or the data entered was invalid" style="width: 60px" />
  -
  <input type="text" id="owner_local3" name="owner_local3" minlength="3" maxlength="3" title="Owner number has either been left blank or the data entered was invalid" style="width: 60px" />
  -
  <input  type="text" id="owner_local4" name="owner_local4" minlength="4" maxlength="4" title="Owner number has either been left blank or the data entered was invalid" style="width: 60px" />
  Ext.
  <input  type="text" id="owner_extn" name="owner_extn" maxlength="5" style="width: 40px"/>
  <input type="hidden" id="owner_phone" />

    Owner Phone1:

  <input type="text" id="owner_area_code1" name="owner_area_code1" minlength="3" maxlength="3" title="Owner number has either been left blank or the data entered was invalid" style="width: 60px" />
  -
  <input type="text" id="owner_local31" name="owner_local31" minlength="3" maxlength="3" title="Owner number has either been left blank or the data entered was invalid" style="width: 60px" />
  -
  <input  type="text" id="owner_local41" name="owner_local41" minlength="4" maxlength="4" title="Owner number has either been left blank or the data entered was invalid" style="width: 60px" />
  Ext.
  <input  type="text" id="owner_extn1" name="owner_extn1" maxlength="5" style="width: 40px"/>
  <input type="hidden" id="owner_phone1" />

    <input type="submit" id="submitBtn"/>

Thanks in advance...

A:

Try like
1) loop through each element with class name phoneclass.
2) Within each div with class phoneclass, pick iterate their children using find() method.
 $('.phoneclass').each(function () {
        $(this).find('input').each(function (index, value) {
            console.log($(value).val());
        });
    });

JSFiddle


Q:

Get names from different table in child-grandparent relationship

I have three tables:
CREATE TABLE category (id integer, parent_id integer);
CREATE TABLE category_name (id integer, name (varchar(20), language_id);
CREATE TABLE language (language_id integer, language_name);

I am able to get the child-parent-grandparent relationship with the following statement:
SELECT c.id, c.parent_id, p.parent_id
FROM category AS p, category AS c
WHERE p.id = c.parent_id AND p.parent_id IS NOT NULL;

But I need to get the names as well for both child, parent and grandparent from the table category_name where the language_id = 3
The query to get the name, without the child-parent-grandparent relation would be something like this:
SELECT c.id, n.name
FROM category c
LEFT JOIN category_name n ON c.id = n.id AND language_ID = 3

But how can the two statements be joined into one, so that I actually get three name columns out?
That is, each row should have the IDs and names for itself, its parent and its grandparent (if the latter exist)
How can I proceed to make this combined query?
Here are the tables and some sample data:
CREATE TABLE category (id integer, parent_id integer);
INSERT INTO category VALUES (1,null);
INSERT INTO category VALUES (2,null);
INSERT INTO category VALUES (3,1);
INSERT INTO category VALUES (4,2);
INSERT INTO category VALUES (5,2);
INSERT INTO category VALUES (6,4);
INSERT INTO category VALUES (7,2);
INSERT INTO category VALUES (8,7);
INSERT INTO category VALUES (9,7);
INSERT INTO category VALUES (10,7);
INSERT INTO category VALUES (11,3);

CREATE TABLE category_name (id integer, name varchar(20), language_id integer);
INSERT INTO category_name VALUES (1, 'CDs', 3);
INSERT INTO category_name VALUES (2, 'Books', 3);
INSERT INTO category_name VALUES (3, 'Music', 3);
INSERT INTO category_name VALUES (4, 'Novels', 3);
INSERT INTO category_name VALUES (5, 'Childrens books', 3);
INSERT INTO category_name VALUES (6, 'European', 3);
INSERT INTO category_name VALUES (7, 'Science', 3);
INSERT INTO category_name VALUES (8, 'Math', 3);
INSERT INTO category_name VALUES (9, 'Informatics', 3);
INSERT INTO category_name VALUES (10, 'Physics', 3);
INSERT INTO category_name VALUES (11, 'Classic', 3);
INSERT INTO category_name VALUES (1, 'CDs', 4);
INSERT INTO category_name VALUES (2, 'Livres', 4);
INSERT INTO category_name VALUES (3, 'Musique', 4);
INSERT INTO category_name VALUES (4, 'Romans', 4);

CREATE TABLE language (language_id integer, language_name varchar(15));
INSERT INTO language (3, 'English');
INSERT INTO language (4, 'French');

Here is how I would like to get out some sample (for c.id = 5 and 8):
c.id | c.parent_id | p.parent_id | nameChild          | nameParent | nameGrandparent
5    | 2           | null        | 'Children's books' | 'Books'    | null
8    | 7           | 2           | 'Math'             | 'Science'  | 'Books'

I have tried the following code, but it gives
Error Code: 1054. Unknown column 'p.parent_id' in 'on clause'
SELECT c.id, c.parent_id, p.parent_id, nc.name, np.name, ng.name
FROM category1 AS p, category1 AS c
LEFT JOIN category_name1 AS nc ON c.id = nc.id AND nc.language_id = 3
LEFT JOIN category_name1 AS np ON c.parent_id = np.id AND np.language_id = 3
LEFT JOIN category_name1 AS ng ON p.parent_id = ng.id AND ng.language_id = 3 AND p.parent_id IS NOT NULL
WHERE p.id = c.parent_id AND p.parent_id IS NOT NULL;

I don't have a problem getting out the child and parent names, but the grandparent name seems to be out of my grasp :(
And below is the code working!
SELECT x.id, x.pid, x.gpid,
nc.name childName, np.name parentName, ng.name gpName
FROM
(SELECT  c.id , c.parent_id AS pid, p.parent_id AS gpid
FROM
category AS c
LEFT JOIN category AS p ON p.id = c.parent_id
) x

LEFT JOIN category_name AS nc ON x.id = nc.id AND nc.language_id = 3
LEFT JOIN category_name AS np ON x.pid = np.id AND np.language_id = 3
LEFT JOIN category_name AS ng ON x.gpid = ng.id AND ng.language_id = 3;

A:

Something like this should work:
SELECT
c.id AS childId, cname.name AS childName,
p.id AS parentId, pname.name AS parentName,
g.id AS grandparentId, gname.name AS grandparentName
FROM category p
INNER JOIN category c ON (p.id = c.parent_id)
LEFT JOIN category g ON (p.parent_id = g.id)
LEFT JOIN category_name cname ON (c.id = cname.id AND cname.language_ID = 3)
LEFT JOIN category_name pname ON (p.id = pname.id AND pname.language_ID = 3)
LEFT JOIN category_name gname ON (g.id = gname.id AND gname.language_ID = 3)
WHERE p.parent_id IS NOT NULL;

I feel like there should be a neater way to do this but can't see it at the moment.


Q:

Single configuration for multiple projects with MSBuild?

i am looking for possibility of building with MSBuild in a way, where i can use one configuration for multiple projects.
Here is configuration i want to share:
  <ItemGroup>
    <MySourceFiles Include="$(TargetDir)\*.*"/>
  </ItemGroup>

  <Target Name="Prepare" BeforeTargets="BeforeBuild">
    <Message Text="Preparing folders..." Importance="high" />
    <MakeDir Directories="$(SolutionDir)Build\$(Configuration)" />
    <MakeDir Directories="$(SolutionDir)Build\$(Configuration)\Plugins" />
    <Message Text="Folders prepared..." Importance="high" />
  </Target>

  <Target Name="AfterBuild">
    <Message Text="$(AssemblyName) - Copying output" Importance="high" />
    <Copy SourceFiles="@(MySourceFiles)" DestinationFolder="$(SolutionDir)Build\$(Configuration)" SkipUnchangedFiles="false" />
    <Message Text="$(AssemblyName) - Copying finished" Importance="high" />
  </Target>

As you can see. It will simply check/create Build/Debug folder and copy all compiled files there. And this i need for multiple projects.
Is this possible to have in some external xml or proj file and load configuration and load it from there? I want to prevent possible problems with updates in future.
Thanks for help

A:

You can use
<Import Project="myProj.targets">

in every project, where myProj.targets contains the code as you show.
However it is probably better to refer to ProjectDir and the likes instead of SolutionDir since not all projects have a corresponding solution, and even if they do you might want to use them as if they do not. Anyway, that way your project is self-contained and does not need a solution.


Q:

How can I make an older commit HEAD in Git?

I'm still trying to learn the (basic?) finer points of Git and have managed to get myself into trouble. I realized that I made some mistakes on HEAD, checked out an older commit and started coding from there. When I attempt a push I'm told that my current commit is behind and I need to merge with HEAD. Git recommends "git pull". However, HEAD has the code I want to ignore. How do I solve this problem? Thanks so much for the help.
Flowchart:
-------- HEAD (bad) ---------------------- + (behind conflict, requires
     \                                    /   merge with HEAD, which is
      \------- Current commit (good) ----/    bad and needs to be ignored)

A:

Here is what you can do:
git checkout <branch-to-modify-head>
git reset --hard <commit-hash-id-to-put-as-head>
git push -f

If you don't force the push, git will throw this error: Updates were rejected because the tip of your current branch is behind.
Note that this will tamper your git history, so another way of doing this is revert each commit you don't want. That way you retain your history:
git revert commit-id

Cheers

A:

If your repository isn't being used by other people, you can safely do git push -f to overwrite the remote branch.

A:

The way I do it is:
git reset --hard <commit-SHA>
git push origin HEAD:<name-of-remote-branch>

It's the way git recommends and doing git push -f might be a little problematic for everyone else in the development team


Q:

antlr identifier name same as pre-defined function name cause MismatchedTokenException

I have defined a ANTLR grammer:
grammar test5;

stats_statement
:
    STATS IDENT ASSIGN_SYM functions_stats

;

functions_stats

:   COUNT LPAREN IDENT RPAREN
;

STATS
:   'STATS'
;

COUNT
:   'count'
;

IDENT
:   (LETTER | '_') (LETTER | DIGIT | '_')*
;

ASSIGN_SYM
: ':='
;

COMMA_SYM
: ','
;

SEMI_SYM
: ';'
;

LPAREN
: '(' ;

RPAREN
: ')' ;

fragment
LETTER : ('a'..'z' | 'A'..'Z') ;

fragment
DIGIT : '0'..'9';

which has one build-in function "count". But if I use the following test string:
STATS count:=count(col1)

the parser will return an error saying:
mismatched input 'count' expecting IDENT

any clue and/or hints on how to fix this problem?
Thanks
Charles

A:

Create an ident rule that matched both IDENT and COUNT and use that rule in your parser rules (instead of using IDENT):
stats_statement
 : STATS ident ASSIGN_SYM functions_stats
 ;

functions_stats
 :   COUNT LPAREN ident RPAREN
 ;

ident
 : COUNT
 | IDENT
 ;


Q:

Show spelling suggestions when StackEdit.io spell checker says word is wrong

I am writing a document in Google Drive (I still call it Google Docs) using the StackEdit.io editor.
I have Google Chrome's spell checker disabled. StackEdit.io provides one and I like it that way. Misspelled words are underlined, but sometimes I can't figure out my mistake (English is not my mother tongue).

Is there a way in StackEdit.io to show the spelling suggestions for a misspelled word?

A:

I'm the developer.
It supposed to work, but it's pretty buggy, on Chrome particularly. There is an open issue on GitHub about that and on ACE repo as well.
As a workaround, you can use the "Light mode" (Settings>Advanced) which will replace the ACE editor by a textarea.


Q:

What does MSC in "// appease MSC" comments mean?

I occasionally run across // appease MSC in C++ comments, e.g. here:
const int& Array::operator[](int offSet) const
{
  int mysize = GetitsSize();
  if (offSet >= 0 && offSet < GetitsSize())
    return pType[offSet];
  throw xBoundary();
  return pType[offSet]; // to appease MSC!
}

What does MSC stand for ?

A:

The author means Microsoft's compiler, more formally known as MSVC.


Q:

Dotnet Core WebAPI IIS Express base URL

I've got a webapi that runs in production on a Virtual Directory on ISS, end result is something like api.companyname.com/APINAME/
Now I need to be able to locally test the API using either dotnet run or IIS Express with a baseUrl such as the above, the end result would be something like localhost:5555/APINAME/.
My problem is that I can't change anything in code to have it work and I can't find anything in the web as to where I can go to configure this. I've tried changing the LaunchSettings.json file as well.

A:

There are two different things you are trying to achieve.
To (re)define the listening endpoint(s), you can use the --urls parameter of dotnet the following way:
dotnet <yourdll.dll> --urls "http://*:5000"

You can also provide more than one endpoint (i.e. https, ipv6,...)
Try it out now.
My guess it, that this is all you need to do, and the App already has the path configured. If not, read on.
The other thing is the path base.
That ("/myapp/") cannot be configured this way. To do that, you need to alter the source code. Best practice is to configure your AppBuilder like that:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UsePathBase(...);
        ....

If you cannot edit the source code, you could wrap your own application around the dll. But thats going to far to be answered here.
Please accept as answer when it worked, thank you.
Have Fun!


Q:

Will one with record of unfinished PhD on his/her CV be doubted of his/her ability?

A PhD student of my advisor (I am a master student), having been enrolled the doctorate program for less than a year, is now unsure about whether or not to finish it.
One of his concerns is that if he continues, but eventually quits the doctorate program, and applies for a normal job, the future interviewer, during interview, may suspect his lack of ability due to the record of an unfinished PhD program.
However, if he does not write on his CV about the years during PhD program, the interviewer may further question about the absent years.
So, does a record of an unfinished PhD program makes employers doubt a person's ability? Or are there other negative consequences in it (besides, of course, the opportunity cost of the time interval)?
In addition to helping me reassure him, such information also helps me to decide whether to get a PhD in the future.
(Not being anglophone, if I misused some terms in English please correct me.)

Edit: Wow, to my surprise, this is probably the most popular question among SE questions I have asked (in all sites). I appreciate every answer and have read all of them, but chose Mr Romik for being the earliest among all good answers.

A:

does a record of an unfinished PhD program makes employers doubt a person's ability?

I very much wish it were not so, but the honest answer is yes. Employers, within the restricted context of reviewing job applications, are forced to rely on very partial and superficial information given to them in CVs and job applications. Moreover, they are given huge numbers of applications to select from under time pressure. They respond to this in a way that I think is completely rational, but nonetheless extremely frustrating (to them as well as to the candidates), which is to assign a highly inflated significance to each piece of information given to them: positive things appear much more positive than they should, and negative things appear much more negative than they should.
In particular, both an unfinished PhD and a long period of seeming inactivity in one's CV are likely to be perceived at least somewhat negatively, certainly if they are unaccompanied by an explanation, and possibly (to a smaller extent) even when an explanation is provided. It wouldn't kill someone's chances of getting a job, and can be overcome by many other positive things one has to say about themselves, but I'm pretty sure it will have at least a small negative effect.

A:

There are many reasons that people do not finish doctoral programs other than incompetence or lack of motivation. For instance, one may become disenchanted with the soft deadlines of academia and would like to work in a non-academic setting, where deadlines and tasks may be completed in a more timely manner. Also, one may like the income security that a non-academic salary may provide, rather than having to chase after grants for summer pay. Yet another example is that one may like fixed hours in their employment, rather than spend evenings, weekends and sometimes holidays working on manuscripts or grading papers. So, it would be advisable to include the doctoral studies to demonstrate graduate training (especially if it is in the area of the non-academic jobs one would apply for) and give a reasonable and respectable explanation for leaving academia. I often suggest to non-academic job candidates in this position to write their reasons for leaving academia in their cover letter so that there aren't any unanswered questions that may damage their ability to even getting to the interview.

A:

For an industry job, I don't think it is a big problem (unless it is a research position where PhD is required).
It is very likely that the candidate found out that he/she does not like to do research, and it might have taken them a while, like it took me.
Of course, I have no idea of what kind of opportunities I would have had if "PhD" in my resume did not have "abd" next to it, but from questions that I had about it and amount of time interviewers spend on those question (if they asked at all) it seemed like a fairly minor point. My previous experience and technical skills get much, much more attention.
And just to be clear I started my first job, while I was still in the PhD program.
I do believe that it is a negative, but a small one, so if your friend does not have passion for research, they should get out, ideally get a job first and then get out.
Also, they should put PhD experience on the resume, being part of PhD program is a plus, this is a lot better than having unexplained gap.


Q:

Exceptions after changing to developer mode

After I changed to developer mode, I can't view the main page, and get the following exception (Magento 2.1.2)
Invalid XML in file x.com/app/code/Ves/ImageSlider/etc/widget.xml:
Element 'description': This element is not expected. Expected is ( value ).

The issue is labelled to be at this area of the xml file
<parameter name="autoplay_timeout" xsi:type="text" visible="true">
    Autoplay Timeout
    <depends><parameter name="autoplay" value="1" /></depends>
    <description translate="true"><![CDATA[Default: 3000]]></description>
    <value>3000</value>
</parameter>
<parameter name="autoplay_speed" xsi:type="text" visible="true">
    Autoplay Speed
    <depends><parameter name="autoplay" value="1" /></depends>
    <description translate="true"><![CDATA[Default: 800]]></description>
    <value>800</value>
</parameter>

A:

move the description tag above the depends tag.
In the XSD schema Magento/Widget/etc/widget.xsd the parameter type is defined as this
 <xs:complexType name="parameterType" abstract="true">
    <xs:annotation>
        <xs:documentation>
            Abstract type which is parent of all parameters. Contains attributes
            and elements common across all parameter types.
        </xs:documentation>
    </xs:annotation>
    <xs:sequence>
        <xs:element name="label" type="translatableType" minOccurs="0" maxOccurs="1" />
        <xs:element name="description" type="translatableType" minOccurs="0" maxOccurs="1" />
        <xs:element name="depends" type="dependsType" minOccurs="0" maxOccurs="1" />
    </xs:sequence>
    <xs:attribute name="name" type="xs:NMTOKEN" use="required" />
    <xs:attribute name="visible" type="xs:boolean" />
    <xs:attribute name="sort_order" type="xs:int" />
    <xs:attribute name="required" type="xs:string" />
</xs:complexType>

focus on this part
    <xs:sequence>
        <xs:element name="label" type="translatableType" minOccurs="0" maxOccurs="1" />
        <xs:element name="description" type="translatableType" minOccurs="0" maxOccurs="1" />
        <xs:element name="depends" type="dependsType" minOccurs="0" maxOccurs="1" />
     </xs:sequence>

This means that the element parameter supports the child elements listed in the sequence tag in this order.  label, description, depends.
Side node: Ignore the fact that you don't see the value tag in here. This is added later in the same file depending on the value of the parameter type


Q:

Controller action in IFrame "src" attribute - YII Framework

I am trying to call the controller action in IFrame src,
$('#iframe').attr('src', 'controller/action');

How to call the controller action in the above line inside JavaScript function ?
 <?php
 echo CHtml::imageButton(Yii::app()->request->baseUrl.'/images/new.jpg'
,array('id'=>'reflist-button'
,'style'=>'display:inline-block',
'onclick'=>'$("#cru-frame-RefNew").attr("src","-----How to call controller action -------");
$("#RefList-New").dialog("open"); return false;'));?>

A:

try this
// save your url in a varible first
$myPath=Yii::app()->createUrl('controller/action');

and then change this
'onclick'=>"$('#cru-frame-RefNew').attr('src',$myPath);
$('#RefList-New').dialog('open'); return false;"


Q:

mysterious difference between rake test and ruby

Here is the mysterious:
I have a scope which looks like this (in Image.rb)
  scope :moderate_all, delegates.where("moderation_flag = #{$moderation_flags[:not_moderated]}")

Note that delegates is another scope that I am defining before moderate_all
When I leave it like this, I can run my test that checks if an image has been "checked-out" it is not available anymore. I don't put the code of the test, because it does not matter actually.
With this code, when I run "rake test" it fails, but if I do "ruby test/unit/image_test.rb" it works! I was thinking I am starting to have a bad day. Then I tried
  scope :moderate_all, lambda {
    delegates.where("moderation_flag = #{$moderation_flags[:not_moderated]}")
  }

And "rake test" passes!
So my problem is solved, but why?

A:

$moderation_flags looks like a global, and  the value of the named scope depends on it. My guess is that rake test loads the class before the global is ready, but invoking the test directly goes the other way.
Introducing the lambda causes the where clause to be evaluated when the scope is used, so it always happens late when the global is ready.


Q:

javascript - array does not get set back to [] (blank)

I have this code and every time that the first for loop starts again I want it to reset the array to blank as it is using a new user, but I get an out put with all the values in one array.
var items = [];
    for (var i = 0; i < userArray.length; i++) {

        items.length = 0;
        for (var i2 = 0; i2 < test.length; i2++) {

            var UserFavourite = Parse.Object.extend("UserFavourite");
            var queryUserFav = new Parse.Query(UserFavourite);
            queryUserFav.equalTo('item', test[i2].get('item'));
            queryUserFav.equalTo('school', test[i2].get('school'));
            queryUserFav.equalTo('user1', userArray[i])
            queryUserFav.find().then(function(res) {

                    for (var i3 = 0; i3 < res.length; i3++){
                        var item = res[i3];
                        var itemName = item.get('item');
                        items.push(itemName);
                        if (items !== []) {
                            console.log(items.toString()+" + ")
                        }
                    }

            });

        }
    }

userArray.length is equal to 2 and test.length is equal to 20. If you were wondering. And when it get to the first for loop I want the array to be set back to blank but it isn't?
Thanks for the help in advance.

A:

I thnk you should use set this:
items.length = 0

because items = []
creates a new array which is not the same.
Also add some promises to make the async requests wait


Q:

XSL Transform - select node id by string content

I have xml like this
    <mets:mets xmlns:mets="http://www.loc.gov/METS/">
  <mets:fileSec>
    <mets:fileGrp ID="REP1">
      <mets:file ID="FL1">
        <mets:FLocat LOCTYPE="URL" xlin:href="1.jpg" xmlns:xlin="http://www.w3.org/1999/xlink"/>
      </mets:file>
    </mets:fileGrp>
    <mets:fileGrp ID="REP2">
      <mets:file ID="FL2">
        <mets:FLocat LOCTYPE="URL" xlin:href="1.tif" xmlns:xlin="http://www.w3.org/1999/xlink"/>
      </mets:file>
    </mets:fileGrp>
    <mets:fileGrp ID="REP3">
      <mets:file ID="FL3">
        <mets:FLocat LOCTYPE="URL" xlin:href="2.jpg" xmlns:xlin="http://www.w3.org/1999/xlink"/>
      </mets:file>
    </mets:fileGrp>
  </mets:fileSec>
</mets:mets>

I want to get as output IDs only files with jpg extention -> FL1, FL3.
I have problems with my xsl file :
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:mets="http://www.loc.gov/METS/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:mods="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-0.xsd"
    exclude-result-prefixes="xlin">
    <xsl:output method="html" omit-xml-declaration="yes" indent="yes" />

    <xsl:template match="/">
        <xsl:for-each select="//mets:fileSec/mets:fileGrp/mets:file">
            <xsl:variable name="currentID" select="@ID" />
            <xsl:for-each select="//mets:fileSec/mets:fileGrp/mets:file/mets:FLocat">
                <xsl:variable name="testVariable" select="@xlink:href" xmlns:xlink="http://www.w3.org/1999/xlink" />
                <xsl:choose>
                    <xsl:when test="contains($testVariable, '.jpg')"><xsl:value-of select="$currentID"/>,</xsl:when>
                 </xsl:choose>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

But after transform I get error output as : FL1,FL1,FL2,FL2,FL3,FL3,
Please, help me with XSL.
Thank you!

A:

Would something like this work for you?
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:mets="http://www.loc.gov/METS/"
xmlns:xlin="http://www.w3.org/1999/xlink">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/">
    <xsl:for-each select="mets:mets/mets:fileSec/mets:fileGrp/mets:file[contains(mets:FLocat/@xlin:href, '.jpg')]">
        <xsl:value-of select="@ID"/>
        <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
        </xsl:if>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>


Q:

Angularjs with jquery auto complete not working

I am trying for the past 5 hours without success...
 Here is the code..
In View:
<input type="text" ng-model="foo" auto-complete/>Foo = {{foo}}

In controller:
    myapp.directive('autoComplete', function(autoCompleteDataService) {
    return {
        restrict: 'A',
        link: function(scope, elem, attr, ctrl) {
            elem.autocomplete({
                source: autoCompleteDataService.getSource(), //from your service
                select: function( event, ui ) {
                    scope.foo= ui.item.label;
                    scope.$apply;
                },
                change:function (event, ui) {
                    if (ui.item === null) {
                        scope.foo = null;
                    }
                },
                minLength: 2
            });
        }
    };
});

    myapp.factory('autoCompleteDataService', [function() {
    return {
        getSource: function() {
            return ['apples', 'oranges', 'bananas'];
        }
    }
}]);

Here is the issue...
The selected item is getting into the input box, but foo variable next to input box is not updating.
Where is the mistake.
Please suggest...

A:

Change
scope.$apply;

to
scope.$apply(function(){
    scope.foo= ui.item.label;
});


Q:

How to optimize this pandas iterable

I have the following method in which I am eliminating overlapping intervals in a dataframe based on a set of hierarchical rules:
def disambiguate(arg):

    arg['length'] = (arg.end - arg.begin).abs()

    df = arg[['begin', 'end', 'note_id', 'score', 'length']].copy()

    data = []
    out = pd.DataFrame()
    for row in df.itertuples():

        test = df[df['note_id']==row.note_id].copy()

        # get overlapping intervals:
        # https://stackoverflow.com/questions/58192068/is-it-possible-to-use-pandas-overlap-in-a-dataframe
        iix = pd.IntervalIndex.from_arrays(test.begin.apply(pd.to_numeric), test.end.apply(pd.to_numeric), closed='neither')
        span_range = pd.Interval(row.begin, row.end)
        fx = test[iix.overlaps(span_range)].copy()

        maxLength = fx['length'].max()
        minLength = fx['length'].min()
        maxScore = abs(float(fx['score'].max()))
        minScore = abs(float(fx['score'].min()))

        # filter out overlapping rows via hierarchy
        if maxScore > minScore:
            fx = fx[fx['score'] == maxScore]

        elif maxLength > minLength:
            fx = fx[fx['length'] == minScore]

        data.append(fx)

    out = pd.concat(data, axis=0)

    # randomly reindex to keep random row when dropping remaining duplicates: https://gist.github.com/cadrev/6b91985a1660f26c2742
    out.reset_index(inplace=True)
    out = out.reindex(np.random.permutation(out.index))

    return out.drop_duplicates(subset=['begin', 'end', 'note_id'])

This works fine, except for the fact that the dataframes I am iterating over have well over 100K rows each, so this is taking forever to complete. I did a timing of various methods using %prun in Jupyter, and the method that seems to eat up processing time was series.py:3719(apply) ... NB: I tried using modin.pandas, but that was causing more problems (I kept getting an error wrt to Interval needing a value where left was less than right, which I couldn't figure out: I may file a GitHub issue there).
Am looking for a way to optimize this, such as using vectorization, but honestly, I don't have the slightest clue how to convert this to a vectotrized form.
Here is a sample of my data:
begin,end,note_id,score
0,9,0365,1
10,14,0365,1
25,37,0365,0.7
28,37,0365,1
38,42,0365,1
53,69,0365,0.7857142857142857
56,60,0365,1
56,69,0365,1
64,69,0365,1
83,86,0365,1
91,98,0365,0.8333333333333334
101,108,0365,1
101,127,0365,1
112,119,0365,1
112,127,0365,0.8571428571428571
120,127,0365,1
163,167,0365,1
196,203,0365,1
208,216,0365,1
208,223,0365,1
208,231,0365,1
208,240,0365,0.6896551724137931
217,223,0365,1
217,231,0365,1
224,231,0365,1
246,274,0365,0.7692307692307693
252,274,0365,1
263,274,0365,0.8888888888888888
296,316,0365,0.7222222222222222
301,307,0365,1
301,316,0365,1
301,330,0365,0.7307692307692307
301,336,0365,0.78125
308,316,0365,1
308,323,0365,1
308,330,0365,1
308,336,0365,1
317,323,0365,1
317,336,0365,1
324,330,0365,1
324,336,0365,1
361,418,0365,0.7368421052631579
370,404,0365,0.7111111111111111
370,418,0365,0.875
383,418,0365,0.8285714285714286
396,404,0365,1
396,418,0365,0.8095238095238095
405,418,0365,0.8333333333333334
432,453,0365,0.7647058823529411
438,453,0365,1
438,458,0365,0.7222222222222222

A:

I think I know what the issue was: I did my filtering on note_id incorrectly, and thus iterating over the entire dataframe.
It should been:
    cases = set(df['note_id'].tolist())

    for case in cases:
        test = df[df['note_id']==case].copy()
        for row in df.itertuples():

            # get overlapping intervals:
            # https://stackoverflow.com/questions/58192068/is-it-possible-to-use-pandas-overlap-in-a-dataframe
            iix = pd.IntervalIndex.from_arrays(test.begin, test.end, closed='neither')
            span_range = pd.Interval(row.begin, row.end)
            fx = test[iix.overlaps(span_range)].copy()

            maxLength = fx['length'].max()
            minLength = fx['length'].min()
            maxScore = abs(float(fx['score'].max()))
            minScore = abs(float(fx['score'].min()))

            if maxScore > minScore:
                fx = fx[fx['score'] == maxScore]

            elif maxLength > minLength:
                fx = fx[fx['length'] == maxLength]

            data.append(fx)

        out = pd.concat(data, axis=0)

For testing on one note, before I stopped iterating over the entire, non-filtered dataframe, it was taking over 16 minutes. Now, it's at 28 seconds!


Q:

adding static time interval panel in Grafana Prometheus

I am trying to add a static panel to show total number of request for the current year in grafana prometheus
I am using sum(http_server_requests_seconds_count{}) for the current interval selection in grafana
Is any way i can do that for current year

A:

Use increase(http_server_requests_seconds_count[1y]). But it's not going to be fast. Or easy on Prometheus. Also, make sure you're using it as instant query (the Instant switch below the query textarea) or it's going to be even worse.


Q:

Can't display BLOB stored in database

I've got an problem when I want to convert an image in blob format stored in my database.
When iç just echo $content I can actualy see the blob file printed out so there is no problem with my queries.
The problem is that my code only displays an broken image instead of the Image in the database.
Does anyone know how to display the image properly?
Thanks in advance
        $content = mysql_result($result,$i,'Image');

        echo '<img src="data:image/jpeg;base64,<?php echo base64_encode($content); ?>" width="100" />';

A:

The best way to do it would be to use a separate page to display the image like the following:
<?php
header("Content-Type: image/jpeg");
// Do your query
$content = mysql_result($result,$i,'Image');
echo $content;
?>

Then in another page do

It's also answered in this question: How to display an BLOB image stored in MySql database?


Q:

MVC 3 ninject bind lazy evaluated parameter

I want o bind my controller with a parameter that is lazy evaluated.
 protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        try
        {
            return controllerType == null
                       ? null
                       : (IController) _ninjectKernel.Get(controllerType);
        }
        catch (Exception ex)
        {
            throw;
        }
    }

And I have the next binding:
_ninjectKernel.Bind<IFilesRepository>().To<FilesManager>().WithConstructorArgument("storageFolderAbsolutePath", c => c.ToString());

The problem is at the lambda function. I want to return Server.MapPath("/") ... but I don't have the request context in the c object. How can I sent it?

A:

I'm not overly familiar with Ninject, but you should be able to register a provider with the container to be able to resolve a HttpContextBase. By doing so, the IFilesRepository can now take a HttpContextBase as a constructor argument, which will be injected by the container, using the provider, when creating an instance of IFilesRepository.
To register a provider (using a delegate to resolve the service),
Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current));

Be aware however, that the life style of an IFilesRepository would most likely need to change to a "per Web Request" lifestyle, as the HttpContext.Current is created per web request, so you wouldn't want to go holding onto that in an IFilesRepository that had a longer life style. You may want to abstract out the "mapping paths" functionality so that you can have an IFilesRepository with a longer lifestyle.


Q:

SQL - Categorize employee entrance time

I have a SQL table where I store every employee IN and OUT timestamp.
There are employees that punch the card more than once (because they don't hear that the card was read), other employees that punch the card for some reason (maybe they meet a friend and stay talking for 1 or 2 min) they wait some minutes before they punch again to access the turnstile.
The sample SQL table data looks like this (3 employees only):

Now, I would like to categorize each time to know what timestamp is correct, etc.
For example:

In you see EMP_01 (Yellow record) the LAST_LEAVE technically was 00:38:21 but it's obvious that the employee punch twice that's why the really LAST_LEAVE was 00:38:16.
But, EMP_04 has some other issues, if you see the last 4 records, he has 3 IN's in a row, but those aren't because he didnt hear the beep from the sensor, those are because he leave from other door without punch who knows when, but we know he enter 1 hour after again, and so on.
So, any recommendation on how to deal with this? and how to assign my "Status" flags?
UPDATE:
If EMP_04 has 3 consecutives timestamps of the same type (IN's or OUT's) for example:

9:04:27am (IN)
9:04:35am (IN)
9:04:40am (IN)

My tolerance will be 120 seconds between times, so the first time 9:04:27 is OK, but the next 2 consecutive timestamps should be INACTIVE because my tolerance is 120 seconds.
But, for example if EMP_04 has the following consecutive timestamps:

9:04:27am (IN)
9:04:35am (IN)
9:08:10am (IN)

Then the only time marked as INACTIVE will be 9:04:35am. Because between 9:04.35 and 9:08:10am is greater than 2 min.

A:

First, acknowledging @RamRS put the hard work into the trigger, here is one that is tested and should get your started. Clearly some robust testing is needed for corner cases:
CREATE TRIGGER TS_FindDups ON dbo.TS FOR INSERT
AS
BEGIN

;WITH DupRecords
AS
(
        SELECT i.EmployeeId, i.[TimeStamp]
          FROM inserted i
    INNER JOIN dbo.TS SRC ON i.EmployeeId = SRC.EmployeeId AND i.EntranceType = SRC.EntranceType
         WHERE SRC.[Status] != 'Inactive'
               /* same day (nice...thanks to RamRS) */
               AND CAST(i.[TimeStamp] AS date) =  CAST(SRC.[TimeStamp] AS date)
               /* only checking newer timestamps (also need this so DATEDIFF <= 2 works correctly) */
               AND i.[TimeStamp] > SRC.[TimeStamp]
               /* newer timestamps are less than two minutes for same Employee, same day, same EntranceType */
               AND DATEDIFF(MINUTE, SRC.[TimeStamp], i.[TimeStamp]) <= 2
)

      UPDATE dbo.TS
         SET [Status] = 'Inactive'
        FROM dbo.TS SRC
  INNER JOIN DupRecords ON SRC.EmployeeId = DupRecords.EmployeeId AND SRC.[TimeStamp] = DupRecords.[TimeStamp]

END


Q:

WSO2 API Manager sandbox keys are accepted by production servers

I just started working with wso2 api manager version 1.6 and it seems that sandbox and production keys can be used interchangeably. Is that a bug?

A:

When using a Sandbox key, it'll send the request to the sandbox url specified when creating the API. If the sandbox url points to a production backend then, you won't see a difference when switching key types.


Q:

PHP: String replace with Regex

Ive tried to get the Regex to work for this script.
What I need it to do is take the width and height from the youtube code that is inserted and replace it with a specified height and width.
$youtube = str_replace('width="' * ' "','width="500"' $_POST['youtube']);

Can anyone help with this?

A:

Assuming your code is:
$code = 'width="100" and height="200"';

And then perform the below regex replace using preg_replace()
$code = preg_replace('/width="\d+"/', 'width="XXX"', $code);
$code = preg_replace('/height="\d+"/', 'height="XXX"', $code);

\d+ means any number of digit starting from length one.


Q:

Checking for double email addresses which are encrypted in the database

People can register for a newsletter on my website.
Their email address and other personal information will be encrypted in the database.
Now for that registration form I'd like to check if the newly inputted email address is already in my database, but as all emails are encrypted, I can't really check unless I loop through every possible email address, decrypt it and see if it matches the newly inputted email? Is that correct? Or is there a more efficient way to do this?

A:

If you use the same encryption key all the time, you can simply search for the encrypted version. If you do not, you can still store a hash of the addresses additionally and compare against that.


Q:

is it "safe" to expose your RxJS Subjects to the "outside world"

I read this good article on
Angular onPush Change Detection Strategy
at some potin he wrote:

It’s an anti-pattern to expose your subject to the outside world, always expose the observable, by using the asObservable() method.

but he doesn't explain why. Does this mean that I shouldn't do somthing like this?
export class ExampleComponent {

  public drawerTrigger$ = new Subject<{}>();
}

and in the HTML
  <button  class="hamburgher-button" type="button"
     (click)="drawerTrigger$.next($event)">
    <i >menu</i>
  </button>

if no, which is the proper way?

A:

In general, you shouldn't expose Subjects because this gives anyone using your service possibility to uncontrollably call drawerTrigger$.next() even in incorrect use-cases.
Even worst situations is that anyone can use drawerTrigger$.error() or drawerTrigger$.complete(). Subjects have internal state and if they emit error or complete the Subject is marked as stopped and will never ever emit anything. If you expose your Subject then you let anyone emit these notifications.
The officially recommended way of exposing Subjects from TypeScript classes is just forcing their types to Observable. You don't need to use asObservable() (RxJS itself doesn't internally use asObservable() anywhere in its codebase):
export class ExampleComponent {
  private drawerTriggerSubject = new Subject<{}>();
  public drawerTrigger$: Observable<{}> = this.drawerTriggerSubject;
}


Q:

Purpose of ammine in Tollens' reagent

In this previous question the mechanism for the reaction of Tollens' reagent was outlined. As I understand it the oxidising agent in Tollens' is the diamminesilver(I) complex $\ce{[Ag(NH3)2]+}$ but the mechanism only showed the silver ion.
What is the purpose of adding ammonia to the silver nitrate to form the diamminesilver(I) complex: why not just use silver nitrate? Is it purely to provide a source of hydroxide ions or is the structure of the complex ion actually important?

A:

The formation of the diamminesilver(I) complex $\ce{[Ag(NH3)2]+}$ due to addition of ammonia has mainly three functions.
1.
The Tollens test takes place under alkaline aqueous conditions. The complexation of $\ce{Ag+}$ with $\ce{NH3}$ prevents precipitation of brown $\ce{Ag2O}$:
$$\ce{2Ag+ + 2OH- <=> 2 AgOH <=> Ag2O + H2O}$$
2.
The Tollens test shall be selective for aldehydes. $\ce{[Ag(NH3)2]+}$ is a milder oxidising agent than $\ce{Ag+}$.
$$\begin{alignat}{2}
\ce{Ag+ + e- \;&<=> Ag}\quad &&E^\circ = +0.799\ \mathrm{V}\\
\ce{[Ag(NH3)2]+ + e- \;&<=> Ag + 2 NH3}\quad &&E^\circ = +0.373\ \mathrm{V}
\end{alignat}$$
The difference in redox potential can be explained using the stability constant of $\ce{[Ag(NH3)2]+}$:
$$K_\text{B} = \frac{\left[\ce{[Ag(NH3)2]+}\right]}{\left[\ce{Ag+}\right]\left[\ce{NH3}\right]^2}$$
$$\begin{aligned}
E&=E_{\ce{Ag+}}^\circ+\frac{RT}{F}\cdot\ln\left[\ce{Ag+}\right]\\
&=E_{\ce{Ag+}}^\circ+\frac{RT}{F}\cdot\ln\frac{\left[\ce{[Ag(NH3)2]+}\right]}{K_\text{B}\cdot\left[\ce{NH3}\right]^2} \\
E_{\ce{[Ag(NH3)2]+}}^\circ&=E_{\ce{Ag+}}^\circ+\frac{RT}{F}\cdot\ln\frac{1}{K_\text{B}} \\
&\approx E_{\ce{Ag+}}^\circ-0.059\ \mathrm{V}\cdot\log K_\text{B}
\end{aligned} $$
3.
The complex formation equilibrium slows down the overall reaction. A slow, controlled reaction is important for creating the desired silver mirror. If $\ce{Ag+}$ is reduced too quickly, colloidal silver metal would appear, which would create a black cloudy liquid.


Q:

Marker interface - what's a practical code example of 'communicating a semantic constraint/guarantee that doesn't otherwise change the API

Let's start with a loose definition of 'marker interface' (please correct me or dispute this if you disagree):

If applied to a type, a marker interface doesn't provide any contract
  of methods to implement for that type. A marker interface gives
  semantic meaning.

So, OK, that's fine. However giving something a meaning has to ultimately have a practical consumption or usage elsewhere to be of benefit, right? So we may have two types that are different, but that are (for example) types related to 'scheduled tasks' in a system, so we may 'decorate' them both with an 'IAmTask' interface.
OK, so how do we then put that to practical use? I've read that:

One of the benefits of a marker interface is to 'communicate a
  semantic constraint/guarantee that doesn't otherwise change the API'.

OK, well a marker interface isn't defining a contract for methods that must be present on the type, so what's a practical example in code of how a semantic constraint/guarantee can be ultimately be returned to the user and consumed in a way that tightens up the intended guarantee to the consumer, without enforcing methods on the API? There must be a way to do this, otherwise we're simply declaring an essentially useless meaning.

A:

Since marker interfaces provide semantic meaning, they can be used like annotations to decorate a type, and you can use reflection to make decisions based on the semantics. The marker interface doesn't provide any compiler-enforceable contract.
For example, you have an interface UserRepository, and you have two implementations InMemoryUserRepository that stores users in memory and DatabaseUserRepository that stores users in a database.
interface UserRepository { def storeUser(user) }
class InMemoryUserRepository implements UserRepository { ... }
class DatabaseUserRepository implements UserRepository { ... }

I could introduce a marker interface to describe the semantics of the implementations. For example if I wanted to dynamically find implementations of UserRepository that have local semantics, I could introduce LocalRepository marker interface and have InMemoryUserRepository implement LocalRepository
interface UserRepository { def storeUser(user) }
interface LocalRepository {}
class InMemoryUserRepository implements UserRepository, LocalRepository { ... }
class DatabaseUserRepository implements UserRepository { ... }

The usefulness is that I can now distinguish the two repository classes from each other and decide to use the one with local semantics via reflection.
Some other examples of usages of marker interfaces:

Big(O) complexity of implementation e.g. java.util.RandomAccess (from @immibis comment). Maybe you have a dozen different sort algorithms. You could introduce marker interfaces with worst case and best case complexities.
Local vs. Remote. This is useful for dynamically picking a configuration for your system for testing. You could configure your dependency injection system to prefer local marked implementations when testing.
Serialization format. I may have a couple different serializers for different file formats that all have the same interface. I could introduce a marker interface to distinguish Json serializers and XML serializers, and use runtime preferences to use the file format. Or use a marker interface to describe their size footprint and choose the best serializer for network transfer based on size.


Q:

Dropdown menu causes scrollbar

I used this example from W3C:

    <button class="btn btn-sm dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">

    </button>

HTML

CSS

JavaScript

About Us

And it all works, except for one thing. Whenever dropdown is opened it outfits the page making a horizontal scrollbar to appear. Ref screenshot below (note horizontal scrollbar at the bottom of the images):

What would be most "official" way to fix this?
EDIT:

Added fiddle: https://jsfiddle.net/aav5f25g/3/

A:

Could you try this?

    <button class="btn btn-sm dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">

    </button>

HTML

CSS

JavaScript

About Us

I added dropdown-menu-right to the dropdown-menu
You may find that pull-right works if you're using an older version.


Q:

Find getElementById property in window.document

Summary: I wanted to know if there was a way to open console in chrome, type window, go to document and search for the getElementById method
Reason: I was searching around and found a lot of the CSS styles for an element(see picture 1 below) and was curious if methods like getElementById were displayed as well
What I tried:
1) I tried looking searching for the getElementById by control + f and searched for "get"
2) Tried seeing if I could get info from mdn: https://developer.mozilla.org/en-US/docs/Web/API/Document/Document
3) Tried reading the link pasted on mdn https://dom.spec.whatwg.org/#interface-nonelementparentnode
Still couldn't find it though :/
element css styles
window.document properties

A:

If I understand you right (directly - how to find 'getElementById' property within global Window object) it is possible to do. You should write in the console Window, open document, then __proto__ (should be the last property of the document object), then __proto__ again, and now you can find getElementById method here. The reason is Window object quite difficult, and uses prototypes to keep all inherit properties and methods: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype


Q:

Retrieving table rows with matching values in a SET Field Type

I have a field in tables, with datatype "set" so that it can accept multiple values. But I got stuck at the time, when I am retrieving the results matching values to it.
An Example field
"menuPosition" : set('top','left','right','bottom')

An Example query
SELECT * FROM mytable where menuPosition='top'

This query only returns those rows with only top as their values, the rows having multiple values like top,left are not returned. How to retrieve all those records?
And since my above query only compares one values, how to write a query to match multiple values like where menuPosition='top' && 'bottom'

A:

You caeither use FIND_IN_SET like:
SELECT * FROM mytable WHERE FIND_IN_SET('top', menuPosition)

Or you can use LIKE:
SELECT * FROM mytable WHERE menuPosition LIKE '%top%'

I guess the first one is faster.


Q:

Is pincushion or barrel distortion really all that bad in a lens?

Given that software can pretty trivially fix pincushion and barrel distortion patterns if you're shooting in RAW (Lightroom did the right thing just by knowing what lens I used with the given EXIF information), does it really matter if a lens has these types of distortion (so long as the are not so significant that the post processing does not lead to other significant artifacts of course)?
Reasoning for asking this:
I've found the distortion with the D7000's kit lens to be really bad -- but optically it's fine on pretty much every other front. Lightroom makes this go away, but I want to be aware of possible issues this might cause while I'm actually shooting...

A:

No, it's not all that bad. On most shots, you won't be able to tell by eye if the curvilinear distortions have been corrected for or not - you'll need straight lines adjacently parallel to each other or to edge to tell. In nature, you won't have those lines. In portraiture, it will exaggerate some parts and diminish others, but perspective distortion and lighting has much more effect on result.
The reason you've heard so much about them is that you've read many lens reviews, and distortion is rather easy to measure and write about.
Possible downsides of shooting distorted and correcting in post:

you'll spend more time setting up and verifying your workflow;
in your heart, you might want to do as much as possible in camera (many cameras can correct JPEGs for manufacturer's brand lenses);
some contests have quite strict rules against manipulation in digital post-processing;
as Jerry Coffin already commented, slight loss of sharpness;
as you mentioned in your question, it's easy to correct if you're shooting RAW and your software knows the lens. These conditions might not be true for various reasons.

A:

Yes, distortion is the second worst type of aberration. The worst is softness.
That is why when Nikon introduced their 18-200mm lens, instead of making it extremely soft like all others of the same focal-range, they made it sharper but left in a lot more severe  distortion.
Distortion is particularly bad because it is impossible to correct without losing sharpness.
Correcting distortion also affects composition, so some things that were in the frame can end up cropped-out of the frame as the distortion correction involves stretching parts of the image and the results get cropped to keep the frame rectangular.
The reason distortion is better than general softness is that you at least have the option to not correct it and - of course - not make everything soft at the same time. There are plenty of subjects for which distortion is not easily noticeable.
Chromatic aberrations are annoying but generally avoidable and affect only small parts of the image. Correcting them has a very localized effect.
Vignetting is extremely annoying but, unless it is severe (1+ stops), can be correct quite easily without much detriment to image quality. You will get increased noise in the extreme corners but that is usually it. Of course, when it is above +1 stop, it can cause areas to be under-exposed while measurably withing the camera's dynamic-range. Personally, I find that 1/4 EV or less of vignetting is not noticeable on most subjects.

A:

As the post above says, it depends on what you shoot. I do allot of architectural and travel photography: Except where I want to use a distortion for artistic effect, I dislike any pincushion or barrel effects. Five years ago when I mainly shot landscapes it could also be a problem when the horizon was off centre, it would curve up or down. However for nature and close up shots it should be less of an issue and you should look for the lens sharpness, fine detail or speed instead.
Although you say you can easily correct distortion in you computer, it's always best to get it right in the camera first time. You should only resort to the computer when it is impossible or impractical to do better at the time.