Programs & Examples On #Gd graph

How many times does each value appear in a column?

You can use CountIf. Put the following code in B1 and drag down the whole column

=COUNTIF(A:A,A1)

It will look like this:

enter image description here

UIScrollView Scrollable Content Size Ambiguity

In my case I received the issue of incorrect content size and content Size Ambiguity in iPad but was working in case of iPhone. I have done the following changes in storyboard to resolve the issue.

  1. Add scrollview in UIView and add constraints leading, top, trailing and bottom to 0,0,0,0.
  2. Set height of scroll view as per the requirements for eg. 100.
  3. Add UIView to scroll view and add constraints leading, top, trailing and bottom to 0,0,0,0 and align centre(X) and center(Y) constraints.
  4. Deselect “Content Layout Guides” in size inspector of scroll view.

Simple WPF RadioButton Binding?

This example might be seem a bit lengthy, but its intention should be quite clear.

It uses 3 Boolean properties in the ViewModel called, FlagForValue1, FlagForValue2 and FlagForValue3. Each of these 3 properties is backed by a single private field called _intValue.

The 3 Radio buttons of the view (xaml) are each bound to its corresponding Flag property in the view model. This means the radio button displaying "Value 1" is bound to the FlagForValue1 bool property in the view model and the other two accordingly.

When setting one of the properties in the view model (e.g. FlagForValue1), its important to also raise property changed events for the other two properties (e.g. FlagForValue2, and FlagForValue3) so the UI (WPF INotifyPropertyChanged infrastructure) can selected / deselect each radio button correctly.

    private int _intValue;

    public bool FlagForValue1
    {
        get
        {
            return (_intValue == 1) ? true : false;
        }
        set
        {
            _intValue = 1;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

    public bool FlagForValue2
    {
        get
        {
            return (_intValue == 2) ? true : false;
        }
        set
        {
            _intValue = 2;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

    public bool FlagForValue3
    {
        get
        {
            return (_intValue == 3) ? true : false;
        }
        set
        {
            _intValue = 3;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

The xaml looks like this:

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue1, Mode=TwoWay}"
                             >Value 1</RadioButton>

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue2, Mode=TwoWay}"
                             >Value 2</RadioButton>

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue3, Mode=TwoWay}"
                             >Value 3</RadioButton>

What is the difference between And and AndAlso in VB.NET?

Also see Stack Overflow question: Should I always use the AndAlso and OrElse operators?.

Also: A comment for those who mentioned using And if the right side of the expression has a side-effect you need:

If the right side has a side effect you need, just move it to the left side rather than using "And". You only really need "And" if both sides have side effects. And if you have that many side effects going on you're probably doing something else wrong. In general, you really should prefer AndAlso.

HTTP GET request in JavaScript?

Modern, clean and shortest

fetch('https://www.randomtext.me/api/lorem')

_x000D_
_x000D_
let url = 'https://www.randomtext.me/api/lorem';

// to only send GET request without waiting for response just call 
fetch(url);

// to wait for results use 'then'
fetch(url).then(r=> r.json().then(j=> console.log('\nREQUEST 2',j)));

// or async/await
(async()=> 
  console.log('\nREQUEST 3', await(await fetch(url)).json()) 
)();
_x000D_
Open Chrome console network tab to see request
_x000D_
_x000D_
_x000D_

In Android EditText, how to force writing uppercase?

Just do this:

// ****** Every first letter capital in word *********
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textCapWords"
    />

//***** if all letters are capital ************

    android:inputType="textCapCharacters"

How to get address location from latitude and longitude in Google Map.?

Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.

https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY

Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.

Click here to get an API key

How to open child forms positioned within MDI parent in VB.NET?

   Private Sub FileMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) handles FileMenu.Click

    Form1.MdiParent = Me
    Form1.Dock = DockStyle.Fill
    Form1.Show()
End Sub

Convert LocalDate to LocalDateTime or java.sql.Timestamp

function call asStartOfDay() on java.time.LocalDate object returns a java.time.LocalDateTime object

RecyclerView onClick

Here is simple and clear way is add inside your ReacyclerView ViewHolder

public static class MyViewholder extends RecyclerView.ViewHolder {

    public MyViewholder(View itemView) {
        super(itemView);

        itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Tag", "onClick:" + getAdapterPosition());
            }
        });

    }
}

getAdapterPosition() is returns the current clicked item position

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

A different case in which I encountered this was when I was using echo to pipe the JSON into my python script and carelessly wrapped the JSON string in double quotes:

echo "{"thumbnailWidth": 640}" | myscript.py

Note that the JSON string itself has quotes and I should have done:

echo '{"thumbnailWidth": 640}' | myscript.py

As it was, this is what the python script received: {thumbnailWidth: 640}; the double quotes were effectively stripped.

Change color and appearance of drop down arrow

Try changing the color of your "border-top" attribute to white

Restart container within pod

All the above answers have mentioned deleting the pod...but if you have many pods of the same service then it would be tedious to delete each one of them...

Therefore, I propose the following solution, restart:

  • 1) Set scale to zero :

     kubectl scale deployment <<name>> --replicas=0 -n service 
    

    The above command will terminate all your pods with the name <<name>>

  • 2) To start the pod again, set the replicas to more than 0

    kubectl scale deployment <<name>> --replicas=2 -n service
    

    The above command will start your pods again with 2 replicas.

Bootstrap Modal immediately disappearing

I had the same problem working on a project with asp.NET. I was using bootstrap 3.1.0 solved it downgrading to Bootstrap 2.3.2.

Copy/duplicate database without using mysqldump

All of the prior solutions get at the point a little, however, they just don't copy everything over. I created a PHP function (albeit somewhat lengthy) that copies everything including tables, foreign keys, data, views, procedures, functions, triggers, and events. Here is the code:

/* This function takes the database connection, an existing database, and the new database and duplicates everything in the new database. */
function copyDatabase($c, $oldDB, $newDB) {

    // creates the schema if it does not exist
    $schema = "CREATE SCHEMA IF NOT EXISTS {$newDB};";
    mysqli_query($c, $schema);

    // selects the new schema
    mysqli_select_db($c, $newDB);

    // gets all tables in the old schema
    $tables = "SELECT table_name
               FROM information_schema.tables
               WHERE table_schema = '{$oldDB}'
               AND table_type = 'BASE TABLE'";
    $results = mysqli_query($c, $tables);

    // checks if any tables were returned and recreates them in the new schema, adds the foreign keys, and inserts the associated data
    if (mysqli_num_rows($results) > 0) {

        // recreates all tables first
        while ($row = mysqli_fetch_array($results)) {
            $table = "CREATE TABLE {$newDB}.{$row[0]} LIKE {$oldDB}.{$row[0]}";
            mysqli_query($c, $table);
        }

        // resets the results to loop through again
        mysqli_data_seek($results, 0);

        // loops through each table to add foreign key and insert data
        while ($row = mysqli_fetch_array($results)) {

            // inserts the data into each table
            $data = "INSERT IGNORE INTO {$newDB}.{$row[0]} SELECT * FROM {$oldDB}.{$row[0]}";
            mysqli_query($c, $data);

            // gets all foreign keys for a particular table in the old schema
            $fks = "SELECT constraint_name, column_name, table_name, referenced_table_name, referenced_column_name
                    FROM information_schema.key_column_usage
                    WHERE referenced_table_name IS NOT NULL
                    AND table_schema = '{$oldDB}'
                    AND table_name = '{$row[0]}'";
            $fkResults = mysqli_query($c, $fks);

            // checks if any foreign keys were returned and recreates them in the new schema
            // Note: ON UPDATE and ON DELETE are not pulled from the original so you would have to change this to your liking
            if (mysqli_num_rows($fkResults) > 0) {
                while ($fkRow = mysqli_fetch_array($fkResults)) {
                    $fkQuery = "ALTER TABLE {$newDB}.{$row[0]}                              
                                ADD CONSTRAINT {$fkRow[0]}
                                FOREIGN KEY ({$fkRow[1]}) REFERENCES {$newDB}.{$fkRow[3]}({$fkRow[1]})
                                ON UPDATE CASCADE
                                ON DELETE CASCADE;";
                    mysqli_query($c, $fkQuery);
                }
            }
        }   
    }

    // gets all views in the old schema
    $views = "SHOW FULL TABLES IN {$oldDB} WHERE table_type LIKE 'VIEW'";                
    $results = mysqli_query($c, $views);

    // checks if any views were returned and recreates them in the new schema
    if (mysqli_num_rows($results) > 0) {
        while ($row = mysqli_fetch_array($results)) {
            $view = "SHOW CREATE VIEW {$oldDB}.{$row[0]}";
            $viewResults = mysqli_query($c, $view);
            $viewRow = mysqli_fetch_array($viewResults);
            mysqli_query($c, preg_replace("/CREATE(.*?)VIEW/", "CREATE VIEW", str_replace($oldDB, $newDB, $viewRow[1])));
        }
    }

    // gets all triggers in the old schema
    $triggers = "SELECT trigger_name, action_timing, event_manipulation, event_object_table, created
                 FROM information_schema.triggers
                 WHERE trigger_schema = '{$oldDB}'";                 
    $results = mysqli_query($c, $triggers);

    // checks if any triggers were returned and recreates them in the new schema
    if (mysqli_num_rows($results) > 0) {
        while ($row = mysqli_fetch_array($results)) {
            $trigger = "SHOW CREATE TRIGGER {$oldDB}.{$row[0]}";
            $triggerResults = mysqli_query($c, $trigger);
            $triggerRow = mysqli_fetch_array($triggerResults);
            mysqli_query($c, str_replace($oldDB, $newDB, $triggerRow[2]));
        }
    }

    // gets all procedures in the old schema
    $procedures = "SHOW PROCEDURE STATUS WHERE db = '{$oldDB}'";
    $results = mysqli_query($c, $procedures);

    // checks if any procedures were returned and recreates them in the new schema
    if (mysqli_num_rows($results) > 0) {
        while ($row = mysqli_fetch_array($results)) {
            $procedure = "SHOW CREATE PROCEDURE {$oldDB}.{$row[1]}";
            $procedureResults = mysqli_query($c, $procedure);
            $procedureRow = mysqli_fetch_array($procedureResults);
            mysqli_query($c, str_replace($oldDB, $newDB, $procedureRow[2]));
        }
    }

    // gets all functions in the old schema
    $functions = "SHOW FUNCTION STATUS WHERE db = '{$oldDB}'";
    $results = mysqli_query($c, $functions);

    // checks if any functions were returned and recreates them in the new schema
    if (mysqli_num_rows($results) > 0) {
        while ($row = mysqli_fetch_array($results)) {
            $function = "SHOW CREATE FUNCTION {$oldDB}.{$row[1]}";
            $functionResults = mysqli_query($c, $function);
            $functionRow = mysqli_fetch_array($functionResults);
            mysqli_query($c, str_replace($oldDB, $newDB, $functionRow[2]));
        }
    }

    // selects the old schema (a must for copying events)
    mysqli_select_db($c, $oldDB);

    // gets all events in the old schema
    $query = "SHOW EVENTS
              WHERE db = '{$oldDB}';";
    $results = mysqli_query($c, $query);

    // selects the new schema again
    mysqli_select_db($c, $newDB);

    // checks if any events were returned and recreates them in the new schema
    if (mysqli_num_rows($results) > 0) {
        while ($row = mysqli_fetch_array($results)) {
            $event = "SHOW CREATE EVENT {$oldDB}.{$row[1]}";
            $eventResults = mysqli_query($c, $event);
            $eventRow = mysqli_fetch_array($eventResults);
            mysqli_query($c, str_replace($oldDB, $newDB, $eventRow[3]));
        }
    }
}

Bogus foreign key constraint fail

Disable foreign key checking

SET FOREIGN_KEY_CHECKS=0

How to spyOn a value property (rather than a method) with Jasmine

I'm using a kendo grid and therefore can't change the implementation to a getter method but I want to test around this (mocking the grid) and not test the grid itself. I was using a spy object but this doesn't support property mocking so I do this:

    this.$scope.ticketsGrid = { 
        showColumn: jasmine.createSpy('showColumn'),
        hideColumn: jasmine.createSpy('hideColumn'),
        select: jasmine.createSpy('select'),
        dataItem: jasmine.createSpy('dataItem'),
        _data: []
    } 

It's a bit long winded but it works a treat

XML parsing of a variable string in JavaScript

<script language="JavaScript">
function importXML()
{
    if (document.implementation && document.implementation.createDocument)
    {
            xmlDoc = document.implementation.createDocument("", "", null);
            xmlDoc.onload = createTable;
    }
    else if (window.ActiveXObject)
    {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.onreadystatechange = function () {
                    if (xmlDoc.readyState == 4) createTable()
            };
    }
    else
    {
            alert('Your browser can\'t handle this script');
            return;
    }
    xmlDoc.load("emperors.xml");
}

function createTable()
{
    var theData="";
    var x = xmlDoc.getElementsByTagName('emperor');
    var newEl = document.createElement('TABLE');
    newEl.setAttribute('cellPadding',3);
    newEl.setAttribute('cellSpacing',0);
    newEl.setAttribute('border',1);
    var tmp = document.createElement('TBODY');
    newEl.appendChild(tmp);
    var row = document.createElement('TR');
    for (j=0;j<x[0].childNodes.length;j++)
    {
            if (x[0].childNodes[j].nodeType != 1) continue;
            var container = document.createElement('TH');
            theData = document.createTextNode(x[0].childNodes[j].nodeName);
            container.appendChild(theData);
            row.appendChild(container);
    }
    tmp.appendChild(row);
    for (i=0;i<x.length;i++)
    {
            var row = document.createElement('TR');
            for (j=0;j<x[i].childNodes.length;j++)
            {
                    if (x[i].childNodes[j].nodeType != 1) continue;
                    var container = document.createElement('TD');
                    var theData = document.createTextNode(x[i].childNodes[j].firstChild.nodeValue);
                    container.appendChild(theData);
                    row.appendChild(container);
            }
            tmp.appendChild(row);
    }
    document.getElementById('writeroot').appendChild(newEl);
}
</script>
</HEAD>

<BODY onLoad="javascript:importXML();">
<p id=writeroot> </p>
</BODY>

For more info refer this http://www.easycodingclub.com/xml-parser-in-javascript/javascript-tutorials/

Javascript change font color

Html code

<div id="coloredBy">
    Colored By Santa
</div>

javascript code

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff

I think this is very easy to use

how to detect search engine bots with php?

If you really need to detect GOOGLE engine bots you should never rely on "user_agent" or "IP" address because "user_agent" can be changed and acording to what google said in: Verifying Googlebot

To verify Googlebot as the caller:

1.Run a reverse DNS lookup on the accessing IP address from your logs, using the host command.

2.Verify that the domain name is in either googlebot.com or google.com

3.Run a forward DNS lookup on the domain name retrieved in step 1 using the host command on the retrieved domain name. Verify that it is the same as the original accessing IP address from your logs.

Here is my tested code :

<?php
$remote_add=$_SERVER['REMOTE_ADDR'];
$hostname = gethostbyaddr($remote_add);
$googlebot = 'googlebot.com';
$google = 'google.com';
if (stripos(strrev($hostname), strrev($googlebot)) === 0 or stripos(strrev($hostname),strrev($google)) === 0 ) 
{
//add your code
}

?>

In this code we check "hostname" which should contain "googlebot.com" or "google.com" at the end of "hostname" which is really important to check exact domain not subdomain. I hope you enjoy ;)

how to POST/Submit an Input Checkbox that is disabled?

You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.

$('#myForm').submit(function() {
    $('checkbox').removeAttr('disabled');
});

Is it possible to use Visual Studio on macOS?

I recently purchased a MacBook Air (mid-2011 model) and was really happy to find that Apple officially supports Windows 7. If you purchase Windows 7 (I got DSP), you can use the Boot Camp assistant in OSX to designate part of your hard drive to Windows. Then you can install and run Windows 7 natively as if it were as Windows notebook.

I use Visual Studio 2010 on Windows 7 on my MacBook Air (I kept OSX as well) and I could not be happier. Heck, the initial start-up of the program only takes 3 seconds thanks to the SSD.

As others have mentions, you can run it on OSX using Parallels, etc. but I prefer to run it natively.

Get name of property as a string

I modified your solution to chain over multiple properties:

public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    MemberExpression me = propertyLambda.Body as MemberExpression;
    if (me == null)
    {
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    }

    string result = string.Empty;
    do
    {
        result = me.Member.Name + "." + result;
        me = me.Expression as MemberExpression;
    } while (me != null);

    result = result.Remove(result.Length - 1); // remove the trailing "."
    return result;
}

Usage:

string name = GetPropertyName(() => someObject.SomeProperty.SomeOtherProperty);
// returns "SomeProperty.SomeOtherProperty"

Nesting await in Parallel.ForEach

This should be pretty efficient, and easier than getting the whole TPL Dataflow working:

var customers = await ids.SelectAsync(async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    return await repo.GetCustomer(i);
});

...

public static async Task<IList<TResult>> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector, int maxDegreesOfParallelism = 4)
{
    var results = new List<TResult>();

    var activeTasks = new HashSet<Task<TResult>>();
    foreach (var item in source)
    {
        activeTasks.Add(selector(item));
        if (activeTasks.Count >= maxDegreesOfParallelism)
        {
            var completed = await Task.WhenAny(activeTasks);
            activeTasks.Remove(completed);
            results.Add(completed.Result);
        }
    }

    results.AddRange(await Task.WhenAll(activeTasks));
    return results;
}

Add Bootstrap Glyphicon to Input Box

If you are using Fontawesome you can do this :

<input type="text" style="font-family:Arial, FontAwesome"  placeholder="&#xf007;" />

Result

enter image description here

The complete list of unicode can be found in the The complete Font Awesome 4.6.3 icon reference

File path issues in R using Windows ("Hex digits in character string" error)

Replace back slashes \ with forward slashes / when running windows machine

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Reading serial data in realtime in Python

You can use inWaiting() to get the amount of bytes available at the input queue.

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)

How to check if an object is an array?

You can check the type of your variable whether it is an array with;

var myArray=[];

if(myArray instanceof Array)
{
....
}

How to get the date from jQuery UI datepicker

the link to getdate: https://api.jqueryui.com/datepicker/#method-getDate

$("#datepicker").datepicker( 'getDate' );

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

Edit:

This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx


You can use this ObjectFilter:

    public class ObjectFilter : ActionFilterAttribute {

    public string Param { get; set; }
    public Type RootType { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
            object o =
            new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
            filterContext.ActionParameters[Param] = o;
        }

    }
}

You can then apply it to your controller methods like so:

    [ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
    public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }

So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.

Get the cell value of a GridView row

I suggest you use a HiddenField inside template field use FindControl to find this field.

ie:

ASPX

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HiddenField ID="hfFname" runat="server" Value='<%# Eval("FileName") %>' />
                    </ItemTemplate>
                </asp:TemplateField>

Code behind

protected void gvAttachments_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView gv1 = (GridView)sender;
        GridViewRow gvr1 = (GridViewRow)gv1.Rows[e.RowIndex];

        //get hidden field value and not directly from the GridviewRow, as that will be null or empty!
        HiddenField hf1 = (HiddenField)gvr1.FindControl("hfFname");
        if (hf1 != null)
        {
           ..
        }
    }

How can I consume a WSDL (SOAP) web service in Python?

Zeep is a decent SOAP library for Python that matches what you're asking for: http://docs.python-zeep.org

docker unauthorized: authentication required - upon push with successful login

If you are pushing a new private image for the first time, make sure your subscription supports this extra image.

Docker allows you to have 6 private images named, even if you only pay for 5, but not to push that 6th image. The lack of an informative message is confusing and irritating.

Unable to Connect to GitHub.com For Cloning

I had the same error because I was using proxy. As the answer is given but in case you are using proxy then please set your proxy first using these commands:

git config --global http.proxy http://proxy_username:proxy_password@proxy_ip:port
git config --global https.proxy https://proxy_username:proxy_password@proxy_ip:port

Update statement using with clause

The WITH syntax appears to be valid in an inline view, e.g.

UPDATE (WITH comp AS ...
        SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
   SET SomeColumn=ComputedValue;

But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.

You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:

MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;

But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING clause arbitrarily complex, incorporating multiple WITH clauses.

How to convert a string into double and vice versa?

// Converting String in to Double

double doubleValue = [yourString doubleValue];

// Converting Double in to String
NSString *yourString = [NSString stringWithFormat:@"%.20f", doubleValue];
// .20f takes the value up to 20 position after decimal

// Converting double to int

int intValue = (int) doubleValue;
or
int intValue = [yourString intValue];

How to fix request failed on channel 0

This was happening when I was trying to use sudo on ssh -t [email protected] after adding my local user's public key to github

Just a head's up to the google happy people like me

In angular $http service, How can I catch the "status" of error?

Response status comes as second parameter in callback, (from docs):

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

How to declare an array of objects in C#

You are creating an array of null references. You should do something like:

for (int i = 0; i < houses.Count; i++)
{
    houses[i] = new GameObject();
}

How to run an awk commands in Windows?

Actually, I do like mark instruction but little differently. I've added C:\Program Files (x86)\GnuWin32\bin\ to the Path variable, and try to run it with type awk using cmd.

Hope it works.

How to have a transparent ImageButton: Android

in run time, you can use following code

btn.setBackgroundDrawable(null);

Can I set text box to readonly when using Html.TextBoxFor?

You can also disabled TextBoxFor

@Html.TextBoxFor(x=>x.day, null, new { @class = "form-control success" ,@disabled="disabled" })

Getting a list of all subdirectories in the current directory

With full path and accounting for path being ., .., \\, ..\\..\\subfolder, etc:

import os, pprint
pprint.pprint([os.path.join(os.path.abspath(path), x[0]) \
    for x in os.walk(os.path.abspath(path))])

PowerShell : retrieve JSON object by field value

David Brabant's answer led me to what I needed, with this addition:

x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type

MySQL "WITH" clause

You've got the syntax right:

WITH AuthorRating(AuthorName, AuthorRating) AS
   SELECT aname         AS AuthorName,
          AVG(quantity) AS AuthorRating
   FROM Book
   GROUP By Book.aname

However, as others have mentioned, MySQL does not support this command. WITH was added in SQL:1999; the newest version of the SQL standard is SQL:2008. You can find some more information about databases that support SQL:1999's various features on Wikipedia.

MySQL has traditionally lagged a bit in support for the SQL standard, whereas commercial databases like Oracle, SQL Server (recently), and DB2 have followed them a bit more closely. PostgreSQL is typically pretty standards compliant as well.

You may want to look at MySQL's roadmap; I'm not completely sure when this feature might be supported, but it's great for creating readable roll-up queries.

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

Read from file or stdin

You can just read from stdin unless the user supply a filename ?

If not, treat the special "filename" - as meaning "read from stdin". The user would have to start the program like cat file | myprogram - if he wants to pipe data to it, and myprogam file if he wants it to read from a file.

int main(int argc,char *argv[] ) {
  FILE *input;
  if(argc != 2) {
     usage();
     return 1;
   }
   if(!strcmp(argv[1],"-")) {
     input = stdin;
    } else {
      input = fopen(argv[1],"rb");
      //check for errors
    }

If you're on *nix, you can check whether stdin is a fifo:

 struct stat st_info;
 if(fstat(0,&st_info) != 0)
   //error
  }
  if(S_ISFIFO(st_info.st_mode)) {
     //stdin is a pipe
  }

Though that won't handle the user doing myprogram <file

You can also check if stdin is a terminal/console

if(isatty(0)) {
  //stdin is a terminal
}

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Handling NULL values in Hive

Try using isnull(a), isnotnull(a), nvl(), etc. On some versions(potentially in conjunction with the server settings - atleast with the one I am working on) of hive the 'IS NULL' and 'IS NOT NULL' syntax does not execute the logic when it is compiled. Check here for more information.

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

Simply use Window.Maximize() command

WebDriver driver= new ChromeDriver()
driver.Manage().Window.Maximize();  

Remove first Item of the array (like popping from stack)

The easiest way is using shift(). If you have an array, the shift function shifts everything to the left.

var arr = [1, 2, 3, 4]; 
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

UPDATE:

Starting end August 2012, the API has been updated to allow you to retrieve user's profile pictures in varying sizes. Add the optional width and height fields as URL parameters:

https://graph.facebook.com/USER_ID/picture?width=WIDTH&height=HEIGHT

where WIDTH and HEIGHT are your requested dimension values.

This will return a profile picture with a minimum size of WIDTH x HEIGHT while trying to preserve the aspect ratio. For example,

https://graph.facebook.com/redbull/picture?width=140&height=110

returns

    {
      "data": {
        "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/c0.19.180.142/s148x148/2624_134501175351_4831452_a.jpg",
        "width": 148,
        "height": 117,
        "is_silhouette": false
      }
   }

END UPDATE

To get a user's profile picture, call

https://graph.facebook.com/USER_ID/picture

where USER_ID can be the user id number or the user name.

To get a user profile picture of a specific size, call

https://graph.facebook.com/USER_ID/picture?type=SIZE

where SIZE should be replaced with one of the words

square
small
normal
large

depending on the size you want.

This call will return a URL to a single image with its size based on your chosen type parameter.

For example:

https://graph.facebook.com/USER_ID/picture?type=small

returns a URL to a small version of the image.

The API only specifies the maximum size for profile images, not the actual size.

Square:

maximum width and height of 50 pixels.

Small

maximum width of 50 pixels and a maximum height of 150 pixels.

Normal

maximum width of 100 pixels and a maximum height of 300 pixels.

Large

maximum width of 200 pixels and a maximum height of 600 pixels.

If you call the default USER_ID/picture you get the square type.

CLARIFICATION

If you call (as per above example)

https://graph.facebook.com/redbull/picture?width=140&height=110

it will return a JSON response if you're using one of the Facebook SDKs request methods. Otherwise it will return the image itself. To always retrieve the JSON, add:

&redirect=false

like so:

https://graph.facebook.com/redbull/picture?width=140&height=110&redirect=false

less than 10 add 0 to number

You can always do

('0' + deg).slice(-2)

If you use it very often, you may extend the object Number

Number.prototype.pad = function(n) {
    if (n==undefined)
        n = 2;

    return (new Array(n).join('0') + this).slice(-n);
}

deg.pad(4) // "0045"

where you can set any pad size or leave the default 2.

How do I timestamp every ping result?

  1. terminal output:

    ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}'

  2. file output:

    ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' > test.txt

  3. terminal + file output:

    ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' | tee test.txt

  4. file output background:

    nohup ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' > test.txt &

How to run ssh-add on windows?

If you are trying to setup a key for using git with ssh, there's always an option to add a configuration for the identity file.

vi ~/.ssh/config

Host example.com
IdentityFile ~/.ssh/example_key

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

Truncate all tables in a MySQL database in one command?

I find that TRUNCATE TABLE .. has trouble with foreign key constraints, even after a NOCHECK CONSTRAINT ALL, so I use a DELETE FROM statement instead. This does mean that identity seeds are not reset, you could always add a DBCC CHECKIDENT to achieve this.

I Use the code below to print out to the message window the sql for truncating all the tables in the database, before running it. It just makes it a bit harder to make a mistake.

EXEC sp_MSforeachtable 'PRINT ''ALTER TABLE ? NOCHECK CONSTRAINT ALL'''
EXEC sp_MSforeachtable 'print ''DELETE FROM ?'''
EXEC sp_MSforeachtable 'print ''ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'''

Owl Carousel Won't Autoplay

Your Javascript should be

<script>
$("#intro").owlCarousel({

// Most important owl features

//Autoplay
autoplay: false,
autoplayTimeout: 5000,
autoplayHoverPause: true
)}
</script>

How much RAM is SQL Server actually using?

You should explore SQL Server\Memory Manager performance counters.

Counting the number of option tags in a select tag in jQuery

The W3C solution:

var len = document.getElementById("input1").length;

How do I open multiple instances of Visual Studio Code?

Ctrl + Shift + N will open a new window, while Ctrl+K then releases the keys, and pressing O would open the current tab in a new window. You can then use menu FileOpen Folder to have two instances of Visual Studio Code with different folders in each window.

? + Shift + N and ? + K for Mac.

List of helpful keyboard shortcuts can be found here.

Can't use method return value in write context

empty() needs to access the value by reference (in order to check whether that reference points to something that exists), and PHP before 5.5 didn't support references to temporary values returned from functions.

However, the real problem you have is that you use empty() at all, mistakenly believing that "empty" value is any different from "false".

Empty is just an alias for !isset($thing) || !$thing. When the thing you're checking always exists (in PHP results of function calls always exist), the empty() function is nothing but a negation operator.

PHP doesn't have concept of emptyness. Values that evaluate to false are empty, values that evaluate to true are non-empty. It's the same thing. This code:

$x = something();
if (empty($x)) …

and this:

$x = something();
if (!$x) …

has always the same result, in all cases, for all datatypes (because $x is defined empty() is redundant).

Return value from the method always exists (even if you don't have return statement, return value exists and contains null). Therefore:

if (!empty($r->getError()))

is logically equivalent to:

if ($r->getError())

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

You should probably set all of the cookie properties not just the value of it. setPath(), setDomain() ... etc

How do I Validate the File Type of a File Upload?

Based on kd7's reply suggesting you check for the files content type, here's a wrapper method:

private bool FileIsValid(FileUpload fileUpload)
{
    if (!fileUpload.HasFile)
    {
        return false;
    }
    if (fileUpload.PostedFile.ContentType == "application/vnd.ms-excel" ||
        fileUpload.PostedFile.ContentType == "application/excel" ||
        fileUpload.PostedFile.ContentType == "application/x-msexcel" ||
        fileUpload.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" //this is xlsx format
        )
        return true;

    return false;
}

returning true if the file to upload is .xls or .xlsx

How to insert a value that contains an apostrophe (single quote)?

You need to escape the apostrophe. In T-SQL this is with a double apostrophe, so your insert statement becomes:

Insert into Person
(First, Last)
Values
'Joe', 'O''Brien'

laravel 5.4 upload image

You can use it by easy way, through store method in your controller

like the below

First, we must create a form with file input to let us upload our file.

{{Form::open(['route' => 'user.store', 'files' => true])}}

{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}

{{Form::close()}}

Here is how we can handle file in our controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

  public function store(Request $request)
  {

  // get current time and append the upload file extension to it,
  // then put that name to $photoName variable.
  $photoName = time().'.'.$request->user_photo->getClientOriginalExtension();

  /*
  talk the select file and move it public directory and make avatars
  folder if doesn't exsit then give it that unique name.
  */
  $request->user_photo->move(public_path('avatars'), $photoName);

  }
}

That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.

SQL Server 2005 Using DateAdd to add a day to a date

Try following code will Add one day to current date

select DateAdd(day, 1, GetDate())

And in the same way can use Year, Month, Hour, Second etc. instead of day in the same function

Cut Java String at a number of character

Jakarta Commons StringUtils.abbreviate(). If, for some reason you don't want to use a 3rd-party library, at least copy the source code.

One big benefit of this over the other answers to date is that it won't throw if you pass in a null.

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

<a href="javascript:void(0)" onclick="$('#myDialog').dialog();">
  Open as dialog
</a>

<div id="myDialog">
I have a dialog!
</div>

See the example I posted on jsbin.com.

How to see docker image contents

There is a free open source tool called Anchore that you can use to scan container images. This command will allow you to list all files in a container image

anchore-cli image content myrepo/app:latest files

https://anchore.com/opensource/

Why does NULL = NULL evaluate to false in SQL server

The confusion arises from the level of indirection (abstraction) that comes about from using NULL.

Going back to the "what's under the Christmas tree" analogy, "Unknown" describes the state of knowledge about what is in Box A.

So if you don't know what's in Box A, you say it's "Unknown", but that doesn't mean that "Unknown" is inside the box. Something other than unknown is in the box, possibly some kind of object, or possibly nothing is in the box.

Similarly, if you don't know what's in Box B, you can label your state of knowledge about the contents as being "Unknown".

So here's the kicker: Your state of knowledge about Box A is equal to your state of knowledge about Box B. (Your state of knowledge in both cases is "Unknown" or "I don't know what's in the Box".) But the contents of the boxes may or may not be equal.

Going back to SQL, ideally you should only be able to compare values when you know what they are. Unfortunately, the label that describes a lack of knowledge is stored in the cell itself, so we're tempted to use it as a value. But we should not use that as a value, because it would lead to "the content of Box A equals the content of Box B when we don't know what's in Box A and/or we don't know what's in Box B. (Logically, the implication "if I don't know what's in Box A and if I don't know what's in Box B, then what's in Box A = What's in Box B" is false.)

Yay, Dead Horse.

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

how to change a selections options based on another select option selected?

Your if statement is setting the value. You want to compare it by doing this

if ($("#type").val() == "item1") {
 ...
}

daLizard is right though. You want an event handler. document.ready runs only once, when the page DOM is ready to be used.

How do we update URL or query strings using javascript/jQuery without reloading the page?

Plain javascript: document.location = 'http://www.google.com';

This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.

PostgreSQL database service

I'm not on windows, but I think you can use the pgAdmin you just installed to configure a server connection and start the server.

Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

enter image description here

How to send POST request in JSON using HTTPClient in Android?

In this answer I am using an example posted by Justin Grammens.

About JSON

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

The Parts
A fan object with email as a key and [email protected] as a value

{
  fan:
    {
      email : '[email protected]'
    }
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of '[email protected]'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be '[email protected]' 
    //{ fan: { email : '[email protected]' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and '[email protected]'  together in map
        holder.put(key, data);
    }
    return holder;
}

Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

Update

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.

How to redirect the output of an application in background to /dev/null

You use:

yourcommand  > /dev/null 2>&1

If it should run in the Background add an &

yourcommand > /dev/null 2>&1 &

>/dev/null 2>&1 means redirect stdout to /dev/null AND stderr to the place where stdout points at that time

If you want stderr to occur on console and only stdout going to /dev/null you can use:

yourcommand 2>&1 > /dev/null

In this case stderr is redirected to stdout (e.g. your console) and afterwards the original stdout is redirected to /dev/null

If the program should not terminate you can use:

nohup yourcommand &

Without any parameter all output lands in nohup.out

String.Format alternative in C++

In addition to options suggested by others I can recommend the fmt library which implements string formatting similar to str.format in Python and String.Format in C#. Here's an example:

std::string a = "test";
std::string b = "text.txt";
std::string c = "text1.txt";
std::string result = fmt::format("{0} {1} > {2}", a, b, c);

Disclaimer: I'm the author of this library.

How to toggle a boolean?

bool === tool ? bool : tool

if you want the value to hold true if tool (another boolean) has the same value

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

Unrecognized SSL message, plaintext connection? Exception

It worked for me now, I have change the setting of my google account as below:

        System.out.println("Start");
        final String username = "[email protected]";
        final String password = "************";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

         Session session = Session.getInstance(props,
                  new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                  });


        try {
            Transport transport=session.getTransport();
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));//formBean.getString("fromEmail")
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
            message.setSubject("subject");//formBean.getString(
            message.setText("mailBody");
            transport.connect();
            transport.send(message, InternetAddress.parse("[email protected]"));//(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            System.out.println("e="+e);
            e.printStackTrace();
            throw new RuntimeException(e);

        }

Though I have enabled SSL and TSL while running program in this link of same post. I spend a lot of time but than I realized and found this link. And done 2 following steps and setting control in google. :

  • Disable the 2-step verification (password and OTP)

  • Enabling to allow to access less secure app(Allow less secure apps: ON.)

Now I am able to send mail using above program.

Oracle PL/SQL string compare issue

To fix the core question, "how should I detect that these two variables don't have the same value when one of them is null?", I don't like the approach of nvl(my_column, 'some value that will never, ever, ever appear in the data and I can be absolutely sure of that') because you can't always guarantee that a value won't appear... especially with NUMBERs.

I have used the following:

if (str1 is null) <> (str2 is null) or str1 <> str2 then
  dbms_output.put_line('not equal');
end if;

Disclaimer: I am not an Oracle wizard and I came up with this one myself and have not seen it elsewhere, so there may be some subtle reason why it's a bad idea. But it does avoid the trap mentioned by APC, that comparing a null to something else gives neither TRUE nor FALSE but NULL. Because the clauses (str1 is null) will always return TRUE or FALSE, never null.

(Note that PL/SQL performs short-circuit evaluation, as noted here.)

Adding form action in html in laravel

I wanted to store a post in my application, so I created a controller of posts (PostsController) with the resources included:

php artisan make:controller PostsController --resource

The controller was created with all the methods needed to do a CRUD app, then I added the following code to the web.php in the routes folder :

Route::resource('posts', 'PostsController');

I solved the form action problem by doing this:

  1. I checked my routing list by doing php artisan route:list
  2. I searched for the route name of the store method in the result table in the terminal and I found it under the name of posts.store
  3. I added this to the action attribute of my form: action="{{route('posts.store')}}" instead of action="??what to write here??"

How to draw a line in android

To improve on the answers provided by @Janusz

I added this to my styles:

<style name="Divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item>
    <item name="android:background">?android:attr/listDivider</item>
</style>

Then in my layouts is less code and simpler to read.

<View style="@style/Divider"/>

if you want to do horizontal line spacing then do the above.


And for vertical line between two Views you have to replace android:layout_width parameters(attributes) with android:layout_height

When to use %r instead of %s in Python?

%r shows with quotes:

It will be like:

I said: 'There are 10 types of people.'.

If you had used %s it would have been:

I said: There are 10 types of people..

How to get input textfield values when enter key is pressed in react js?

Use onKeyDown event, and inside that check the key code of the key pressed by user. Key code of Enter key is 13, check the code and put the logic there.

Check this example:

_x000D_
_x000D_
class CartridgeShell extends React.Component {_x000D_
_x000D_
   constructor(props) {_x000D_
      super(props);_x000D_
      this.state = {value:''}_x000D_
_x000D_
      this.handleChange = this.handleChange.bind(this);_x000D_
      this.keyPress = this.keyPress.bind(this);_x000D_
   } _x000D_
 _x000D_
   handleChange(e) {_x000D_
      this.setState({ value: e.target.value });_x000D_
   }_x000D_
_x000D_
   keyPress(e){_x000D_
      if(e.keyCode == 13){_x000D_
         console.log('value', e.target.value);_x000D_
         // put the login here_x000D_
      }_x000D_
   }_x000D_
_x000D_
   render(){_x000D_
      return(_x000D_
         <input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
      )_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
_x000D_
_x000D_

Note: Replace the input element by Material-Ui TextField and define the other properties also.

JSON Invalid UTF-8 middle byte

I had this problem inconsistently between different platforms, as I got JSON as String from Mapper and did the writing myself. Sometimes it went into file as ansi and other times correctly as UTF8. I switched to

mapper.writeValue(file, data);

letting Mapper do the file operations, and it started working fine.

Invert colors of an image in CSS or JavaScript

Can be done in major new broswers using the code below

.img {
    -webkit-filter:invert(100%);
     filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}

However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.

Why SpringMVC Request method 'GET' not supported?

Apparently some POST requests looks like a "GET" to the server (like Heroku...)

So I use this strategy and it works for me:

@RequestMapping(value = "/salvar", method = { RequestMethod.GET, RequestMethod.POST })

.datepicker('setdate') issues, in jQuery

As Scobal's post implies, the datepicker is looking for a Date object - not just a string! So, to modify your example code to do what you want:

var queryDate = new Date('2009/11/01'); // Dashes won't work
$('#datePicker').datepicker('setDate', queryDate);

How to print a string at a fixed width?

>>> print(f"{'123':<4}56789")
123 56789

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

How to make Twitter Bootstrap menu dropdown on hover rather than click

The very simple solution for version 2, only CSS. Keeps the same friendly functionality for mobile and tablet.

@media (min-width: 980px) {
    .dropdown:hover .dropdown-menu {
       display: block;
    }
}

How to get the sizes of the tables of a MySQL database?

select x.dbname as db_name, x.table_name as table_name, x.bytesize as the_size from
  (select
     table_schema as dbname,
     sum(index_length+data_length) as bytesize,
     table_name
   from
     information_schema.tables
   group by table_schema
  ) x
where
  x.bytesize > 999999
order by x.bytesize desc;

Ignore self-signed ssl cert using Jersey Client

For Jersey 1.X

    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}

        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}

        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            // or you can return null too
            return new java.security.cert.X509Certificate[0];
        }
    }};


    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String string, SSLSession sslSession) {
            return true;
        }
    });

How do I make bootstrap table rows clickable?

I show you my example with modal windows...you create your modal and give it an id then In your table you have tr section, just ad the first line you see below (don't forget to set the on the first row like this

<tr onclick="input" data-toggle="modal" href="#the name for my modal windows" >
 <td><label>Some value here</label></td>
</tr>                                                                                                                                                                                   

curl_exec() always returns false

Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error() and curl_errno() will contain further information in case of failure:

try {
    $ch = curl_init();

    // Check if initialization had gone wrong*    
    if ($ch === false) {
        throw new Exception('failed to initialize');
    }

    curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(/* ... */);

    $content = curl_exec($ch);

    // Check the return value of curl_exec(), too
    if ($content === false) {
        throw new Exception(curl_error($ch), curl_errno($ch));
    }

    /* Process $content here */

    // Close curl handle
    curl_close($ch);
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);

}

* The curl_init() manual states:

Returns a cURL handle on success, FALSE on errors.

I've observed the function to return FALSE when you're using its $url parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.

Get original URL referer with PHP?

Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.

Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):

if(!isset($_COOKIE['origin_ref']))
{
    setcookie('origin_ref', $_SERVER['HTTP_REFERER']);
}

Then you can access it later:

$var = $_COOKIE['origin_ref'];

And to addition to what @pcp suggested about escaping $_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape $_COOKIE['origin_ref'] on each request.

Documentation for using JavaScript code inside a PDF file

The comprehensive place for Acrobat JavaScript documentation is the Acrobat SDK, which can be downloaded from the Adobe website. In the Documentation section, you will find all the material needed to work with Acrobat JavaScript.

To complete the documentation you may in addition get the specification of the JavaScript Core. My book of choice for that is "JavaScript, the Definitive Guide" by David Flanagan, published by O'Reilly.

What is <scope> under <dependency> in pom.xml for?

If we don't provide any scope then the default scope is compile, If you want to confirm, simply go to Effective pom tab in eclipse editor, it will show you as compile.

How to get detailed list of connections to database in sql server 2005?

As @Hutch pointed out, one of the major limitations of sp_who2 is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE).

Instead, you can just go directly to the source on master.dbo.sysprocesses

I've constructed this to output almost exactly the same thing that sp_who2 generates, except that you can easily add ORDER BY and WHERE clauses to get meaningful output.

SELECT  spid,
        sp.[status],
        loginame [Login],
        hostname, 
        blocked BlkBy,
        sd.name DBName, 
        cmd Command,
        cpu CPUTime,
        physical_io DiskIO,
        last_batch LastBatch,
        [program_name] ProgramName   
FROM master.dbo.sysprocesses sp 
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid 

Getting the source of a specific image element with jQuery

To select and element where you know only the attribute value you can use the below jQuery script

var src = $('.conversation_img[alt="example"]').attr('src');

Please refer the jQuery Documentation for attribute equals selectors

Please also refer to the example in Demo

Following is the code incase you are not able to access the demo..

HTML

<div>
    <img alt="example" src="\images\show.jpg" />
    <img  alt="exampleAll" src="\images\showAll.jpg" />  

</div>

SCRIPT JQUERY

var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);


var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );

Output will be

Two Alert messages each having values

  1. source of image with alternate text = example - \images\show.jpg
  2. source of image with alternate text = exampleAll - \images\showAll.jpg

How to give color to each class in scatter plot in R?

One way is to use the lattice package and xyplot():

R> DF <- data.frame(x=1:10, y=rnorm(10)+5, 
+>                  z=sample(letters[1:3], 10, replace=TRUE))
R> DF
    x       y z
1   1 3.91191 c
2   2 4.57506 a
3   3 3.16771 b
4   4 5.37539 c
5   5 4.99113 c
6   6 5.41421 a
7   7 6.68071 b
8   8 5.58991 c
9   9 5.03851 a
10 10 4.59293 b
R> with(DF, xyplot(y ~ x, group=z))

By giving explicit grouping information via variable z, you obtain different colors. You can specify colors etc, see the lattice documentation.

Because z here is a factor variable for which we obtain the levels (== numeric indices), you can also do

R> with(DF, plot(x, y, col=z))

but that is less transparent (to me, at least :) then xyplot() et al.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Multiline strings in VB.NET

If you need an XML literal in VB.Net with an line code variable, this is how you would do it:

<Tag><%= New XCData(T.Property) %></Tag>

How to reset index in a pandas dataframe?

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True)

If you don't want to reassign:

df.reset_index(drop=True, inplace=True)

In AVD emulator how to see sdcard folder? and Install apk to AVD?

Adding to the usefile DDMS/File Explorer solution, for those that don't know, if you want to read a file you need to select the "Pull File from Device" button on the file viewer toolbar. Unfortunately you can't just drag out, or double click to read.

Use mysql_fetch_array() with foreach() instead of while()

the most obvious way to make foreach a possibility includes materializing the whole resultset in an array, which will probably kill you memory-wise, sooner or later. you'd need to turn to iterators to avoid that problem. see http://www.php.net/~helly/php/ext/spl/

Get records of current month

This query should work for you:

SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())

How to convert a date string to different format

If you can live with 01 for January instead of 1, then try...

d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")

You can check the docs for other formatting directives.

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

This kind of error can also happen when using COPY and having an escaped string containing NULL values(00) such as:

"H\x00\x00\x00tj\xA8\x9E#D\x98+\xCA\xF0\xA7\xBBl\xC5\x19\xD7\x8D\xB6\x18\xEDJ\x1En"

If you use COPY without specifying the format 'CSV' postgres by default will assume format 'text'. This has a different interaction with backlashes, see text format.

If you're using COPY or a file_fdw make sure to specify format 'CSV' to avoid this kind of errors.

Given URL is not permitted by the application configuration

Update to Anvesh Saxena's answer(correct but outdated as FB App interface has changed):

In your FB App configuration you need to add a Website platform with your website's URL set. Then you can add App Domains which I set to our website's base domain (e.g. for a URL like http://www.mycoolwebsite.com, just use mycoolwebsite.com).

New FB Settings Screenshot

IMPORTANT: In order for this to work you'll need to be using a subdomain of your app's URL for your local development. You can do this easily by modifying your hosts file on your development computer to use a non-existent subdomain of your website such as local.mycoolwebsite.com. Just google 'edit hosts file' for your platform (e.g. mac / windows) if you're not familiar with how to do this.

How to get first and last day of previous month (with timestamp) in SQL Server

I've not seen this solution presented yet; this is my preference for its simpler readability:

select dateadd(month,-1,format(getutcdate(),'yyyy-MM-01'))

Is it possible to run one logrotate check manually?

You may want to run it in verbose + force mode.

logrotate -vf /etc/logrotate.conf

Iterator Loop vs index loop

Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.

How to find where javaw.exe is installed?

Try this

for %i in (javaw.exe) do @echo. %~$PATH:i

Set position / size of UI element as percentage of screen size

The above problem can also be solved using ConstraintLayout through Guidelines.

Below is the snippet.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.constraint.Guideline
    android:id="@+id/upperGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.68" />

<Gallery
    android:id="@+id/gallery"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/lowerGuideLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/upperGuideLine" />

<android.support.constraint.Guideline
    android:id="@+id/lowerGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.84" />

</android.support.constraint.ConstraintLayout>

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

How can I make the cursor turn to the wait cursor?

Use this with WPF:

Cursor = Cursors.Wait;

// Your Heavy work here

Cursor = Cursors.Arrow;

Difference between style = "position:absolute" and style = "position:relative"

Absolute places the object (div, span, etc.) at an absolute forced location (usually determined in pixels) and relative will place it a certain amount away from where it's location would normally be. For example:

position:relative; left:-20px;

Might make the left side of the text disappear if it was within 20px to the left edge of the screen.

Copy map values to vector in STL

I thought it should be

std::transform( map.begin(), map.end(), 
                   std::back_inserter(vec), 
                   boost::bind(&MapT::value_type::first,_1) ); 

How to prevent column break within an element?

The following code works to prevent column breaks inside elements:

-webkit-column-break-inside: avoid;
-moz-column-break-inside: avoid;
-o-column-break-inside: avoid;
-ms-column-break-inside: avoid;
column-break-inside: avoid;

Setting selected values for ng-options bound select elements

Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2

_x000D_
_x000D_
<select ng-model="objBillingAddress.StateId"  >_x000D_
   <option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
                                                </select>
_x000D_
_x000D_
_x000D_

Calculating distance between two geographic locations

distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).

distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]

hope that this helps

i've used distanceTo to get the distance from point A to B i think that is the way to go.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

I got this error after my computer froze and rebooted on its own. The solution for me was not found on this page, rather on another very highly rated SO question with the same error psql: could not connect to server: No such file or directory (Mac OS X). The answer: just delete this file /usr/local/var/postgres/postmaster.pid, then brew services restart postgresql did the trick. Heed the warning on the linked answer about killing postgres processes before doing this else you could corrupt your db permanently.

Why does python use 'else' after for and while loops?

I was just trying to make sense of it again myself. I found that the following helps!

• Think of the else as being paired with the if inside the loop (instead of with the for) - if condition is met then break the loop, else do this - except it's one else paired with multiple ifs!
• If no ifs were satisfied at all, then do the else.
• The multiple ifs can also actually be thought of as if-elifs!

javax.servlet.ServletException cannot be resolved to a type in spring web app

<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.2-b02</version>
    <scope>provided</scope>
</dependency>

worked for me.

sendmail: how to configure sendmail on ubuntu?

When you typed in sudo sendmailconfig, you should have been prompted to configure sendmail.

For reference, the files that are updated during configuration are located at the following (in case you want to update them manually):

/etc/mail/sendmail.conf
/etc/cron.d/sendmail
/etc/mail/sendmail.mc

You can test sendmail to see if it is properly configured and setup by typing the following into the command line:

$ echo "My test email being sent from sendmail" | /usr/sbin/sendmail [email protected]

The following will allow you to add smtp relay to sendmail:

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

Add the following lines to sendmail.mc, but before the MAILERDEFINITIONS. Make sure you update your smtp server.

define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/auth/client-info.db')dnl

Invoke creation sendmail.cf (alternatively run make -C /etc/mail):

m4 sendmail.mc > sendmail.cf

Restart the sendmail daemon:

service sendmail restart

<button> vs. <input type="button" />. Which to use?

This article seems to offer a pretty good overview of the difference.

From the page:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to “image”, but the BUTTON element type allows content.

The Button Element - W3C

TSQL CASE with if comparison in SELECT statement

Please select the same in the outer select. You can't access the alias name in the same query.

SELECT *, (CASE
        WHEN articleNumber < 2 THEN 'Ama'
        WHEN articleNumber < 5 THEN 'SemiAma' 
        WHEN articleNumber < 7 THEN 'Good'  
        WHEN articleNumber < 9 THEN 'Better' 
        WHEN articleNumber < 12 THEN 'Best'
        ELSE 'Outstanding'
        END) AS ranking 
FROM(
    SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber, 
    hobbies, etc...
    FROM USERS
)x

libaio.so.1: cannot open shared object file

I'm having a similar issue.

I found

conda install pyodbc

is wrong!

when I use

apt-get install python-pyodbc

I solved this problem?

Node / Express: EADDRINUSE, Address already in use - Kill server

Kill only node process that uses given PORT. As others mentioned, in bash you could use kill $(lsof -t -i:PORT)

Here is a Windows solution (there's a way!): netstat -bona | findstr ".0:PORT +0.0.0.0:0 +LISTENING" | for /f "tokens=5" %t in ('more') do taskkill /PID:%t /F. You need an elevated terminal for that (in VSCode you'll need to open itself with elevation, as integrated terminal cannot be elevated).

PS: if findstr not available, you can simply use find and replace " +" for spaces (non regex mode)

graphing an equation with matplotlib

This is because in line

graph(x**3+2*x-4, range(-10, 11))

x is not defined.

The easiest way is to pass the function you want to plot as a string and use eval to evaluate it as an expression.

So your code with minimal modifications will be

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = eval(formula)
    plt.plot(x, y)  
    plt.show()

and you can call it as

graph('x**3+2*x-4', range(-10, 11))

Collections.emptyList() returns a List<Object>?

You want to use:

Collections.<String>emptyList();

If you look at the source for what emptyList does you see that it actually just does a

return (List<T>)EMPTY_LIST;

python dataframe pandas drop column using int

If you have two columns with the same name. One simple way is to manually rename the columns like this:-

df.columns = ['column1', 'column2', 'column3']

Then you can drop via column index as you requested, like this:-

df.drop(df.columns[1], axis=1, inplace=True)

df.column[1] will drop index 1.

Remember axis 1 = columns and axis 0 = rows.

How do I schedule jobs in Jenkins?

The steps for schedule jobs in Jenkins:

  1. click on "Configure" of the job requirement
  2. scroll down to "Build Triggers" - subtitle
  3. Click on the checkBox of Build periodically
  4. Add time schedule in the Schedule field, for example, @midnight

enter image description here

Note: under the schedule field, can see the last and the next date-time run.

Jenkins also supports predefined aliases to schedule build:

@hourly, @daily, @weekly, @monthly, @midnight

@hourly --> Build every hour at the beginning of the hour --> 0 * * * *

@daily, @midnight --> Build every day at midnight --> 0 0 * * *

@weekly --> Build every week at midnight on Sunday morning --> 0 0 * * 0

@monthly --> Build every month at midnight of the first day of the month --> 0 0 1 * *

vue.js 'document.getElementById' shorthand

Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.

This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.

'git status' shows changed files, but 'git diff' doesn't

Short Answer

Running git add sometimes helps.

Example

Git status is showing changed files and git diff is showing nothing...

> git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   package.json

no changes added to commit (use "git add" and/or "git commit -a")
> git diff
> 

...running git add resolves the inconsistency.

> git add
> git status
On branch master
nothing to commit, working directory clean
> 

mailto using javascript

With JavaScript you can create a link 'on the fly' using something like:

var mail = document.createElement("a");
mail.href = "mailto:[email protected]";
mail.click();

This is redirected by the browser to some mail client installed on the machine without losing the content of the current window ... and you would not need any API like 'jQuery'.

inverting image in Python with OpenCV

You almost did it. You were tricked by the fact that abs(imagem-255) will give a wrong result since your dtype is an unsigned integer. You have to do (255-imagem) in order to keep the integers unsigned:

def inverte(imagem, name):
    imagem = (255-imagem)
    cv2.imwrite(name, imagem)

You can also invert the image using the bitwise_not function of OpenCV:

imagem = cv2.bitwise_not(imagem)

How to check if a String is numeric in Java

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        boolean flag = true;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the String:");
        String str = sc.nextLine();

        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) > 48 && str.charAt(i) < 58) {
                flag = false;
                break;
            }
        }

        if(flag == true) {
            System.out.println("String is a valid String.");
        } else {
            System.out.println("String contains number.");
        }
    }
}

Dynamic array in C#

Dynamic Array Example:

Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];

for (int i = 0; i < number; i++)
{
    arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
    Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();

What is the difference between Session.Abandon() and Session.Clear()

Clearing a session removes the values that were stored there, but you still can add new ones there. After destroying the session you cannot add new values there.

'\r': command not found - .bashrc / .bash_profile

Issue maybe occured because of the file/script created/downloaded from a windows machine. Please try converting into linux file format.

dos2unix ./script_name.sh

or

dos2unix ~/.bashrc

New lines inside paragraph in README.md

You can use a backslash at the end of a line.
So this:

a\
b\
c

will then look like:

a
b
c

Notice that there is no backslash at the end of the last line (after the 'c' character).

Hibernate Group by Criteria Object

You can use the approach @Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:

    session.createCriteria(SomeTable.class)       
                    .add(Restrictions.ge("someColumn", xxxxx))      
                    .setProjection(Projections.projectionList()
                            .add(Projections.groupProperty("someColumn"))
                            .add(Projections.max("someColumn"))
                            .add(Projections.min("someColumn"))
                            .add(Projections.count("someColumn"))           
                    ).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));

List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();

Is it possible for UIStackView to scroll?

I present you the right solution

For Xcode 11+

Step 1: Add a ScrollView and resize it

enter image description hereenter image description here

Step 2: Add Constraints for a ScrollView

enter image description here

Step 3: Add a StackView into ScrollView, and resize it.

enter image description here

Step 4: Add Constraints for a StackView (Stask View -> Content Layout Guide -> "Leading, Top, Trailing, Bottom")

enter image description here enter image description here

Step 4.1: Correct Constraints -> Constant (... -> Constant = 0)

enter image description here enter image description here

Step 5: Add Constraints for a StackView (Stask View -> Frame Layout Guide -> "Equal Widths")

enter image description here enter image description here

Step 6 Example: Add two UIView(s) with HeightConstraints and RUN enter image description here enter image description here

I hope it will be useful for you like

Java get last element of a collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement = itr.next();
    }
    return lastElement;
}

Where do alpha testers download Google Play Android apps?

Here is a check list for you:

1) Is your app published? (Production APK is not required for publishing)

2) Did your alpha/beta testers "Accept invitation" to Google+ community or Google group?

3) Are your alpha/beta testers logged in their Google+ account?

4) Are your alpha/beta testers using your link from Google Play developer console? It has format like this: https://play.google.com/apps/testing/com.yourdomain.package

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

You are passing a target array of shape (x-dim, y-dim) while using as loss categorical_crossentropy. categorical_crossentropy expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:

from keras.utils import to_categorical
y_binary = to_categorical(y_int)

Alternatively, you can use the loss function sparse_categorical_crossentropy instead, which does expect integer targets.

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Wordpress - Images not showing up in the Media Library

Check Screen Options (dropdown tab in the upper right hand corner of the page), and make sure there are sane settings for what to show on screen. All the column settings should be checked, and there should be a positive number of media items being shown on screen.

If that is ok, then check Settings ? Media and make sure that Uploading Files folder is set to wp-content/uploads.

I believe these are the only settings that can be changed from the administrative screens.

How to Return partial view of another controller by controller?

Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared folder if shared between controllers (hence the name).

"Answer" (but not recommended - see below):

You can refer to views/partial views from another controller, by specifying the full path (including extension) like:

return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

or a relative path (no extension), based on the answer by @Max Toro

return PartialView("../ABC/XXX", zyxmodel);

BUT THIS IS NOT A GOOD IDEA ANYWAY

*Note: These are the only two syntax that work. not ABC\\XXX or ABC/XXX or any other variation as those are all relative paths and do not find a match.

Better Alternatives:

You can use Html.Renderpartial in your view instead, but it requires the extension as well:

Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);

Use @Html.Partial for inline Razor syntax:

@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)

You can use the ../controller/view syntax with no extension (again credit to @Max Toro):

@Html.Partial("../ControllerName/ViewName", modeldata)

Note: Apparently RenderPartial is slightly faster than Partial, but that is not important.

If you want to actually call the other controller, use:

@Html.Action("action", "controller", parameters)

Recommended solution: @Html.Action

My personal preference is to use @Html.Action as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).

You would normally pass just the required key values (like any other view) e.g. for your example:

@Html.Action("XXX", "ABC", new {id = model.xyzId })

This will execute the ABC.XXX action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).

Update Sep 2014:

I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action and controller names. To that end I added this simple View extension method to UrlHelper so you can say return PartialView(Url.View("actionName", "controllerName"), modelData):

public static class UrlHelperExtension
{
    /// <summary>
    /// Return a view path based on an action name and controller name
    /// </summary>
    /// <param name="url">Context for extension method</param>
    /// <param name="action">Action name</param>
    /// <param name="controller">Controller name</param>
    /// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
    public static string View(this UrlHelper url, string action, string controller)
    {
        return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
    }
}

How to disable Django's CSRF validation?

For Django 2:

from django.utils.deprecation import MiddlewareMixin


class DisableCSRF(MiddlewareMixin):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)

That middleware must be added to settings.MIDDLEWARE when appropriate (in your test settings for example).

Note: the setting isn't not called MIDDLEWARE_CLASSES anymore.

Key value pairs using JSON

JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.

Since Javascripts objects consists of key/value pairs its very easy to use and access JSON that way.

So if we have an object:

var myObj = {
    foo:   'bar',
    base:  'ball',
    deep:  {
       java:  'script'
    }
};

We can convert that into a string by calling window.JSON.stringify(myObj); with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}".

The other way around, we would call window.JSON.parse("a json string like the above");.

JSON.parse() returns a javascript object/array on success.

alert(myObj.deep.java);  // 'script'

window.JSON is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.

How do I check for null values in JavaScript?

You can use lodash module to check value is null or undefined

_.isNil(value)
Example 

 country= "Abc"
    _.isNil(country)
    //false

   state= null
    _.isNil(state)
    //true

city= undefined
    _.isNil(state)
    //true

   pin= true
    _.isNil(pin)
    // false   

Reference link: https://lodash.com/docs/#isNil

Clicking HTML 5 Video element to play, pause video, breaks play button

Following up on ios-lizard's idea:

I found out that the controls on the video are about 35 pixels. This is what I did:

$(this).on("click", function(event) {
    console.log("clicked");
    var offset = $(this).offset();
    var height = $(this).height();
    var y = (event.pageY - offset.top - height) * -1;
    if (y > 35) {
        this.paused ? this.play() : this.pause();
    }
});

Basically, it finds the position of the click relative to the element. I multiplied it by -1 to make it positive. If the value was greater than 35 (the height of the controls) that means that the user click somewhere else than the controls Therefore we pause or play the video.

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

In my case I forgot to include the "stdafx.h" in the header file where I was declaring a template function.

Automatically plot different colored lines

Late answer, but two things to add:

  • For information on how to change the 'ColorOrder' property and how to set a global default with 'DefaultAxesColorOrder', see the "Appendix" at the bottom of this post.
  • There is a great tool on the MATLAB Central File Exchange to generate any number of visually distinct colors, if you have the Image Processing Toolbox to use it. Read on for details.

The ColorOrder axes property allows MATLAB to automatically cycle through a list of colors when using hold on/all (again, see Appendix below for how to set/get the ColorOrder for a specific axis or globally via DefaultAxesColorOrder). However, by default MATLAB only specifies a short list of colors (just 7 as of R2013b) to cycle through, and on the other hand it can be problematic to find a good set of colors for more data series. For 10 plots, you obviously cannot rely on the default ColorOrder.

A great way to define N visually distinct colors is with the "Generate Maximally Perceptually-Distinct Colors" (GMPDC) submission on the MATLAB Central File File Exchange. It is best described in the author's own words:

This function generates a set of colors which are distinguishable by reference to the "Lab" color space, which more closely matches human color perception than RGB. Given an initial large list of possible colors, it iteratively chooses the entry in the list that is farthest (in Lab space) from all previously-chosen entries.

For example, when 25 colors are requested:

25 "maximally perceptually-distinct colors"

The GMPDC submission was chosen on MathWorks' official blog as Pick of the Week in 2010 in part because of the ability to request an arbitrary number of colors (in contrast to MATLAB's built in 7 default colors). They even made the excellent suggestion to set MATLAB's ColorOrder on startup to,

distinguishable_colors(20)

Of course, you can set the ColorOrder for a single axis or simply generate a list of colors to use in any way you like. For example, to generate 10 "maximally perceptually-distinct colors" and use them for 10 plots on the same axis (but not using ColorOrder, thus requiring a loop):

% Starting with X of size N-by-P-by-2, where P is number of plots
mpdc10 = distinguishable_colors(10) % 10x3 color list
hold on
for ii=1:size(X,2),
    plot(X(:,ii,1),X(:,ii,2),'.','Color',mpdc10(ii,:));
end

The process is simplified, requiring no for loop, with the ColorOrder axis property:

% X of size N-by-P-by-2
mpdc10 = distinguishable_colors(10)
ha = axes; hold(ha,'on')
set(ha,'ColorOrder',mpdc10)    % --- set ColorOrder HERE ---
plot(X(:,:,1),X(:,:,2),'-.')   % loop NOT needed, 'Color' NOT needed. Yay!

APPENDIX

To get the ColorOrder RGB array used for the current axis,

get(gca,'ColorOrder')

To get the default ColorOrder for new axes,

get(0,'DefaultAxesColorOrder')

Example of setting new global ColorOrder with 10 colors on MATLAB start, in startup.m:

set(0,'DefaultAxesColorOrder',distinguishable_colors(10))

Restful API service

Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)

No you have to create a thread yourself, a Local service runs in the UI thread by default.

Python 3: ImportError "No Module named Setuptools"

The distribute package provides a Python 3-compatible version of setuptools: http://pypi.python.org/pypi/distribute

Also, use pip to install the modules. It automatically finds dependencies and installs them for you.

It works just fine for me with your package:

[~] pip --version                                                              
pip 1.2.1 from /usr/lib/python3.3/site-packages (python 3.3)
[~] sudo pip install ansicolors                                                
Downloading/unpacking ansicolors
  Downloading ansicolors-1.0.2.tar.gz
  Running setup.py egg_info for package ansicolors

Installing collected packages: ansicolors
  Running setup.py install for ansicolors

Successfully installed ansicolors
Cleaning up...
[~]

HashMap allows duplicates?

m.put(null,null); // here key=null, value=null
m.put(null,a);    // here also key=null, and value=a

Duplicate keys are not allowed in hashmap.
However,value can be duplicated.

Getting a list of associative array keys

I am currently using Rob de la Cruz's reply:

Object.keys(obj)

And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.

if (!Object.keys) {
    Object.keys = function(object) {
        var keys = [];
        for (var o in object) {
            if (object.hasOwnProperty(o)) {
                keys.push(o);
            }
        }
        return keys;
    };
}

I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.

Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.

Get all column names of a DataTable into string array using (LINQ/Predicate)

List<String> lsColumns = new List<string>();

if(dt.Rows.Count>0)
{
    var count = dt.Rows[0].Table.Columns.Count;

    for (int i = 0; i < count;i++ )
    {
        lsColumns.Add(Convert.ToString(dt.Rows[0][i]));
    }
}

Upgrading Node.js to latest version

Install npm =>

sudo apt-get install npm

Install n =>

sudo npm install n -g

latest version of node =>

sudo n latest 

So latest version will be downloaded and installed

Specific version of node you can

List available node versions =>

n ls

Install a specific version =>

sudo n 4.5.0

System.Collections.Generic.List does not contain a definition for 'Select'

I had this issue , When calling Generic.List like:

mylist.Select( selectFunc )

Where selectFunc is defined as Expression<Func<T, List<string>>>. Simply changed "mylist" to be a IQuerable instead of List then it allowed me to use .Select.

Dynamic classname inside ngClass in angular 2

i want to mention some important point to bare in mind while implementing class binding.

    [ngClass] = "{
    'badge-secondary': somevariable  === value1,
    'badge-danger': somevariable  === value1,
    'badge-warning': somevariable  === value1,
    'badge-warning': somevariable  === value1,
    'badge-success': somevariable  === value1 }" 

class here is not binding correctly because one condition is to be met, whereas you have two identical classes 'badge-warning' that may have two different condition. To correct this

 [ngClass] = "{
    'badge-secondary': somevariable === value1,
    'badge-danger': somevariable  === value1,
    'badge-warning': somevariable  === value1 || somevariable  === value1, 
    'badge-success': somevariable  === value1 }" 

Alternative to iFrames with HTML5

You can use object and embed, like so:

<object data="http://www.web-source.net" width="600" height="400">
    <embed src="http://www.web-source.net" width="600" height="400"> </embed>
    Error: Embedded data could not be displayed.
</object>

Which isn't new, but still works. I'm not sure if it has the same functionality though.

npm not working - "read ECONNRESET"

I had the same issue in windows while installing any package from npm. Fixed that with - ** open command prompt as administrator and run these 3 commands **/

1. npm config rm proxy

2. npm config rm https-proxy

3. npm install npm@latest -g

FOR MAC / LINUX
1. sudo npm config rm proxy

2. sudo npm config rm https-proxy

3. sudo npm install npm@latest -g

Basically this was version isuue with npm . Please check its worrking

How can I do division with variables in a Linux shell?

Those variables are shell variables. To expand them as parameters to another program (ie expr), you need to use the $ prefix:

expr $x / $y

The reason it complained is because it thought you were trying to operate on alphabetic characters (ie non-integer)

If you are using the Bash shell, you can achieve the same result using expression syntax:

echo $((x / y))

Or:

z=$((x / y))
echo $z

Software Design vs. Software Architecture

Architecture is high level, abstract and logical design whereas software design is low level,detailed and physical design.

how to store Image as blob in Sqlite & how to retrieve it?

for a ionic project


    var imgURI       = "";
    var imgBBDD      = ""; //sqllite for save into

    function takepicture() {
                var options = {
                    quality : 75,
                    destinationType : Camera.DestinationType.DATA_URL,
                    sourceType : Camera.PictureSourceType.CAMERA,
                    allowEdit : true,
                    encodingType: Camera.EncodingType.JPEG,
                    targetWidth: 300,
                    targetHeight: 300,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: false
                };

                $cordovaCamera.getPicture(options).then(function(imageData) {
                    imgURI = "data:image/jpeg;base64," + imageData;
                    imgBBDD = imageData;
                }, function(err) {
                    // An error occured. Show a message to the user
                });
            }

And now we put imgBBDD into SqlLite


     function saveImage = function (theId, theimage){
      var insertQuery = "INSERT INTO images(id, image) VALUES("+theId+", '"+theimage+"');"
      console.log('>>>>>>>');
      DDBB.SelectQuery(insertQuery)
                    .then( function(result) {
                        console.log("Image saved");
                    })
                    .catch( function(err) 
                     {
                        deferred.resolve(err);
                        return cb(err);
                    });
    }

A server side (php)


        $request = file_get_contents("php://input"); // gets the raw data
        $dades = json_decode($request,true); // true for return as array


    if($dades==""){
            $array = array();
            $array['error'] = -1;
            $array['descError'] = "Error when get the file";
            $array['logError'] = '';
            echo json_encode($array);
            exit;
        }
        //send the image again to the client
        header('Content-Type: image/jpeg');
        echo '';

Comparing Class Types in Java

It prints true on my machine. And it should, otherwise nothing in Java would work as expected. (This is explained in the JLS: 4.3.4 When Reference Types Are the Same)

Do you have multiple classloaders in place?


Ah, and in response to this comment:

I realise I have a typo in my question. I should be like this:

MyImplementedObject obj = new MyImplementedObject ();
if(obj.getClass() == MyObjectInterface.class) System.out.println("true");

MyImplementedObject implements MyObjectInterface So in other words, I am comparing it with its implemented objects.

OK, if you want to check that you can do either:

if(MyObjectInterface.class.isAssignableFrom(obj.getClass()))

or the much more concise

if(obj instanceof MyobjectInterface)

pip3: command not found but python3-pip is already installed

There is no need to install virtualenv. Just create a workfolder and open your editor in it. Assuming you are using vscode,

$mkdir Directory && cd Directory
$code .

It is the best way to avoid breaking Ubuntu/linux dependencies by messing around with environments. In case anything goes wrong, you can always delete that folder and begin afresh. Otherwise, messing up with the ubuntu/linux python environments could mess up system apps/OS (including the terminal). Then you can press shift+P and type python:select interpreter. Choose any version above 3. After that you can do

$pip3 -v

It will display the pip version. You can then use it for installations as

$pip3 install Library

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

getApplication() vs. getApplicationContext()

Compare getApplication() and getApplicationContext().

getApplication returns an Application object which will allow you to manage your global application state and respond to some device situations such as onLowMemory() and onConfigurationChanged().

getApplicationContext returns the global application context - the difference from other contexts is that for example, an activity context may be destroyed (or otherwise made unavailable) by Android when your activity ends. The Application context remains available all the while your Application object exists (which is not tied to a specific Activity) so you can use this for things like Notifications that require a context that will be available for longer periods and independent of transient UI objects.

I guess it depends on what your code is doing whether these may or may not be the same - though in normal use, I'd expect them to be different.

What is the meaning of the word logits in TensorFlow?

They are basically the fullest learned model you can get from the network, before it's been squashed down to apply to only the number of classes we are interested in. Check out how some researchers use them to train a shallow neural net based on what a deep network has learned: https://arxiv.org/pdf/1312.6184.pdf

It's kind of like how when learning a subject in detail, you will learn a great many minor points, but then when teaching a student, you will try to compress it to the simplest case. If the student now tried to teach, it'd be quite difficult, but would be able to describe it just well enough to use the language.

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

Combine several images horizontally with Python

Just adding to the solutions already suggested. Assumes same height, no resizing.

import sys
import glob
from PIL import Image
Image.MAX_IMAGE_PIXELS = 100000000  # For PIL Image error when handling very large images

imgs    = [ Image.open(i) for i in list_im ]

widths, heights = zip(*(i.size for i in imgs))
total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

# Place first image
new_im.paste(imgs[0],(0,0))

# Iteratively append images in list horizontally
hoffset=0
for i in range(1,len(imgs),1):
    **hoffset=imgs[i-1].size[0]+hoffset  # update offset**
    new_im.paste(imgs[i],**(hoffset,0)**)

new_im.save('output_horizontal_montage.jpg')

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

How to use Redirect in the new react-router-dom of Reactjs

Alternatively, you can use withRouter. You can get access to the history object's properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

import React from "react"
import PropTypes from "prop-types"
import { withRouter } from "react-router"

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return <div>You are now at {location.pathname}</div>
  }
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

Or just:

import { withRouter } from 'react-router-dom'

const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
))

How can I invert color using CSS?

Here is a different approach using mix-blend-mode: difference, that will actually invert whatever the background is, not just a single colour:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
  color: white;_x000D_
  mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ssl_error_rx_record_too_long and Apache SSL

In my case, I had the wrong IP Address in the virtual host file. The listen was 443, and the stanza was <VirtualHost 192.168.0.1:443> but the server did not have the 192.168.0.1 address!

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

What is a simple C or C++ TCP server and client example?

If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like boost::asio are imho quite complicated when it comes to short and simple "hello world" example.

To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
http://www.linuxhowtos.org/data/6/server.c
http://www.linuxhowtos.org/data/6/client.c
from: http://www.linuxhowtos.org/C_C++/socket.htm

  1. Add following includes to both files:

    #include <cstdlib>
    #include <cstring>
    #include <unistd.h>
    
  2. In client.c, change the line:

    if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

    to:

    if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

As you can see in C++ an explicit cast is needed.

Event binding on dynamically created elements?

Here is why dynamically created elements do not respond to clicks :

_x000D_
_x000D_
var body = $("body");_x000D_
var btns = $("button");_x000D_
var btnB = $("<button>B</button>");_x000D_
// `<button>B</button>` is not yet in the document._x000D_
// Thus, `$("button")` gives `[<button>A</button>]`._x000D_
// Only `<button>A</button>` gets a click listener._x000D_
btns.on("click", function () {_x000D_
  console.log(this);_x000D_
});_x000D_
// Too late for `<button>B</button>`..._x000D_
body.append(btnB);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

As a workaround, you have to listen to all clicks and check the source element :

_x000D_
_x000D_
var body = $("body");_x000D_
var btnB = $("<button>B</button>");_x000D_
var btnC = $("<button>C</button>");_x000D_
// Listen to all clicks and_x000D_
// check if the source element_x000D_
// is a `<button></button>`._x000D_
body.on("click", function (ev) {_x000D_
  if ($(ev.target).is("button")) {_x000D_
    console.log(ev.target);_x000D_
  }_x000D_
});_x000D_
// Now you can add any number_x000D_
// of `<button></button>`._x000D_
body.append(btnB);_x000D_
body.append(btnC);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)

_x000D_
_x000D_
var i = 11;_x000D_
var body = $("body");_x000D_
body.on("click", "button", function () {_x000D_
  var letter = (i++).toString(36).toUpperCase();_x000D_
  body.append($("<button>" + letter + "</button>"));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

PermissionError: [Errno 13] in python

I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32 instead of the usual directory from which I run my python module

Is there a method to generate a UUID with go language

You can generate UUIDs using the go-uuid library. This can be installed with:

go get github.com/nu7hatch/gouuid

You can generate random (version 4) UUIDs with:

import "github.com/nu7hatch/gouuid"

...

u, err := uuid.NewV4()

The returned UUID type is a 16 byte array, so you can retrieve the binary value easily. It also provides the standard hex string representation via its String() method.

The code you have also looks like it will also generate a valid version 4 UUID: the bitwise manipulation you perform at the end set the version and variant fields of the UUID to correctly identify it as version 4. This is done to distinguish random UUIDs from ones generated via other algorithms (e.g. version 1 UUIDs based on your MAC address and time).

How to update each dependency in package.json to the latest version?

  1. Use * as the version for the latest releases, including unstable
  2. Use latest as version definition for the latest stable version
  3. Modify the package.json with exactly the latest stable version number using LatestStablePackages

Here is an example:

"dependencies": {
        "express": "latest"  // using the latest STABLE version
    ,   "node-gyp": "latest"    
    ,   "jade": "latest"
    ,   "mongoose": "*" // using the newest version, may involve the unstable releases
    ,   "cookie-parser": "latest"
    ,   "express-session": "latest"
    ,   "body-parser": "latest"
    ,   "nodemailer":"latest"
    ,   "validator": "latest"
    ,   "bcrypt": "latest"
    ,   "formidable": "latest"
    ,   "path": "latest"
    ,   "fs-extra": "latest"
    ,   "moment": "latest"
    ,   "express-device": "latest"
},

How can I get the file name from request.FILES?

file = request.FILES['filename']
file.name           # Gives name
file.content_type   # Gives Content type text/html etc
file.size           # Gives file's size in byte
file.read()         # Reads file

How do I exclude Weekend days in a SQL Server query?

Assuming you're using SQL Server, use DATEPART with dw:

SELECT date_created
FROM your_table
WHERE DATEPART(dw, date_created) NOT IN (1, 7);

EDIT: I should point out that the actual numeric value returned by DATEPART(dw) is determined by the value set by using SET DATEFIRST:
http://msdn.microsoft.com/en-us/library/ms181598.aspx

How to run regasm.exe from command line other than Visual Studio command prompt?

I really dislike the hard coding of paths to get to regasm, when you install a new .Net or run on a machine with a different version, you need to ensure you find a version of regasm. Here's a solution to find the regasm.exe from the most current .Net installed regasm.

Within a bat file:

for /f %%a in ('dir %windir%\Microsoft.Net\Framework\regasm.exe /s /b') do set currentRegasm="%%a"
%currentRegasm% "full\path\to\your.dll" /options

Outside of a bat file (i.e. command prompt), just use %a instead of %%a

When increasing the size of VARCHAR column on a large table could there be any problems?

This is a metadata change only: it is quick.

An observation: specify NULL or NOT NULL explicitly to avoid "accidents" if one of the SET ANSI_xx settings are different eg run in osql not SSMS for some reason