Programs & Examples On #Feature branch

How can I delete all Git branches which have been merged?

Given you want to delete the merged branches, you need to delete the remote-tracking branches only, unless you state otherwise.

So to delete those branches you can do it by

git branch --remote --merged origin/master | egrep -v "(^\*|master|development)" | cut -b 10- | xargs git push --delete origin

This will delete all merged branches (merged to master) except master and development.

Rebase feature branch onto another feature branch

  1. Switch to Branch2

    git checkout Branch2
    
  2. Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:

    git rebase Branch1
    

Which would leave you with the desired result in Branch2:

a -- b -- c                      <-- Master
           \
            d -- e               <-- Branch1
           \
            d -- e -- f' -- g'   <-- Branch2

You can delete Branch1.

Rebasing remote branches in Git

It comes down to whether the feature is used by one person or if others are working off of it.

You can force the push after the rebase if it's just you:

git push origin feature -f

However, if others are working on it, you should merge and not rebase off of master.

git merge master
git push origin feature

This will ensure that you have a common history with the people you are collaborating with.

On a different level, you should not be doing back-merges. What you are doing is polluting your feature branch's history with other commits that don't belong to the feature, making subsequent work with that branch more difficult - rebasing or not.

This is my article on the subject called branch per feature.

Hope this helps.

Git merge master into feature branch

Zimi's answer describes this process generally. Here are the specifics:

  1. Create and switch to a new branch. Make sure the new branch is based on master so it will include the recent hotfixes.

    git checkout master
    git branch feature1_new
    git checkout feature1_new
    
    # Or, combined into one command:
    git checkout -b feature1_new master
    
  2. After switching to the new branch, merge the changes from your existing feature branch. This will add your commits without duplicating the hotfix commits.

    git merge feature1
    
  3. On the new branch, resolve any conflicts between your feature and the master branch.

Done! Now use the new branch to continue to develop your feature.

Display html text in uitextview

Use following block of code for ios 7+.

NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p><img src='http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg' width=70 height=100 />";
NSAttributedString *attributedString = [[NSAttributedString alloc]
          initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
               options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
    documentAttributes: nil
                 error: nil
];
textView.attributedText = attributedString;

How to clear variables in ipython?

Apart from the methods mentioned earlier. You can also use the command del to remove multiple variables

del variable1,variable2

How can I create an error 404 in PHP?

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

It helped me: Go AndroidManifest and paste or replace with this code

<provider
        android:authorities="${applicationId}.here.this.library.provider"
        android:name="androidx.core.content.FileProvider"
        android:exported="false"
        android:grantUriPermissions="true"
        tools:replace="android:authorities" >

    </provider>

How to alter a column's data type in a PostgreSQL table?

If data already exists in the column you should do:

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;

As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.

How can I interrupt a running code in R with a keyboard command?

Try out Ctrl + z But it will kill the process, not suspend it.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

The best solution i found out is to mute the video

HTML

<video loop muted autoplay id="videomain">
  <source src="videoname.mp4" type="video/mp4">
</video>

What is the default Jenkins password?

jenkins default administrator password is logged in log file in ubuntu

log file is situated in /var/log/jenkins/jenkins.log folder

password will be placed after this, Jenkins initial setup is required. An admin user has been created and a password generated. Please use the following password to proceed to installation:

Best way to handle multiple constructors in Java

You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).

These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:

class Book {
    private String title; // not nullable
    private String isbn;  // nullable

    // Here we provide a default value, but we could also skip the 
    // parameterless constructor entirely, to force users of the class to
    // provide a title
    public Book()
    {
        this("Untitled"); 
    }

    public Book(String title) throws IllegalArgumentException
    {
        if (title == null) 
            throw new IllegalArgumentException("Book title can't be null");
        this.title = title;
        // leave isbn without value
    }
    // Constructor with title and isbn
}

However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

The only solution that worked for me

  1. Run, Type command %Temp% -> Deleting "Temporary ASP.NET Files".

Other solutions I have tried, which didn't work.

  1. Cleaning/Rebuilding

  2. Cleaning bin, obj folders

  3. Changing namespace

jquery change class name

I think he wants to replace a class name.

Something like this would work:

$(document).ready(function(){
    $('.blue').removeClass('blue').addClass('green');
});

from http://monstertut.com/2012/06/use-jquery-to-change-css-class/

How to divide flask app into multiple py files?

This task can be accomplished without blueprints and tricky imports using Centralized URL Map

app.py

import views
from flask import Flask

app = Flask(__name__)

app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

views.py

from flask import render_template

def index():
    return render_template('index.html')

def other():
    return render_template('other.html')

Setting different color for each series in scatter plot on matplotlib

A MUCH faster solution for large dataset and limited number of colors is the use of Pandas and the groupby function:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time


# a generic set of data with associated colors
nsamples=1000
x=np.random.uniform(0,10,nsamples)
y=np.random.uniform(0,10,nsamples)
colors={0:'r',1:'g',2:'b',3:'k'}
c=[colors[i] for i in np.round(np.random.uniform(0,3,nsamples),0)]

plt.close('all')

# "Fast" Scatter plotting
starttime=time.time()
# 1) make a dataframe
df=pd.DataFrame()
df['x']=x
df['y']=y
df['c']=c
plt.figure()
# 2) group the dataframe by color and loop
for g,b in df.groupby(by='c'):
    plt.scatter(b['x'],b['y'],color=g)
print('Fast execution time:', time.time()-starttime)

# "Slow" Scatter plotting
starttime=time.time()
plt.figure()
# 2) group the dataframe by color and loop
for i in range(len(x)):
    plt.scatter(x[i],y[i],color=c[i])
print('Slow execution time:', time.time()-starttime)

plt.show()

Can you control how an SVG's stroke-width is drawn?

As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.

The specification for strokes in Adobe's PostScript Manual 2nd edition states: "4.5.1 Stroking: The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)

The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.

Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.

How to disable sort in DataGridView?

It's very simple:

foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
{
    dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
}

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Below is the exact code you need to make your sheet look exactly as it is in the attached PDF:

try
        {
            Excel.Application application;
            Excel.Workbook workBook;
            Excel.Worksheet workSheet;
            object misValue = System.Reflection.Missing.Value;

            application = new Excel.ApplicationClass();
            workBook = application.Workbooks.Add(misValue);
            workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);

            int i = 1;
            workSheet.Cells[i, 2] = "MSS Close Sheet"; 
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;               
            i++;
            workSheet.Cells[i, 2] = "MSS - " + dpsNoTextBox.Text;
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;
            workSheet.Cells[i, 2] = customerNameTextBox.Text;
            i++;                
            workSheet.Cells[i, 2] = "Opening Date : ";
            workSheet.Cells[i, 3] = openingDateTextBox.Value.ToShortDateString();
            i++;
            workSheet.Cells[i, 2] = "Closing Date : ";
            workSheet.Cells[i, 3] = closingDateTextBox.Value.ToShortDateString();
            i++;
            i++;
            i++;

            workSheet.Cells[i, 1] = "SL. No";
            workSheet.Cells[i, 2] = "Month";
            workSheet.Cells[i, 3] = "Amount Deposited";
            workSheet.Cells[i, 4] = "Fine";
            workSheet.Cells[i, 5] = "Cumulative Total";
            workSheet.Cells[i, 6] = "Profit + Cumulative Total";
            workSheet.Cells[i, 7] = "Profit @ " + profitRateComboBox.Text;
            WorkSheet.Cells[i, 1].EntireRow.Font.Bold = true;
            i++;



            /////////////////////////////////////////////////////////
            foreach (RecurringDeposit rd in RecurringDepositList)
            {
                workSheet.Cells[i, 1] = rd.SN.ToString();
                workSheet.Cells[i, 2] = rd.MonthYear;
                workSheet.Cells[i, 3] = rd.InstallmentSize.ToString();
                workSheet.Cells[i, 4] = "";
                workSheet.Cells[i, 5] = rd.CumulativeTotal.ToString();
                workSheet.Cells[i, 6] = rd.ProfitCumulative.ToString();
                workSheet.Cells[i, 7] = rd.Profit.ToString();
                i++;
            }
            //////////////////////////////////////////////////////


            ////////////////////////////////////////////////////////
            workSheet.Cells[i, 2] = "Total (" + RecurringDepositList.Count + " months installment)";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "a) Total Amount Deposited";
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "b) Fine";
            workSheet.Cells[i, 3] = "";
            i++;

            workSheet.Cells[i, 2] = "c) Total Pft Paid";
            workSheet.Cells[i, 3] = totalProfitPaidTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Sub Total";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (totalAmountDepositedTextBox.Value + totalProfitPaidTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Deduction";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;

            workSheet.Cells[i, 2] = "a) Excise Duty";
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "b) Income Tax on Pft. @ " + incomeTaxPercentageTextBox.Text;
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "c) Account Closing Charge ";
            workSheet.Cells[i, 3] = closingChargeCommaNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "d) Outstanding on BAIM(FO) ";
            workSheet.Cells[i, 3] = baimFOLowerTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Total Deduction ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (incomeTaxDeductionTextBox.Value + closingChargeCommaNumberTextBox.Value + baimFOTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Client Paid ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Current Balance ";
            workSheet.Cells[i, 3] = currentBalanceCommaNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "Exp. Pft paid on MSS A/C(PL67054)";
            workSheet.Cells[i, 6] = plTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Total Paid ";
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "IT on Pft (BDT16216)";
            workSheet.Cells[i, 6] = incomeTaxDeductionTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Difference";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (currentBalanceCommaNumberTextBox.Value - customerPayableNumberTextBox.Value).ToString("0.00");
            workSheet.Cells[i, 5] = "Account Closing Charge";
            workSheet.Cells[i, 6] = closingChargeCommaNumberTextBox.Value;
            i++;

            ///////////////////////////////////////////////////////////////

            workBook.SaveAs("D:\\" + dpsNoTextBox.Text.Trim() + "-" + customerNameTextBox.Text.Trim() + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            workBook.Close(true, misValue, misValue);
            application.Quit();

            releaseObject(workSheet);
            releaseObject(workBook);
            releaseObject(application);

How to run a .awk file?

If you put #!/bin/awk -f on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)

#!/bin/awk -f
BEGIN {}  # Begin section
{}        # Loop section
END{}     # End section

Change the file to be executable by running:

chmod ugo+x ./awk-script

and you can then call your AWK script like this:

`$ echo "something" | ./awk-script`

How do I declare and assign a variable on a single line in SQL

on sql 2008 this is valid

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable

on sql server 2005, you need to do this

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable

Data binding to SelectedItem in a WPF Treeview

Answer with attached properties and no external dependencies, should the need ever arise!

You can create an attached property that is bindable and has a getter and setter:

public class TreeViewHelper
{
    private static Dictionary<DependencyObject, TreeViewSelectedItemBehavior> behaviors = new Dictionary<DependencyObject, TreeViewSelectedItemBehavior>();

    public static object GetSelectedItem(DependencyObject obj)
    {
        return (object)obj.GetValue(SelectedItemProperty);
    }

    public static void SetSelectedItem(DependencyObject obj, object value)
    {
        obj.SetValue(SelectedItemProperty, value);
    }

    // Using a DependencyProperty as the backing store for SelectedItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.RegisterAttached("SelectedItem", typeof(object), typeof(TreeViewHelper), new UIPropertyMetadata(null, SelectedItemChanged));

    private static void SelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is TreeView))
            return;

        if (!behaviors.ContainsKey(obj))
            behaviors.Add(obj, new TreeViewSelectedItemBehavior(obj as TreeView));

        TreeViewSelectedItemBehavior view = behaviors[obj];
        view.ChangeSelectedItem(e.NewValue);
    }

    private class TreeViewSelectedItemBehavior
    {
        TreeView view;
        public TreeViewSelectedItemBehavior(TreeView view)
        {
            this.view = view;
            view.SelectedItemChanged += (sender, e) => SetSelectedItem(view, e.NewValue);
        }

        internal void ChangeSelectedItem(object p)
        {
            TreeViewItem item = (TreeViewItem)view.ItemContainerGenerator.ContainerFromItem(p);
            item.IsSelected = true;
        }
    }
}

Add the namespace declaration containing that class to your XAML and bind as follows (local is how I named the namespace declaration):

        <TreeView ItemsSource="{Binding Path=Root.Children}" local:TreeViewHelper.SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}">

    </TreeView>

Now you can bind the selected item, and also set it in your view model to change it programmatically, should that requirement ever arise. This is, of course, assuming that you implement INotifyPropertyChanged on that particular property.

Using Mysql WHERE IN clause in codeigniter

You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now subquery writing in available And now here is your query with active record

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');

And the thing is done. Cheers!!!
Note : While using sub queries you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.
Watch this too

How can I rewrite this SQL into CodeIgniter's Active Records?

Note : In Codeigntier 3 these functions are already public so you do not need to hack them.

How can I find where Python is installed on Windows?

I installed 2 and 3 and had the same problem finding 3. Fortunately, typing path at the windows path let me find where I had installed it. The path was an option when I installed Python which I just forgot. If you didn't select setting the path when you installed Python 3 that probably won't work - unless you manually updated the path when you installed it. In my case it was at c:\Program Files\Python37\python.exe

How to center text vertically with a large font-awesome icon?

For those using Bootstrap 4 is simple:

<span class="align-middle"><i class="fas fa-camera"></i></span>

How to repeat last command in python interpreter shell?

For repeating the last command in python, you can use <Alt + n> in windows

Getting a map() to return a list in Python 3.x

Converting my old comment for better visibility: For a "better way to do this" without map entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert to bytes and decode, a la bytes(list_of_ordinals).decode('ascii'). That gets you a str of the values, but if you need a list for mutability or the like, you can just convert it (and it's still faster). For example, in ipython microbenchmarks converting 45 inputs:

>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

If you leave it as a str, it takes ~20% of the time of the fastest map solutions; even converting back to list it's still less than 40% of the fastest map solution. Bulk convert via bytes and bytes.decode then bulk converting back to list saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1).

How to determine if a point is in a 2D triangle?

Java version of barycentric method:

class Triangle {
    Triangle(double x1, double y1, double x2, double y2, double x3,
            double y3) {
        this.x3 = x3;
        this.y3 = y3;
        y23 = y2 - y3;
        x32 = x3 - x2;
        y31 = y3 - y1;
        x13 = x1 - x3;
        det = y23 * x13 - x32 * y31;
        minD = Math.min(det, 0);
        maxD = Math.max(det, 0);
    }

    boolean contains(double x, double y) {
        double dx = x - x3;
        double dy = y - y3;
        double a = y23 * dx + x32 * dy;
        if (a < minD || a > maxD)
            return false;
        double b = y31 * dx + x13 * dy;
        if (b < minD || b > maxD)
            return false;
        double c = det - a - b;
        if (c < minD || c > maxD)
            return false;
        return true;
    }

    private final double x3, y3;
    private final double y23, x32, y31, x13;
    private final double det, minD, maxD;
}

The above code will work accurately with integers, assuming no overflows. It will also work with clockwise and anticlockwise triangles. It will not work with collinear triangles (but you can check for that by testing det==0).

The barycentric version is fastest if you are going to test different points with the same triangle.

The barycentric version is not symmetric in the 3 triangle points, so it is likely to be less consistent than Kornel Kisielewicz's edge half-plane version, because of floating point rounding errors.

Credit: I made the above code from Wikipedia's article on barycentric coordinates.

How to check if a date is in a given range?

Convert them into dates or timestamp integers and then just check of $date_from_user is <= $end_date and >= $start_date

How to get response using cURL in PHP

If anyone else comes across this, I'm adding another answer to provide the response code or other information that might be needed in the "response".

http://php.net/manual/en/function.curl-getinfo.php

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

// also get the error and response code
$errors = curl_error($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

var_dump($errors);
var_dump($response);

Output:

string(0) ""
int(200)

// change www.google.com to www.googlebofus.co
string(42) "Could not resolve host: www.googlebofus.co"
int(0)

Sending email in .NET through Gmail

Try this one

public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
        MailMessage mailMessage = new MailMessage();
        MailAddress mailAddress = new MailAddress("[email protected]", "Sender Name"); // [email protected] = input Sender Email Address 
        mailMessage.From = mailAddress;
        mailAddress = new MailAddress(receiverEmail, ReceiverName);
        mailMessage.To.Add(mailAddress);
        mailMessage.Subject = subject;
        mailMessage.Body = body;
        mailMessage.IsBodyHtml = true;

        SmtpClient mailSender = new SmtpClient("smtp.gmail.com", 587)
        {
            EnableSsl = true,
            UseDefaultCredentials = false,
            DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential("[email protected]", "pass")   // [email protected] = input sender email address  
                                                                           //pass = sender email password
        };

        try
        {
            mailSender.Send(mailMessage);
            return true;
        }
        catch (SmtpFailedRecipientException ex)
        { 
          // Write the exception to a Log file.
        }
        catch (SmtpException ex)
        { 
           // Write the exception to a Log file.
        }
        finally
        {
            mailSender = null;
            mailMessage.Dispose();
        }
        return false;
}

How to install Laravel's Artisan?

Explanation: When you install a new laravel project on your folder(for example myfolder) using the composer, it installs the complete laravel project inside your folder(myfolder/laravel) than artisan is inside laravel.that's, why you see an error,

Could not open input file: artisan

Solution: You have to go inside by command prompt to that location or move laravel files inside your folder.

Delete a row in DataGridView Control in VB.NET

Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)

Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If myDataGridView.SelectedRows.Count > 0 Then
            'you may want to add a confirmation message, and if the user confirms delete
            myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
        Else
            MessageBox.Show("Select 1 row before you hit Delete")
        End If

    End Sub

Note that this will not delete the row form the database until you perform the delete in the database.

Resource leak: 'in' is never closed

Scanner sc = new Scanner(System.in);

//do stuff with sc

sc.close();//write at end of code.

How to show text on image when hovering?

<!DOCTYPE html><html lang='en' class=''>
<head><script src='//production-assets.codepen.io/assets/editor/live/console_runner-079c09a0e3b9ff743e39ee2d5637b9216b3545af0de366d4b9aad9dc87e26bfd.js'></script><script src='//production-assets.codepen.io/assets/editor/live/events_runner-73716630c22bbc8cff4bd0f07b135f00a0bdc5d14629260c3ec49e5606f98fdd.js'></script><script src='//production-assets.codepen.io/assets/editor/live/css_live_reload_init-2c0dc5167d60a5af3ee189d570b1835129687ea2a61bee3513dee3a50c115a77.js'></script><meta charset='UTF-8'><meta name="robots" content="noindex"><link rel="shortcut icon" type="image/x-icon" href="//production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" /><link rel="mask-icon" type="" href="//production-assets.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" /><link rel="canonical" href="https://codepen.io/nelsonleite/pen/RaGwba?depth=everything&order=popularity&page=4&q=product&show_forks=false" />
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
<style class="cp-pen-styles">.product-description {
  transform: translate3d(0, 0, 0);
  transform-style: preserve-3d;
  perspective: 1000;
  backface-visibility: hidden;
}

body {
  color: #212121;
}

.container {
  padding-top: 25px;
  padding-bottom: 25px;
}

img {
  max-width: 100%;
}

hr {
  border-color: #e5e5e5;
  margin: 15px 0;
}

.secondary-text {
  color: #b6b6b6;
}

.list-inline {
  margin: 0;
}
.list-inline li {
  padding: 0;
}

.card-wrapper {
  position: relative;
  width: 100%;
  height: 390px;
  border: 1px solid #e5e5e5;
  border-bottom-width: 2px;
  overflow: hidden;
  margin-bottom: 30px;
}
.card-wrapper:after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  transition: opacity 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
}
.card-wrapper:hover:after {
  opacity: 1;
}
.card-wrapper:hover .image-holder:before {
  opacity: .75;
}
.card-wrapper:hover .image-holder:after {
  opacity: 1;
  transform: translate(-50%, -50%);
}
.card-wrapper:hover .image-holder--original {
  transform: translateY(-15px);
}
.card-wrapper:hover .product-description {
  height: 205px;
}
@media (min-width: 768px) {
  .card-wrapper:hover .product-description {
    height: 185px;
  }
}

.image-holder {
  display: block;
  position: relative;
  width: 100%;
  height: 310px;
  background-color: #ffffff;
  z-index: 1;
}
@media (min-width: 768px) {
  .image-holder {
    height: 325px;
  }
}
.image-holder:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #4CAF50;
  opacity: 0;
  z-index: 5;
  transition: opacity 0.6s;
}
.image-holder:after {
  content: '+';
  font-family: 'Raleway', sans-serif;
  font-size: 70px;
  color: #4CAF50;
  text-align: center;
  position: absolute;
  top: 92.5px;
  left: 50%;
  width: 75px;
  height: 75px;
  line-height: 75px;
  background-color: #ffffff;
  opacity: 0;
  border-radius: 50%;
  z-index: 10;
  transform: translate(-50%, 100%);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  transition: all 0.4s ease-out;
}
@media (min-width: 768px) {
  .image-holder:after {
    top: 107.5px;
  }
}
.image-holder .image-holder__link {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 15;
}
.image-holder .image-holder--original {
  transition: transform 0.8s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.image-liquid {
  width: 100%;
  height: 325px;
  background-size: cover;
  background-position: center center;
}

.product-description {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  padding: 10px 15px;
  overflow: hidden;
  background-color: #fafafa;
  border-top: 1px solid #e5e5e5;
  transition: height 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
  z-index: 2;
}
@media (min-width: 768px) {
  .product-description {
    height: 65px;
  }
}
.product-description p {
  margin: 0 0 5px;
}
.product-description .product-description__title {
  font-family: 'Raleway', sans-serif;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  margin: 0;
  font-size: 18px;
  line-height: 1.25;
}
.product-description .product-description__title:after {
  content: '';
  width: 60px;
  height: 100%;
  position: absolute;
  top: 0;
  right: 0;
  background: linear-gradient(to right, rgba(255, 255, 255, 0), #fafafa);
}
.product-description .product-description__title a {
  text-decoration: none;
  color: inherit;
}
.product-description .product-description__category {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.product-description .product-description__price {
  color: #4CAF50;
  text-align: left;
  font-weight: bold;
  letter-spacing: 0.06em;
}
@media (min-width: 768px) {
  .product-description .product-description__price {
    text-align: right;
  }
}
.product-description .sizes-wrapper {
  margin-bottom: 15px;
}
.product-description .color-list {
  font-size: 0;
}
.product-description .color-list__item {
  width: 25px;
  height: 10px;
  position: relative;
  z-index: 1;
  transition: all .2s;
}
.product-description .color-list__item:hover {
  width: 40px;
}
.product-description .color-list__item--red {
  background-color: #F44336;
}
.product-description .color-list__item--blue {
  background-color: #448AFF;
}
.product-description .color-list__item--green {
  background-color: #CDDC39;
}
.product-description .color-list__item--orange {
  background-color: #FF9800;
}
.product-description .color-list__item--purple {
  background-color: #673AB7;
}
</style></head><body>
<!--
Inspired in this dribbble
https://dribbble.com/shots/986548-Product-Catalog
-->

<div class="container">
    <div class="row">

        <div class="col-xs-12 col-sm-6 col-md-4">
            <article class="card-wrapper">
                <div class="image-holder">
                    <a href="#" class="image-holder__link"></a>
                    <div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/2/24/Blue_Tshirt.jpg')">
                    </div>
                </div>

                <div class="product-description">
                    <!-- title -->
                    <h1 class="product-description__title">
                        <a href="#">                        
                            Adidas Originals
                            </a>
                    </h1>

                    <!-- category and price -->
                    <div class="row">
                        <div class="col-xs-12 col-sm-8 product-description__category secondary-text">
                            Men's running shirt
                        </div>
                        <div class="col-xs-12 col-sm-4 product-description__price">
                            € 499
                        </div>
                    </div>

                    <!-- divider -->
                    <hr />

                    <!-- sizes -->
                    <div class="sizes-wrapper">
                        <b>Sizes</b>
                        <br />
                        <span class="secondary-text text-uppercase">
                            <ul class="list-inline">
                                <li>xs,</li>                                
                                <li>s,</li>                             
                                <li>sm,</li>                                
                                <li>m,</li>
                                <li>l,</li>                             
                                <li>xl,</li>                                
                                <li>xxl</li>                                
                            </ul>
                        </span>
                    </div>

                    <!-- colors -->
                    <div class="color-wrapper">
                        <b>Colors</b>
                        <br />
                        <ul class="list-inline color-list">
                            <li class="color-list__item color-list__item--red"></li>
                            <li class="color-list__item color-list__item--blue"></li>
                            <li class="color-list__item color-list__item--green"></li>
                            <li class="color-list__item color-list__item--orange"></li>
                            <li class="color-list__item color-list__item--purple"></li>
                        </ul>
                    </div>
                </div>

            </article>
        </div>

        <div class="col-xs-12 col-sm-6 col-md-4">
            <article class="card-wrapper">
                <div class="image-holder">
                    <a href="#" class="image-holder__link"></a>
                    <div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Jeans_BW_2_(3213391837).jpg/543px-Jeans_BW_2_(3213391837).jpg')">
                    </div>
                </div>

                <div class="product-description">
                    <!-- title -->
                    <h1 class="product-description__title">
                        <a href="#">                        
                            Adidas Originals
                            </a>
                    </h1>

                    <!-- category and price -->
                    <div class="row">
                        <div class="col-sm-8 product-description__category secondary-text">
                            Men's running shirt
                        </div>
                        <div class="col-sm-4 product-description__price text-right">
                            € 499
                        </div>
                    </div>

                    <!-- divider -->
                    <hr />

                    <!-- sizes -->
                    <div class="sizes-wrapper">
                        <b>Sizes</b>
                        <br />
                        <span class="secondary-text text-uppercase">
                            <ul class="list-inline">
                                <li>xs,</li>                                
                                <li>s,</li>                             
                                <li>sm,</li>                                
                                <li>m,</li>
                                <li>l,</li>                             
                                <li>xl,</li>                                
                                <li>xxl</li>                                
                            </ul>
                        </span>
                    </div>

                    <!-- colors -->
                    <div class="color-wrapper">
                        <b>Colors</b>
                        <br />
                        <ul class="list-inline color-list">
                            <li class="color-list__item color-list__item--red"></li>
                            <li class="color-list__item color-list__item--blue"></li>
                            <li class="color-list__item color-list__item--green"></li>
                            <li class="color-list__item color-list__item--orange"></li>
                            <li class="color-list__item color-list__item--purple"></li>
                        </ul>
                    </div>
                </div>

            </article>
        </div>

        <div class="col-xs-12 col-sm-6 col-md-4">
            <article class="card-wrapper">
                <div class="image-holder">
                    <a href="#" class="image-holder__link"></a>
                    <div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/b/b8/Columbia_Sportswear_Jacket.jpg')">
                    </div>
                </div>

                <div class="product-description">
                    <!-- title -->
                    <h1 class="product-description__title">
                        <a href="#">                        
                            Adidas Originals
                            </a>
                    </h1>

                    <!-- category and price -->
                    <div class="row">
                        <div class="col-sm-8 product-description__category secondary-text">
                            Men's running shirt
                        </div>
                        <div class="col-sm-4 product-description__price text-right">
                            € 499
                        </div>
                    </div>

                    <!-- divider -->
                    <hr />

                    <!-- sizes -->
                    <div class="sizes-wrapper">
                        <b>Sizes</b>
                        <br />
                        <span class="secondary-text text-uppercase">
                            <ul class="list-inline">
                                <li>xs,</li>                                
                                <li>s,</li>                             
                                <li>sm,</li>                                
                                <li>m,</li>
                                <li>l,</li>                             
                                <li>xl,</li>                                
                                <li>xxl</li>                                
                            </ul>
                        </span>
                    </div>

                    <!-- colors -->
                    <div class="color-wrapper">
                        <b>Colors</b>
                        <br />
                        <ul class="list-inline color-list">
                            <li class="color-list__item color-list__item--red"></li>
                            <li class="color-list__item color-list__item--blue"></li>
                            <li class="color-list__item color-list__item--green"></li>
                            <li class="color-list__item color-list__item--orange"></li>
                            <li class="color-list__item color-list__item--purple"></li>
                        </ul>
                    </div>
                </div>

            </article>
        </div>

        <div class="col-xs-12 col-sm-6 col-md-4">
            <article class="card-wrapper">
                <div class="image-holder">
                    <a href="#" class="image-holder__link"></a>
                    <div class="image-liquid image-holder--original" style="background-image: url('http://www.publicdomainpictures.net/pictures/20000/nahled/red-shoes-isolated.jpg')">
                    </div>
                </div>

                <div class="product-description">
                    <!-- title -->
                    <h1 class="product-description__title">
                        <a href="#">                        
                            Adidas Originals
                            </a>
                    </h1>

                    <!-- category and price -->
                    <div class="row">
                        <div class="col-sm-8 product-description__category secondary-text">
                            Men's running shirt
                        </div>
                        <div class="col-sm-4 product-description__price text-right">
                            € 499
                        </div>
                    </div>

                    <!-- divider -->
                    <hr />

                    <!-- sizes -->
                    <div class="sizes-wrapper">
                        <b>Sizes</b>
                        <br />
                        <span class="secondary-text text-uppercase">
                            <ul class="list-inline">
                                <li>xs,</li>                                
                                <li>s,</li>                             
                                <li>sm,</li>                                
                                <li>m,</li>
                                <li>l,</li>                             
                                <li>xl,</li>                                
                                <li>xxl</li>                                
                            </ul>
                        </span>
                    </div>

                    <!-- colors -->
                    <div class="color-wrapper">
                        <b>Colors</b>
                        <br />
                        <ul class="list-inline color-list">
                            <li class="color-list__item color-list__item--red"></li>
                            <li class="color-list__item color-list__item--blue"></li>
                            <li class="color-list__item color-list__item--green"></li>
                            <li class="color-list__item color-list__item--orange"></li>
                            <li class="color-list__item color-list__item--purple"></li>
                        </ul>
                    </div>
                </div>

            </article>
        </div>

    </div>
</div>

</body></html>

The sample is made

How to set table name in dynamic SQL query?

This is the best way to get a schema dynamically and add it to the different tables within a database in order to get other information dynamically

select @sql = 'insert #tables SELECT ''[''+SCHEMA_NAME(schema_id)+''.''+name+'']'' AS SchemaTable FROM sys.tables'

exec (@sql)

of course #tables is a dynamic table in the stored procedure

key_load_public: invalid format

It seems that ssh cannot read your public key. But that doesn't matter.

You upload your public key to github, but you authenticate using your private key. See e.g. the FILES section in ssh(1).

What are the best use cases for Akka framework

If you abstract the chat server up a level, then you get the answer.

Akka provides a messaging system that is akin to Erlang's "let it crash" mentality.

So examples are things that need varying levels of durability and reliability of messaging:

  • Chat server
  • Network layer for an MMO
  • Financial data pump
  • Notification system for an iPhone/mobile/whatever app
  • REST Server
  • Maybe something akin to WebMachine (guess)

The nice things about Akka are the choices it affords for persistence, it's STM implementation, REST server and fault-tolerance.

Don't get annoyed by the example of a chat server, think of it as an example of a certain class of solution.

With all their excellent documentation, I feel like a gap is this exact question, use-cases and examples. Keeping in mind the examples are non-trivial.

(Written with only experience of watching videos and playing with the source, I have implemented nothing using akka.)

How do I change Eclipse to use spaces instead of tabs?

In Eclipse go to Window » Preferences then search for Formatter.

You will see various bold links, click on each bold link and set it to use spaces instead of tabs.

In the java formatter link, you have to edit the profile and select the tab policy, spaces only in indentation tab

How to dismiss the dialog with click on outside of the dialog?

Another solution, this code was taken from android source code of Window You should just add these Two methods to your dialog source code.

@Override
public boolean onTouchEvent(MotionEvent event) {        
    if (isShowing() && (event.getAction() == MotionEvent.ACTION_DOWN
            && isOutOfBounds(getContext(), event) && getWindow().peekDecorView() != null)) {
        hide();
    }
    return false;
}

private boolean isOutOfBounds(Context context, MotionEvent event) {
    final int x = (int) event.getX();
    final int y = (int) event.getY();
    final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
    final View decorView = getWindow().getDecorView();
    return (x < -slop) || (y < -slop)
            || (x > (decorView.getWidth()+slop))
            || (y > (decorView.getHeight()+slop));
}

This solution doesnt have this problem :

This works great except that the activity underneath also reacts to the touch event. Is there some way to prevent this? – howettl

How to increase the clickable area of a <a> tag button?

You might try using display: block or display: inline-block. A nice tutorial can be found here: http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

Getting indices of True values in a boolean list

Using element-wise multiplication and a set:

>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})

Output: {4, 5, 7}

Java math function to convert positive int to negative and negative to positive?

Necromancing here.
Obviously, x *= -1; is far too simple.

Instead, we could use a trivial binary complement:

number = ~(number - 1) ;

Like this:

import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int iPositive = 15;
        int iNegative = ( ~(iPositive - 1) ) ; // Use extra brackets when using as C preprocessor directive ! ! !...
        System.out.println(iNegative);

        iPositive =  ~(iNegative - 1)  ;
        System.out.println(iPositive);

        iNegative = 0;
        iPositive = ~(iNegative - 1);
        System.out.println(iPositive);


    }
}

That way we can ensure that mediocre programmers don't understand what's going on ;)

Embed image in a <button> element

Try like this format and use "width" attribute to manage the image size, it is simple. JavaScript can be implemented in element too.

_x000D_
_x000D_
<button><img src=""></button>
_x000D_
_x000D_
_x000D_

How do I test if a variable is a number in Bash?

regular expression vs parameter expansion

As Charles Duffy's answer work, but only use regular expression, and I know this to be slow, I would like to show another way, using only parameter expansion:

For positive integers only:

is_num() { [ "$1" ] && [ -z "${1//[0-9]}" ] ;}

For integers:

is_num() { 
    local chk=${1#[+-]};
    [ "$chk" ] && [ -z "${chk//[0-9]}" ]
}

Then for floating:

is_num() { 
    local chk=${1#[+-]};
    chk=${chk/.}
    [ "$chk" ] && [ -z "${chk//[0-9]}" ]
}

To match initial request:

set -- "foo bar"
is_num "$1" && VAR=$1 || echo "need a number"
need a number

set -- "+3.141592"
is_num "$1" && VAR=$1 || echo "need a number"

echo $VAR
+3.141592

Now a little comparission:

There is a same check based on Charles Duffy's answer:

cdIs_num() { 
    local re='^[+-]?[0-9]+([.][0-9]+)?$';
    [[ $1 =~ $re ]]
}

Some tests:

if is_num foo;then echo It\'s a number ;else echo Not a number;fi
Not a number
if cdIs_num foo;then echo It\'s a number ;else echo Not a number;fi
Not a number
if is_num 25;then echo It\'s a number ;else echo Not a number;fi
It's a number
if cdIs_num 25;then echo It\'s a number ;else echo Not a number;fi
It's a number
if is_num 3+4;then echo It\'s a number ;else echo Not a number;fi
Not a number
if cdIs_num 3+4;then echo It\'s a number ;else echo Not a number;fi
Not a number
if is_num 3.1415;then echo It\'s a number ;else echo Not a number;fi
It's a number
if cdIs_num 3.1415;then echo It\'s a number ;else echo Not a number;fi
It's a number

Ok, that's fine. Now how many time will take all this (On my raspberry pi):

time for i in {1..1000};do is_num +3.14159265;done
real    0m2.476s
user    0m1.235s
sys     0m0.000s

Then with regular expressions:

time for i in {1..1000};do cdIs_num +3.14159265;done
real    0m4.363s
user    0m2.168s
sys     0m0.000s

Django URL Redirect

Another way of doing it is using HttpResponsePermanentRedirect like so:

In view.py

def url_redirect(request):
    return HttpResponsePermanentRedirect("/new_url/")

In the url.py

url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),

What does the percentage sign mean in Python

The modulus operator. The remainder when you divide two number.

For Example:

>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1
>>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1
>>> 3 % 1 = 0 # because 1 divides evenly into 3

Changing CSS Values with Javascript

Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a Shawn Olson tutorial. You can directly reference his code here.

Here is the summary:

You can retrieve the stylesheets via document.styleSheets. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the document.styleSheets[styleIndex].href property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what CSSRule you are on is by the selectorText property. The working code looks something like this:

var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText;  //maybe '#tId'
var value = rule.value;            //both selectorText and value are settable.

Let me know how this works for ya, and please comment if you see any errors.

Rotating videos with FFmpeg

Unfortunately, the Ubuntu version of ffmpeg does support videofilters.

You need to use avidemux or some other editor to achieve the same effect.

In the programmatic way, mencoder has been recommended.

jQuery textbox change event

You can achieve it:

 $(document).ready(function(){              
     $('#textBox').keyup(function () {alert('changed');});
 });

or with change (handle copy paste with right click):

 $(document).ready(function(){              
     $('#textBox2').change(function () {alert('changed');});
 });

Here is Demo

Correct MySQL configuration for Ruby on Rails Database.yml file

If you can have an empty config/database.yml file then define ENV['DATABASE_URL'] variable, then It will work

$ cat config/database.yml
 
$ echo $DATABASE_URL
mysql://root:[email protected]:3306/my_db_name

for Heroku: heroku config:set DATABASE_URL='mysql://root:[email protected]/my_db_name'

How do I run all Python unit tests in a directory?

Here is my approach by creating a wrapper to run tests from the command line:

#!/usr/bin/env python3
import os, sys, unittest, argparse, inspect, logging

if __name__ == '__main__':
    # Parse arguments.
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-?", "--help",     action="help",                        help="show this help message and exit" )
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose",  help="increase output verbosity" )
    parser.add_argument("-d", "--debug",    action="store_true", dest="debug",    help="show debug messages" )
    parser.add_argument("-h", "--host",     action="store",      dest="host",     help="Destination host" )
    parser.add_argument("-b", "--browser",  action="store",      dest="browser",  help="Browser driver.", choices=["Firefox", "Chrome", "IE", "Opera", "PhantomJS"] )
    parser.add_argument("-r", "--reports-dir", action="store",   dest="dir",      help="Directory to save screenshots.", default="reports")
    parser.add_argument('files', nargs='*')
    args = parser.parse_args()

    # Load files from the arguments.
    for filename in args.files:
        exec(open(filename).read())

    # See: http://codereview.stackexchange.com/q/88655/15346
    def make_suite(tc_class):
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(tc_class)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(tc_class(name, cargs=args))
        return suite

    # Add all tests.
    alltests = unittest.TestSuite()
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj) and name.startswith("FooTest"):
            alltests.addTest(make_suite(obj))

    # Set-up logger
    verbose = bool(os.environ.get('VERBOSE', args.verbose))
    debug   = bool(os.environ.get('DEBUG', args.debug))
    if verbose or debug:
        logging.basicConfig( stream=sys.stdout )
        root = logging.getLogger()
        root.setLevel(logging.INFO if verbose else logging.DEBUG)
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.INFO if verbose else logging.DEBUG)
        ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))
        root.addHandler(ch)
    else:
        logging.basicConfig(stream=sys.stderr)

    # Run tests.
    result = unittest.TextTestRunner(verbosity=2).run(alltests)
    sys.exit(not result.wasSuccessful())

For sake of simplicity, please excuse my non-PEP8 coding standards.

Then you can create BaseTest class for common components for all your tests, so each of your test would simply look like:

from BaseTest import BaseTest
class FooTestPagesBasic(BaseTest):
    def test_foo(self):
        driver = self.driver
        driver.get(self.base_url + "/")

To run, you simply specifying tests as part of the command line arguments, e.g.:

./run_tests.py -h http://example.com/ tests/**/*.py

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Code:

private static void RegisterServices(IKernel kernel)
{
    Mock<IProductRepository> mock=new Mock<IProductRepository>();
    mock.Setup(x => x.Products).Returns(new List<Product>
    {
        new Product {Name = "Football", Price = 23},
        new Product {Name = "Surf board", Price = 179},
        new Product {Name = "Running shose", Price = 95}
    });

    kernel.Bind<IProductRepository>().ToConstant(mock.Object);
}        

but see exception.

Import/Index a JSON file into Elasticsearch

I'm the author of elasticsearch_loader
I wrote ESL for this exact problem.

You can download it with pip:

pip install elasticsearch-loader

And then you will be able to load json files into elasticsearch by issuing:

elasticsearch_loader --index incidents --type incident json file1.json file2.json

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Use of main thread to present and dismiss view controller worked for me.

DispatchQueue.main.async { self.present(viewController, animated: true, completion: nil) }

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

How to upload & Save Files with Desired name

This would work very well -- You can use HTML5 to allow only image files to be uploaded. This is the code for uploader.htm --

<html>    
    <head>
        <script>
            function validateForm(){
                var image = document.getElementById("image").value;
                var name = document.getElementById("name").value;
                if (image =='')
                {
                    return false;
                }
                if(name =='')
                {
                    return false;
                } 
                else 
                {
                    return true;
                } 
                return false;
            }
        </script>
    </head>

    <body>
        <form method="post" action="upload.php" enctype="multipart/form-data">
            <input type="text" name="ext" size="30"/>
            <input type="text" name="name" id="name" size="30"/>
            <input type="file" accept="image/*" name="image" id="image" />
            <input type="submit" value='Save' onclick="return validateForm()"/>
        </form>
    </body>
</html>

Now the code for upload.php --

<?php  
$name = $_POST['name'];
$ext = $_POST['ext'];
if (isset($_FILES['image']['name']))
{
    $saveto = "$name.$ext";
    move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
    $typeok = TRUE;
    switch($_FILES['image']['type'])
    {
        case "image/gif": $src = imagecreatefromgif($saveto); break;
        case "image/jpeg": // Both regular and progressive jpegs
        case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
        case "image/png": $src = imagecreatefrompng($saveto); break;
        default: $typeok = FALSE; break;
    }
    if ($typeok)
    {
        list($w, $h) = getimagesize($saveto);
        $max = 100;
        $tw = $w;
        $th = $h;
        if ($w > $h && $max < $w)
        {
            $th = $max / $w * $h;
            $tw = $max;
        }
        elseif ($h > $w && $max < $h)
        {
            $tw = $max / $h * $w;
            $th = $max;
        }
        elseif ($max < $w)
        {
            $tw = $th = $max;
        }

        $tmp = imagecreatetruecolor($tw, $th);      
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
        imageconvolution($tmp, array( // Sharpen image
            array(-1, -1, -1),
            array(-1, 16, -1),
            array(-1, -1, -1)      
        ), 8, 0);
        imagejpeg($tmp, $saveto);
        imagedestroy($tmp);
        imagedestroy($src);
    }
}
?>

Creating JSON on the fly with JObject

There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.

In these cases you can do:

using Newtonsoft.Json.Linq;

JObject jsonObject =
     new JObject(
             new JProperty("Date", DateTime.Now),
             new JProperty("Album", "Me Against The World"),
             new JProperty("Year", "James 2Pac-King's blog."),
             new JProperty("Artist", "2Pac")
         )

More documentation here: http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm

Eclipse HotKey: how to switch between tabs?

If you want to simply switch between your current and your previous tab selections, using CTRL + F6 will switch you back and forth. To navigate to a tab further back in your history, you need to use the UP / DOWN keys while the Editors window is open. This works with Helios (Eclipse 3.6); not sure if this is true for older versions of Eclipse.

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Use Awk to extract substring

You do not need any external command at all, just use Parameter Expansion in bash:

hostname=aaa0.bbb.ccc
echo ${hostname%%.*}

What is the size of a pointer?

Recently came upon a case where this was not true, TI C28x boards can have a sizeof pointer == 1, since a byte for those boards is 16-bits, and pointer size is 16 bits. To make matters more confusing, they also have far pointers which are 22-bits. I'm not really sure what sizeof far pointer would be.

In general, DSP boards can have weird integer sizes.

So pointer sizes can still be weird in 2020 if you are looking in weird places

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

Is there a GUI design app for the Tkinter / grid geometry?

The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.

Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.

* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).

Specifying maxlength for multiline textbox

use custom attribute maxsize="100"

<asp:TextBox ID="txtAddress" runat="server"  maxsize="100"
      Columns="17" Rows="4" TextMode="MultiLine"></asp:TextBox>
   <script>
       $("textarea[maxsize]").each(function () {
         $(this).attr('maxlength', $(this).attr('maxsize'));
         $(this).removeAttr('maxsize'); 
       });
   </script>

this will render like this

<textarea name="ctl00$BodyContentPlac
eHolder$txtAddress" rows="4" cols="17" id="txtAddress" maxlength="100"></textarea>

Is there any difference between "!=" and "<>" in Oracle Sql?

No there is no difference at all in functionality.
(The same is true for all other DBMS - most of them support both styles):

Here is the current SQL reference: https://docs.oracle.com/database/121/SQLRF/conditions002.htm#CJAGAABC

The SQL standard only defines a single operator for "not equals" and that is <>

Verify External Script Is Loaded

I think it's better to use window.addEventListener('error') to capture the script load error and try to load it again. It's useful when we load scripts from a CDN server. If we can't load script from the CDN, we can load it from our server.

window.addEventListener('error', function(e) {
  if (e.target.nodeName === 'SCRIPT') {
    var scriptTag = document.createElement('script');
    scriptTag.src = e.target.src.replace('https://static.cdn.com/', '/our-server/static/');
    document.head.appendChild(scriptTag);
  }
}, true);

How to get a view table query (code) in SQL Server 2008 Management Studio

Use sp_helptext before the view_name. Example:

sp_helptext Example_1

Hence you will get the query:

CREATE VIEW dbo.Example_1
AS
SELECT       a, b, c
FROM         dbo.table_name JOIN blah blah blah
WHERE        blah blah blah

sp_helptext will give stored procedures.

What is "android:allowBackup"?

It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"), it is possible to modify/read the content of an app even on a non-rooted device.

Solution - use android:allowBackup="false" in the manifest file.

You can read this post to have more information: Hacking Android Apps Using Backup Techniques

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

Add borders to cells in POI generated Excel File

HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

How to get the current date/time in Java

Create object of date and simply print it down.

Date d = new Date(System.currentTimeMillis());
System.out.print(d);

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

Setup a Git server with msysgit on Windows

I'm using GitWebAccess for many projects for half a year now, and it's proven to be the best of what I've tried. It seems, though, that lately sources are not supported, so - don't take latest binaries/sources. Currently they're broken :(

You can build from this version or download compiled binaries which I use from here.

How to remove empty lines with or without whitespace in Python

you can simply use rstrip:

    for stuff in largestring:
        print(stuff.rstrip("\n")

PHP $_POST not working?

A few thing you could do:

  1. Make sure that the "action" attribute on your form leads to the correct destination.
  2. Try using $_REQUEST[] instead of $_POST, see if there is any change.
  3. [Optional] Try including both a 'name' and an 'id' attribute e.g.

    <input type="text" name="firstname" id="firstname">
    

  4. If you are in a Linux environment, check that you have both Read/Write permissions to the file.

In addition, this link might also help.

EDIT:

You could also substitute

<code>if(isset($_POST['submit'])){</code>

with this:

<code>if($_SERVER['REQUEST_METHOD'] == "POST"){ </code>

This is always the best way of checking whether or not a form has been submitted

how concatenate two variables in batch script?

You can do it without setlocal, because of the setlocal command the variable won't survive an endlocal because it was created in setlocal. In this way the variable will be defined the right way.

To do that use this code:

set var1=A

set var2=B

set AB=hi

call set newvar=%%%var1%%var2%%%

echo %newvar% 

Note: You MUST use call before you set the variable or it won't work.

HTTPS setup in Amazon EC2

Amazon EC2 instances are just virtual machines so you would setup SSL the same way you would set it up on any server.

You don't mention what platform you are on, so it difficult to give any more information.

What is WebKit and how is it related to CSS?

Addition to what @KennyTM said:

  • IE
  • Edge
  • Firefox
    • Engine: Gecko
    • CSS-prefix: -moz
  • Opera
    • Engine: Presto ? Blink1
    • CSS-prefix: -o (Presto) and -webkit (Blink)
  • Safari
    • Engine: WebKit
    • CSS-prefix: -webkit
  • Chrome

1) On February 12 2013 Opera (version 15+) announces they moving away from their own engine Presto to WebKit named Blink.

2) On April 3 2013 Google (Chrome version 28+) announces they are going to use the WebKit-based Blink engine.

3) On December 6 2018 Microsoft (Microsoft Edge 79+ stable) announces they are going to use the WebKit-based Blink engine.

How to exit if a command failed?

The other answers have covered the direct question well, but you may also be interested in using set -e. With that, any command that fails (outside of specific contexts like if tests) will cause the script to abort. For certain scripts, it's very useful.

XMLHttpRequest (Ajax) Error

The problem is likely to lie with the line:

window.onload = onPageLoad();

By including the brackets you are saying onload should equal the return value of onPageLoad(). For example:

/*Example function*/
function onPageLoad()
{
    return "science";
}
/*Set on load*/
window.onload = onPageLoad()

If you print out the value of window.onload to the console it will be:

science

The solution is remove the brackets:

window.onload = onPageLoad;

So, you're using onPageLoad as a reference to the so-named function.

Finally, in order to get the response value you'll need a readystatechange listener for your XMLHttpRequest object, since it's asynchronous:

xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.

Here you add the listener:

xmlHttp.onreadystatechange = function() {
    if(this.readyState == 4) {
        // Do something
    }
}

babel-loader jsx SyntaxError: Unexpected token

The following way has helped me (includes react-hot, babel loaders and es2015, react presets):

loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react']
      }
]

How can I access global variable inside class in Python

class flag:
    ## Store pseudo-global variables here

    keys=False

    sword=True

    torch=False


## test the flag class

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)


## now change the variables

flag.keys=True
flag.sword= not flag.sword
flag.torch=True

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)

How to split a string, but also keep the delimiters?

Fast answer: use non physical bounds like \b to split. I will try and experiment to see if it works (used that in PHP and JS).

It is possible, and kind of work, but might split too much. Actually, it depends on the string you want to split and the result you need. Give more details, we will help you better.

Another way is to do your own split, capturing the delimiter (supposing it is variable) and adding it afterward to the result.

My quick test:

String str = "'ab','cd','eg'";
String[] stra = str.split("\\b");
for (String s : stra) System.out.print(s + "|");
System.out.println();

Result:

'|ab|','|cd|','|eg|'|

A bit too much... :-)

Bash ignoring error for a particular command

I have been using the snippet below when working with CLI tools and I want to know if some resource exist or not, but I don't care about the output.

if [ -z "$(cat no_exist 2>&1 >/dev/null)" ]; then
    echo "none exist actually exist!"
fi

INNER JOIN vs LEFT JOIN performance in SQL Server

If everything works as it should it shouldn't, BUT we all know everything doesn't work the way it should especially when it comes to the query optimizer, query plan caching and statistics.

First I would suggest rebuilding index and statistics, then clearing the query plan cache just to make sure that's not screwing things up. However I've experienced problems even when that's done.

I've experienced some cases where a left join has been faster than a inner join.

The underlying reason is this: If you have two tables and you join on a column with an index (on both tables). The inner join will produce the same result no matter if you loop over the entries in the index on table one and match with index on table two as if you would do the reverse: Loop over entries in the index on table two and match with index in table one. The problem is when you have misleading statistics, the query optimizer will use the statistics of the index to find the table with least matching entries (based on your other criteria). If you have two tables with 1 million in each, in table one you have 10 rows matching and in table two you have 100000 rows matching. The best way would be to do an index scan on table one and matching 10 times in table two. The reverse would be an index scan that loops over 100000 rows and tries to match 100000 times and only 10 succeed. So if the statistics isn't correct the optimizer might choose the wrong table and index to loop over.

If the optimizer chooses to optimize the left join in the order it is written it will perform better than the inner join.

BUT, the optimizer may also optimize a left join sub-optimally as a left semi join. To make it choose the one you want you can use the force order hint.

Return back to MainActivity from another activity

I'm used it and worked perfectly...

startActivity(new Intent(getApplicationContext(),MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); 

because Finish() use for 2 activities, not for multiple activities

Get Number of Rows returned by ResultSet in Java

Another way to differentiate between 0 rows or some rows from a ResultSet:

ResultSet res = getData();

if(!res.isBeforeFirst()){          //res.isBeforeFirst() is true if the cursor
                                   //is before the first row.  If res contains
                                   //no rows, rs.isBeforeFirst() is false.

    System.out.println("0 rows");
}
else{
    while(res.next()){
        // code to display the rows in the table.
    }
}

If you must know the number of rows given a ResultSet, here is a method to get it:

public int getRows(ResultSet res){
    int totalRows = 0;
    try {
        res.last();
        totalRows = res.getRow();
        res.beforeFirst();
    } 
    catch(Exception ex)  {
        return 0;
    }
    return totalRows ;    
}

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

How to position text over an image in css

This is another method for working with Responsive sizes. It will keep your text centered and maintain its position within its parent. If you don't want it centered then it's even easier, just work with the absolute parameters. Keep in mind the main container is using display: inline-block. There are many others ways to do this, depending on what you're working on.

Based off of Centering the Unknown

Working codepen example here

HTML

<div class="containerBox">
    <div class="text-box">
        <h4>Your Text is responsive and centered</h4>
    </div>
    <img class="img-responsive" src="http://placehold.it/900x100"/>
</div>

CSS

.containerBox {
    position: relative;
    display: inline-block;
}
.text-box {
    position: absolute;    
    height: 100%;
    text-align: center;    
    width: 100%;
}
.text-box:before {
   content: '';
   display: inline-block;
   height: 100%;
   vertical-align: middle;
}
h4 {
   display: inline-block;
   font-size: 20px; /*or whatever you want*/
   color: #FFF;   
}
img {
  display: block;
  max-width: 100%;
  height: auto;
}

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

Another good way of dealing with Lion's hidden scroll bars is to display a prompt to scroll down. It doesn't work with small scroll areas such as text fields but well with large scroll areas and keeps the overall style of the site. One site doing this is http://versusio.com, just check this example page and wait 1.5 seconds to see the prompt:

http://versusio.com/en/samsung-galaxy-nexus-32gb-vs-apple-iphone-4s-64gb

The implementation isn't hard but you have to take care, that you don't display the prompt when the user has already scrolled.

You need jQuery + Underscore and

$(window).scroll to check if the user already scrolled by himself,

_.delay() to trigger a delay before you display the prompt -- the prompt shouldn't be to obtrusive

$('#prompt_div').fadeIn('slow') to fade in your prompt and of course

$('#prompt_div').fadeOut('slow') to fade out when the user scrolled after he saw the prompt

In addition, you can bind Google Analytics events to track user's scrolling behavior.

What is the difference between syntax and semantics in programming languages?

  • You need correct syntax to compile.
  • You need correct semantics to make it work.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

Binding a list in @RequestParam

Just complementing what Donal Fellows said, you can use List with @RequestParam

public String controllerMethod(@RequestParam(value="myParam") List<ObjectToParse> myParam){
....
}

Hope it helps!

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

Margin-Top not working for span element?

Looks like you missed some options, try to add:

position: relative;
top: 25px;

PHP7 : install ext-dom issue

For CentOS, RHEL, Fedora:

$ yum search php-xml
============================================================================================================ N/S matched: php-xml ============================================================================================================
php-xml.x86_64 : A module for PHP applications which use XML
php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php-xmlseclibs.noarch : PHP library for XML Security
php54-php-xml.x86_64 : A module for PHP applications which use XML
php54-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php55-php-xml.x86_64 : A module for PHP applications which use XML
php55-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php56-php-xml.x86_64 : A module for PHP applications which use XML
php56-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php70-php-xml.x86_64 : A module for PHP applications which use XML
php70-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php71-php-xml.x86_64 : A module for PHP applications which use XML
php71-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php72-php-xml.x86_64 : A module for PHP applications which use XML
php72-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php73-php-xml.x86_64 : A module for PHP applications which use XML
php73-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol

Then select the php-xml version matching your php version:

# php -v
PHP 7.2.11 (cli) (built: Oct 10 2018 10:00:29) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

# sudo yum install -y php72-php-xml.x86_64

Hiding a form and showing another when a button is clicked in a Windows Forms application

private void button5_Click(object sender, EventArgs e)
{
    this.Visible = false;
    Form2 login = new Form2();
    login.ShowDialog();
}

How do I register a DLL file on Windows 7 64-bit?

There is a difference in Windows 7. Logging on as Administrator does not give the same rights as when running a program as Administrator.

Go to Start - All Programs - Accesories. Right click on the Command window and select "Run as administrator" Now register the dll normally via : regsrvr32 xxx.dll

What's the difference between using "let" and "var"?

let is a part of es6. These functions will explain the difference in easy way.

function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}

Regex to test if string begins with http:// or https://

^https?://

You might have to escape the forward slashes though, depending on context.

Oracle Insert via Select from multiple tables where one table may not have a row

A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:

INSERT INTO account_type_standard   
  (account_type_Standard_id, tax_status_id, recipient_id) 
VALUES(   
  account_type_standard_seq.nextval,
  (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
  (SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)

Add error bars to show standard deviation on a plot in R

In addition to @csgillespie's answer, segments is also vectorised to help with this sort of thing:

plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

How to get a string between two characters?

This is a simple use \D+ regex and job done.
This select all chars except digits, no need to complicate

/\D+/

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I use this:

interface IObjectKeys {
  [key: string]: string | number;
}

interface IDevice extends IObjectKeys {
  id: number;
  room_id: number;
  name: string;
  type: string;
  description: string;
}

If you use the optional property in your object:

interface IDevice extends IObjectKeys {
  id: number;
  room_id?: number;
  name?: string;
  type?: string;
  description?: string;
}

... you should add 'undefined' value into the IObjectKeys interface:

interface IObjectKeys {
  [key: string]: string | number | undefined;
}

How to escape single quotes in MySQL

There is another way to do this which may or may not be safer, depending upon your perspective. It requires MySQL 5.6 or later because of the use of a specific string function: FROM_BASE64.

Let's say you have this message you'd like to insert:

"Ah," Nearly Headless Nick waved an elegant hand, "a matter of no importance. . . . It's not as though I really wanted to join. . . . Thought I'd apply, but apparently I 'don't fulfill requirements' -"

That quote has a bunch of single- and double-quotes and would be a real pain to insert into MySQL. If you are inserting that from a program, it's easy to escape the quotes, etc. But, if you have to put that into a SQL script, you'll have to edit the text (to escape the quotes) which could be error prone or sensitive to word-wrapping, etc.

Instead, you can Base64-encode the text, so you have a "clean" string:

SWtGb0xDSWdUbVZoY214NUlFaGxZV1JzWlhOeklFNXBZMnNnZD JGMlpXUWdZVzRnWld4bFoyRnVkQ0JvWVc1a0xDQWlZU0J0WVhS MFpYCklnYjJZZ2JtOGdhVzF3YjNKMFlXNWpaUzRnTGlBdUlDNG dTWFFuY3lCdWIzUWdZWE1nZEdodmRXZG9JRWtnY21WaGJHeDVJ SGRoYm5SbApaQ0IwYnlCcWIybHVMaUF1SUM0Z0xpQlVhRzkxWj JoMElFa25aQ0JoY0hCc2VTd2dZblYwSUdGd2NHRnlaVzUwYkhr Z1NTQW5aRzl1SjMKUWdablZzWm1sc2JDQnlaWEYxYVhKbGJXVn VkSE1uSUMwaUlBPT0K

Some notes about Base64-encoding:

  1. Base64-encoding is a binary encoding, so you'd better make sure that you get your character set correct when you do the encoding, because MySQL is going to decode the Base64-encoded string into bytes and then interpret those. Be sure base64 and MySQL agree on what the character encoding is (I recommend UTF-8).
  2. I've wrapped the string to 50 columns for readability on Stack Overflow. You can wrap it to any number of columns you want (or not wrap at all) and it will still work.

Now, to load this into MySQL:

INSERT INTO my_table (text) VALUES (FROM_BASE64(' SWtGb0xDSWdUbVZoY214NUlFaGxZV1JzWlhOeklFNXBZMnNnZD JGMlpXUWdZVzRnWld4bFoyRnVkQ0JvWVc1a0xDQWlZU0J0WVhS MFpYCklnYjJZZ2JtOGdhVzF3YjNKMFlXNWpaUzRnTGlBdUlDNG dTWFFuY3lCdWIzUWdZWE1nZEdodmRXZG9JRWtnY21WaGJHeDVJ SGRoYm5SbApaQ0IwYnlCcWIybHVMaUF1SUM0Z0xpQlVhRzkxWj JoMElFa25aQ0JoY0hCc2VTd2dZblYwSUdGd2NHRnlaVzUwYkhr Z1NTQW5aRzl1SjMKUWdablZzWm1sc2JDQnlaWEYxYVhKbGJXVn VkSE1uSUMwaUlBPT0K '));

This will insert without any complaints, and you didn't have to manually-escape any text inside the string.

How to make picturebox transparent?

you can set the PictureBox BackColor proprty to Transparent

How do I run a batch script from within a batch script?

You can just invoke the batch script by name, as if you're running on the command line.

So, suppose you have a file bar.bat that says echo This is bar.bat! and you want to call it from a file foo.bat, you can write this in foo.bat:

if "%1"=="blah" bar

Run foo blah from the command line, and you'll see:

C:\>foo blah

C:\>if "blah" == "blah" bar

C:\>echo This is bar.bat!
This is bar.bat!

But beware: When you invoke a batch script from another batch script, the original batch script will stop running. If you want to run the secondary batch script and then return to the previous batch script, you'll have to use the call command. For example:

if "%1"=="blah" call bar
echo That's all for foo.bat!

If you run foo blah on that, you'd see:

C:\>foo blah

C:\>if "blah" == "blah" call bar

C:\>echo This is bar.bat!
This is bar.bat!

C:\>echo That's all for foo.bat!
That's all for foo.bat!

Force HTML5 youtube video

Inline tag is used to add another src of document to the current html element.

In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link

so add ?html=5 to the end of the link.. :)

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

Make header and footer files to be included in multiple html pages

I add common parts as header and footer using Server Side Includes. No HTML and no JavaScript is needed. Instead, the webserver automatically adds the included code before doing anything else.

Just add the following line where you want to include your file:

<!--#include file="include_head.html" -->

Input button target="_blank" isn't causing the link to load in a new window/tab

use formtarget="_blank" its working for me

<input type="button" onClick="parent.location='http://www.facebook.com/'" value="facebook" formtarget="_blank">

Browser compatibility: from caniuse.com
IE: 10+ | Edge: 12+ | Firefox: 4+ | Chrome: 15+ | Safari/iOS: 5.1+ | Android: 4+

How to get current instance name from T-SQL

another method to find Instance name- Right clck on Database name and select Properties, in this part you can see view connection properties in left down corner, click that then you can see the Instance name.

How to display .svg image using swift

You can keep your images as strings and use WKWebView to display them:

let webView: WKWebView = {
    let mySVGImage = "<svg height=\"190\"><polygon points=\"100,10 40,180 190,60 10,60 160,180\" style=\"fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;\"></svg>"
    let preferences = WKPreferences()
    preferences.javaScriptEnabled = false
    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences
    let wv = WKWebView(frame: .zero, configuration: configuration)
    wv.scrollView.isScrollEnabled = false
    wv.loadHTMLString(mySVGImage, baseURL: nil)
    return wv
}()

Creating Roles in Asp.net Identity MVC 5

I wanted to share another solution for adding roles:

<h2>Create Role</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<span class="label label-primary">Role name:</span>
<p>
    @Html.TextBox("RoleName", null, new { @class = "form-control input-lg" })
</p>
<input type="submit" value="Save" class="btn btn-primary" />
}

Controller:

    [HttpGet]
    public ActionResult AdminView()
    {
        return View();
    }

    [HttpPost]
    public ActionResult AdminView(FormCollection collection)
    {
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

        if (roleManager.RoleExists(collection["RoleName"]) == false)
        {
            Guid guid = Guid.NewGuid();
            roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] });
        }
        return View();
    }

Unable to find velocity template resources

The following code helped me resolve the issue. The path to the template needs to be provided as part of file.resource.loader path. By default it comes as "." . So setting the property explicitly will be required.

Print getClass().getClassLoader().getResource("resources") or getClass().getClassLoader().getResource("") to see where your template comes and based on that set it in the velocity template engine.

URL url = getClass().getClassLoader().getResource("resources");
//URL url = getClass().getClassLoader().getResource("");
File folder= new File(url.getFile());   
VelocityEngine ve = new VelocityEngine();
       
ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, folder.getAbsolutePath());
ve.init();

Template template = ve.getTemplate( "MyTemplate.vm" );

How to list all dates between two dates

I made a calendar using:

http://social.technet.microsoft.com/wiki/contents/articles/22776.t-sql-calendar-table.aspx

then a Store procedure passing two dates and thats all:

USE DB_NAME;
GO

CREATE PROCEDURE [dbo].[USP_LISTAR_RANGO_FECHAS]
@FEC_INICIO date,
@FEC_FIN date
AS
Select Date from CALENDARIO where Date BETWEEN @FEC_INICIO AND @FEC_FIN;

How to input a path with a white space?

If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:

1) Java's build.properties file:

build_path='/home/ec2-user/Name\\ of\\ Directory'

Where ~/ is equal to /home/ec2-user

2) Jenkinsfile:

build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"

Copy folder recursively, excluding some folders

EXCLUDE="foo bar blah jah"                                                                             
DEST=$1

for i in *
do
    for x in $EXCLUDE
    do  
        if [ $x != $i ]; then
            cp -a $i $DEST
        fi  
    done
done

Untested...

How to test valid UUID/GUID?

Beside Gambol's answer that will do the job in nearly all cases, all answers given so far missed that the grouped formatting (8-4-4-4-12) is not mandatory to encode GUIDs in text. It's used extremely often but obviously also a plain chain of 32 hexadecimal digits can be valid.[1] regexenh:

/^[0-9a-f]{8}-?[0-9a-f]{4}-?[1-5][0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$/i

[1] The question is about checking variables, so we should include the user-unfriendly form as well.

How do I calculate a point on a circle’s circumference?

Who needs trig when you have complex numbers:

#include <complex.h>
#include <math.h>

#define PI      3.14159265358979323846

typedef complex double Point;

Point point_on_circle ( double radius, double angle_in_degrees, Point centre )
{
    return centre + radius * cexp ( PI * I * ( angle_in_degrees  / 180.0 ) );
}

IF EXISTS in T-SQL

Yes it stops execution so this is generally preferable to HAVING COUNT(*) > 0 which often won't.

With EXISTS if you look at the execution plan you will see that the actual number of rows coming out of table1 will not be more than 1 irrespective of number of matching records.

In some circumstances SQL Server can convert the tree for the COUNT query to the same as the one for EXISTS during the simplification phase (with a semi join and no aggregate operator in sight) an example of that is discussed in the comments here.

For more complicated sub trees than shown in the question you may occasionally find the COUNT performs better than EXISTS however. Because the semi join needs only retrieve one row from the sub tree this can encourage a plan with nested loops for that part of the tree - which may not work out optimal in practice.

How can I generate a unique ID in Python?

Maybe this work for u

str(uuid.uuid4().fields[-1])[:5]

Array initialization in Perl

What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);

my @array = (); should work just fine -- it allocates a new array called @array, and then assigns it the empty list, (). Note that this is identical to simply saying my @array;, since the initial value of a new array is the empty list anyway.

Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings; in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)

How to run a python script from IDLE interactive shell?

execFile('helloworld.py') does the job for me. A thing to note is to enter the complete directory name of the .py file if it isnt in the Python folder itself (atleast this is the case on Windows)

For example, execFile('C:/helloworld.py')

How can I turn a JSONArray into a JSONObject?

Can't you originally get the data as a JSONObject?

Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?

I'm not sure that it is possible to convert a JsonArray into a JsonObject.

I presume you are using the following from json.org

  • JSONObject.java
    A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONArray.java
    A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

How do I get the path of the current executed file in Python?

import os
current_file_path=os.path.dirname(os.path.realpath('__file__'))

How to word wrap text in HTML?

Cross Browser

.wrap
{
    white-space: pre-wrap; /* css-3 */    
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */    
    white-space: -o-pre-wrap; /* Opera 7 */    
    word-wrap: break-word; /* Internet Explorer 5.5+ */
}

Returning JSON object as response in Spring Boot

use ResponseEntity<ResponseBean>

Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.

@GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
            HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        loginService.login(username, password, request);
        return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
                HttpStatus.ACCEPTED);
    }

for response ServiceStatus or(ResponseBody)

    public enum ServiceStatus {

    LOGIN_SUCCESS(0, "Login success"),

    private final int id;
    private final String message;

    //Enum constructor
    ServiceStatus(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

Spring REST API should have below key in response

  1. Status Code
  2. Message

you will get final response below

{

   "StatusCode" : "0",

   "Message":"Login success"

}

you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

WSDL: Stands for Web Service Description Language

In SOAP(simple object access protocol), when you use web service and add a web service to your project, your client application(s) doesn't know about web service Functions. Nowadays it's somehow old-fashion and for each kind of different client you have to implement different WSDL files. For example you cannot use same file for .Net and php client. The WSDL file has some descriptions about web service functions. The type of this file is XML. SOAP is an alternative for REST.

REST: Stands for Representational State Transfer

It is another kind of API service, it is really easy to use for clients. They do not need to have special file extension like WSDL files. The CRUD operation can be implemented by different HTTP Verbs(GET for Reading, POST for Creation, PUT or PATCH for Updating and DELETE for Deleting the desired document) , They are based on HTTP protocol and most of times the response is in JSON or XML format. On the other hand the client application have to exactly call the related HTTP Verb via exact parameters names and types. Due to not having special file for definition, like WSDL, it is a manually job using the endpoint. But it is not a big deal because now we have a lot of plugins for different IDEs to generating the client-side implementation.

SOA: Stands for Service Oriented Architecture

Includes all of the programming with web services concepts and architecture. Imagine that you want to implement a large-scale application. One practice can be having some different services, called micro-services and the whole application mechanism would be calling needed web service at the right time. Both REST and SOAP web services are kind of SOA.

JSON: Stands for javascript Object Notation

when you serialize an object for javascript the type of object format is JSON. imagine that you have the human class :

class Human{
 string Name;
 string Family;
 int Age;
}

and you have some instances from this class :

Human h1 = new Human(){
  Name='Saman',
  Family='Gholami',
  Age=26
}

when you serialize the h1 object to JSON the result is :

  [h1:{Name:'saman',Family:'Gholami',Age:'26'}, ...]

javascript can evaluate this format by eval() function and make an associative array from this JSON string. This one is different concept in comparison to other concepts I described formerly.

Chrome javascript debugger breakpoints don't do anything?

I had a minifier that was stripping out debugger statements ¯_(?)_/¯

Convert date field into text in Excel

You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this

="Today is "&TEXT(A1,"dd-mm-yyyy")

You can change the "dd-mm-yyyy" part as required

text-align: right on <select> or <option>

The following CSS will right-align both the arrow and the options:

_x000D_
_x000D_
select { text-align-last: right; }_x000D_
option { direction: rtl; }
_x000D_
<!-- example usage -->_x000D_
Choose one: <select>_x000D_
  <option>The first option</option>_x000D_
  <option>A second, fairly long option</option>_x000D_
  <option>Last</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to parse XML and count instances of a particular node attribute?

XML:

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

Python code:

import xml.etree.cElementTree as ET

tree = ET.parse("foo.xml")
root = tree.getroot() 
root_tag = root.tag
print(root_tag) 

for form in root.findall("./bar/type"):
    x=(form.attrib)
    z=list(x)
    for i in z:
        print(x[i])

Output:

foo
1
2

How can I list all the deleted files in a Git repository?

And if you want to somehow constrain the results here's a nice one:

$ git log --diff-filter=D --summary | sed -n '/^commit/h;/\/some_dir\//{G;s/\ncommit \(.*\)/ \1/gp}'
delete mode 100644 blah/some_dir/file1 d3bfbbeba5b5c1da73c432cb3fb61990bdcf6f64
delete mode 100644 blah/some_dir/file2 d3bfbbeba5b5c1da73c432cb3fb61990bdcf6f64
delete mode 100644 blah/some_dir/file3 9c89b91d8df7c95c6043184154c476623414fcb7

You'll get all files deleted from some_dir (see the sed command) together with the commit number in which it happen. Any sed regex will do (I use this to find deleted file types, etc)

How to open select file dialog via js?

With jquery library

<button onclick="$('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">

JQuery html() vs. innerHTML

Specifically regarding "Can I rely completely upon jquery html() method that it'll perform like innerHTML" my answer is NO!

Run this in internet explorer 7 or 8 and you'll see.

jQuery produces bad HTML when setting HTML containing a <FORM> tag nested within a <P> tag where the beginning of the string is a newline!

There are several test cases here and the comments when run should be self explanatory enough. This is quite obscure, but not understanding what's going on is a little disconcerting. I'm going to file a bug report.

<html>

    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>   

        <script>
            $(function() {

                // the following two blocks of HTML are identical except the P tag is outside the form in the first case
                var html1 = "<p><form id='form1'><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></form></p>";
                var html2 = "<form id='form1'><p><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></p></form>";

                // <FORM> tag nested within <P>
                RunTest("<FORM> tag nested within <P> tag", html1);                 // succeeds in Internet Explorer    
                RunTest("<FORM> tag nested within <P> tag with leading newline", "\n" + html1);     // fails with added new line in Internet Explorer


                // <P> tag nested within <HTML>
                RunTest("<P> tag nested within <FORM> tag", html2);                 // succeeds in Internet Explorer
                RunTest("<P> tag nested within <FORM> tag with leading newline", "\n" + html2);     // succeeds in Internet Explorer even with \n

            });

            function RunTest(testName, html) {

                // run with jQuery
                $("#placeholder").html(html);
                var jqueryDOM = $('#placeholder').html();
                var jqueryFormSerialize = $("#placeholder form").serialize();

                // run with innerHTML
                $("#placeholder")[0].innerHTML = html;

                var innerHTMLDOM = $('#placeholder').html();
                var innerHTMLFormSerialize = $("#placeholder form").serialize();

                var expectedSerializedValue = "field1=111&field2=222";

                alert(  'TEST NAME: ' + testName + '\n\n' +
                    'The HTML :\n"' + html + '"\n\n' +
                    'looks like this in the DOM when assigned with jQuery.html() :\n"' + jqueryDOM + '"\n\n' +
                    'and looks like this in the DOM when assigned with innerHTML :\n"' + innerHTMLDOM + '"\n\n' +

                    'We expect the form to serialize with jQuery.serialize() to be "' + expectedSerializedValue + '"\n\n' +

                    'When using jQuery to initially set the DOM the serialized value is :\n"' + jqueryFormSerialize + '\n' +
                    'When using innerHTML to initially set the DOM the serialized value is :\n"' + innerHTMLFormSerialize + '\n\n' +

                    'jQuery test : ' + (jqueryFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") + '\n' +
                    'InnerHTML test : ' + (innerHTMLFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") 

                    );
            }

        </script>
    </head>

    <div id="placeholder">
        This is #placeholder text will 
    </div>

</html>

Should I use encodeURI or encodeURIComponent for encoding URLs?

As a general rule use encodeURIComponent. Don't be scared of the long name thinking it's more specific in it's use, to me it's the more commonly used method. Also don't be suckered into using encodeURI because you tested it and it appears to be encoding properly, it's probably not what you meant to use and even though your simple test using "Fred" in a first name field worked, you'll find later when you use more advanced text like adding an ampersand or a hashtag it will fail. You can look at the other answers for the reasons why this is.

How to check if a string contains an element from a list in Python

It is better to parse the URL properly - this way you can handle http://.../file.doc?foo and http://.../foo.doc/file.exe correctly.

from urlparse import urlparse
import os
path = urlparse(url_string).path
ext = os.path.splitext(path)[1]
if ext in extensionsToCheck:
  print(url_string)

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

How come I can't remove the blue textarea border in Twitter Bootstrap?

For anyone still searching. It's neither border or box-shadow. It's actually "outline". So just set outline: none; to disable it.

TypeError: p.easing[this.easing] is not a function

If you're using Bootstrap it's also possible that Bootstrap's jQuery, if included below your jQuery script tag, is overwriting your jQuery script tag with another version. Including jQuery's own CDN and deleting the jQuery script tag that Bootstrap provides was the only thing that worked for me.

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error is often caused by incompatible jQuery versions. I encountered the same error with a foundation 6 repository. My repository was using jQuery 3, but foundation requires an earlier version. I then changed it and it worked.

If you look at the version of jQuery required by the foundation 5 dependencies it states "jquery": "~2.1.0".

Can you confirm that you are loading the correct version of jQuery?

I hope this helps.

List all the files and folders in a Directory with PHP recursive function

Here is what I came up with and this is with not much lines of code

function show_files($start) {
    $contents = scandir($start);
    array_splice($contents, 0,2);
    echo "<ul>";
    foreach ( $contents as $item ) {
        if ( is_dir("$start/$item") && (substr($item, 0,1) != '.') ) {
            echo "<li>$item</li>";
            show_files("$start/$item");
        } else {
            echo "<li>$item</li>";
        }
    }
    echo "</ul>";
}

show_files('./');

It outputs something like

..idea
.add.php
.add_task.php
.helpers
 .countries.php
.mysqli_connect.php
.sort.php
.test.js
.test.php
.view_tasks.php

** The dots are the dots of unoordered list.

Hope this helps.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

GLSL Shader version based on Patapoms answer:

vec3 HSV2RGB( vec3 hsv )
{
    hsv.x = mod( 100.0 + hsv.x, 1.0 ); // Ensure [0,1[
    float   HueSlice = 6.0 * hsv.x; // In [0,6[
    float   HueSliceInteger = floor( HueSlice );
    float   HueSliceInterpolant = HueSlice - HueSliceInteger; // In [0,1[ for each hue slice
    vec3  TempRGB = vec3(   hsv.z * (1.0 - hsv.y), hsv.z * (1.0 - hsv.y * HueSliceInterpolant), hsv.z * (1.0 - hsv.y * (1.0 - HueSliceInterpolant)) );
    float   IsOddSlice = mod( HueSliceInteger, 2.0 ); // 0 if even (slices 0, 2, 4), 1 if odd (slices 1, 3, 5)
    float   ThreeSliceSelector = 0.5 * (HueSliceInteger - IsOddSlice); // (0, 1, 2) corresponding to slices (0, 2, 4) and (1, 3, 5)
    vec3  ScrollingRGBForEvenSlices = vec3( hsv.z, TempRGB.zx );           // (V, Temp Blue, Temp Red) for even slices (0, 2, 4)
    vec3  ScrollingRGBForOddSlices = vec3( TempRGB.y, hsv.z, TempRGB.x );  // (Temp Green, V, Temp Red) for odd slices (1, 3, 5)
    vec3  ScrollingRGB = mix( ScrollingRGBForEvenSlices, ScrollingRGBForOddSlices, IsOddSlice );
    float   IsNotFirstSlice = clamp( ThreeSliceSelector, 0.0,1.0 );                   // 1 if NOT the first slice (true for slices 1 and 2)
    float   IsNotSecondSlice = clamp( ThreeSliceSelector-1.0, 0.0,1. );              // 1 if NOT the first or second slice (true only for slice 2)
    return  mix( ScrollingRGB.xyz, mix( ScrollingRGB.zxy, ScrollingRGB.yzx, IsNotSecondSlice ), IsNotFirstSlice );    // Make the RGB rotate right depending on final slice index
}

How to change href of <a> tag on button click through javascript

Without having a href, the click will reload the current page, so you need something like this:

<a href="#" onclick="f1()">jhhghj</a>

Or prevent the scroll like this:

<a href="#" onclick="f1(); return false;">jhhghj</a>

Or return false in your f1 function and:

<a href="#" onclick="return f1();">jhhghj</a>

....or, the unobtrusive way:

<a href="#" id="abc">jhg</a>
<a href="#" id="myLink">jhhghj</a>

<script type="text/javascript">
  document.getElementById("myLink").onclick = function() {
    document.getElementById("abc").href="xyz.php"; 
    return false;
  };
</script>

Rerender view on browser resize with React

Using React Hooks:

You can define a custom Hook that listens to the window resize event, something like this:

import React, { useLayoutEffect, useState } from 'react';

function useWindowSize() {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}

function ShowWindowDimensions(props) {
  const [width, height] = useWindowSize();
  return <span>Window size: {width} x {height}</span>;
}

The advantage here is the logic is encapsulated, and you can use this Hook anywhere you want to use the window size.

Using React classes:

You can listen in componentDidMount, something like this component which just displays the window dimensions (like <span>Window size: 1024 x 768</span>):

import React from 'react';

class ShowWindowDimensions extends React.Component {
  state = { width: 0, height: 0 };
  render() {
    return <span>Window size: {this.state.width} x {this.state.height}</span>;
  }
  updateDimensions = () => {
    this.setState({ width: window.innerWidth, height: window.innerHeight });
  };
  componentDidMount() {
    window.addEventListener('resize', this.updateDimensions);
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions);
  }
}

How to re-sign the ipa file?

Check iResign for an easy tool on how to do this!

[edit] after some fudling around, I found a solution to keychain-aware resigning. You can check it out at https://gist.github.com/Weptun/5406993

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

diff to output only the file names

You can also use rsync

rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out

Open Facebook Page in Facebook App (if installed) on Android

I already have answered here and it's working for me, please refer this link https://stackoverflow.com/a/40133225/3636561

    String socailLink="https://www.facebook.com/kfc";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String facebookUrl = Utils.getFacebookUrl(getActivity(), socailLink);
    if (facebookUrl == null || facebookUrl.length() == 0) {
        Log.d("facebook Url", " is coming as " + facebookUrl);
        return;
    }
    intent.setData(Uri.parse(facebookUrl));
    startActivity(intent);

please refer link to get rest part.

How do you tell if a string contains another string in POSIX sh?

case $(pwd) in
  *path) echo "ends with path";;
  path*) echo "starts with path";;
  *path*) echo "contains path";;
  *) echo "this is the default";;
esac

Copy folder recursively in Node.js

This is my approach to solve this problem without any extra modules. Just using the built-in fs and path modules.

Note: This does use the read / write functions of fs, so it does not copy any meta data (time of creation, etc.). As of Node.js 8.5 there is a copyFileSync function available which calls the OS copy functions and therefore also copies meta data. I did not test them yet, but it should work to just replace them. (See https://nodejs.org/api/fs.html#fs_fs_copyfilesync_src_dest_flags)

var fs = require('fs');
var path = require('path');

function copyFileSync( source, target ) {

    var targetFile = target;

    // If target is a directory, a new file with the same name will be created
    if ( fs.existsSync( target ) ) {
        if ( fs.lstatSync( target ).isDirectory() ) {
            targetFile = path.join( target, path.basename( source ) );
        }
    }

    fs.writeFileSync(targetFile, fs.readFileSync(source));
}

function copyFolderRecursiveSync( source, target ) {
    var files = [];

    // Check if folder needs to be created or integrated
    var targetFolder = path.join( target, path.basename( source ) );
    if ( !fs.existsSync( targetFolder ) ) {
        fs.mkdirSync( targetFolder );
    }

    // Copy
    if ( fs.lstatSync( source ).isDirectory() ) {
        files = fs.readdirSync( source );
        files.forEach( function ( file ) {
            var curSource = path.join( source, file );
            if ( fs.lstatSync( curSource ).isDirectory() ) {
                copyFolderRecursiveSync( curSource, targetFolder );
            } else {
                copyFileSync( curSource, targetFolder );
            }
        } );
    }
}

Casting LinkedHashMap to Complex Object

There is a good solution to this issue:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class); 

Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);

Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.

Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)

Gson gson = new GsonBuilder().create();

Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();

BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);

BigDecimal revenue = results.getResult().get(0).getRevenue();

setOnItemClickListener on custom ListView

Sorry for coding with Kotlin. But I faced the same problem. I solved with the code below.

list.setOnItemClickListener{ _, view, _, _ ->
        val text1 = view.find<TextView>(R.id.~~).text

        }

You can put an id which shows a TextView that you want in "~~".

Hope it'll help someone!

Show image using file_get_contents

You can use readfile and output the image headers which you can get from getimagesize like this:

$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: {$imginfo['mime']}");
readfile($remoteImage);

The reason you should use readfile here is that it outputs the file directly to the output buffer where as file_get_contents will read the file into memory which is unnecessary in this content and potentially intensive for large files.

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

warning about too many open figures

If you intend to knowingly keep many plots in memory, but don't want to be warned about it, you can update your options prior to generating figures.

import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})

This will prevent the warning from being emitted without changing anything about the way memory is managed.

How do I select a random value from an enumeration?

You can also cast a random value:

using System;

enum Test {
  Value1,
  Value2,
  Value3
}

class Program {
  public static void Main (string[] args) {
    var max = Enum.GetValues(typeof(Test)).Length;
    var value = (Test)new Random().Next(0, max - 1);
    Console.WriteLine(value);
  }
}

But you should use a better randomizer like the one in this library of mine.

docker error - 'name is already in use by container'

You can remove it with command sudo docker rm YOUR_CONTAINER_ID, then run a new container with sudo docker run ...; or restart an existing container with sudo docker start YOUR_CONTAINER_ID

Check if string has space in between (or anywhere)

Trim() will only remove leading or trailing spaces.

Try .Contains() to check if a string contains white space

"sossjjs sskkk".Contains(" ") // returns true

How can I get the last character in a string?

Javascript strings have a length property that will tell you the length of the string.

Then all you have to do is use the substr() function to get the last character:

var myString = "Test3";
var lastChar = myString.substr(myString.length -1);

edit: yes, or use the array notation as the other posts before me have done.

Lots of String functions explained here

Using group by on multiple columns

Here I am going to explain not only the GROUP clause use, but also the Aggregate functions use.

The GROUP BY clause is used in conjunction with the aggregate functions to group the result-set by one or more columns. e.g.:

-- GROUP BY with one parameter:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

-- GROUP BY with two parameters:
SELECT
    column_name1,
    column_name2,
    AGGREGATE_FUNCTION(column_name3)
FROM
    table_name
GROUP BY
    column_name1,
    column_name2;

Remember this order:

  1. SELECT (is used to select data from a database)

  2. FROM (clause is used to list the tables)

  3. WHERE (clause is used to filter records)

  4. GROUP BY (clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns)

  5. HAVING (clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE)

  6. ORDER BY (keyword is used to sort the result-set)

You can use all of these if you are using aggregate functions, and this is the order that they must be set, otherwise you can get an error.

Aggregate Functions are:

MIN() returns the smallest value in a given column

MAX() returns the maximum value in a given column.

SUM() returns the sum of the numeric values in a given column

AVG() returns the average value of a given column

COUNT() returns the total number of values in a given column

COUNT(*) returns the number of rows in a table

SQL script examples about using aggregate functions:

Let's say we need to find the sale orders whose total sale is greater than $950. We combine the HAVING clause and the GROUP BY clause to accomplish this:

SELECT 
    orderId, SUM(unitPrice * qty) Total
FROM
    OrderDetails
GROUP BY orderId
HAVING Total > 950;

Counting all orders and grouping them customerID and sorting the result ascendant. We combine the COUNT function and the GROUP BY, ORDER BY clauses and ASC:

SELECT 
    customerId, COUNT(*)
FROM
    Orders
GROUP BY customerId
ORDER BY COUNT(*) ASC;

Retrieve the category that has an average Unit Price greater than $10, using AVG function combine with GROUP BY and HAVING clauses:

SELECT 
    categoryName, AVG(unitPrice)
FROM
    Products p
INNER JOIN
    Categories c ON c.categoryId = p.categoryId
GROUP BY categoryName
HAVING AVG(unitPrice) > 10;

Getting the less expensive product by each category, using the MIN function in a subquery:

SELECT categoryId,
       productId,
       productName,
       unitPrice
FROM Products p1
WHERE unitPrice = (
                SELECT MIN(unitPrice)
                FROM Products p2
                WHERE p2.categoryId = p1.categoryId)

The following statement groups rows with the same values in both categoryId and productId columns:

SELECT 
    categoryId, categoryName, productId, SUM(unitPrice)
FROM
    Products p
INNER JOIN
    Categories c ON c.categoryId = p.categoryId
GROUP BY categoryId, productId

android edittext onchange listener

 myTextBox.addTextChangedListener(new TextWatcher() {  

    public void afterTextChanged(Editable s) {}  

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 

    public void onTextChanged(CharSequence s, int start, int before, int count) {  

    TextView myOutputBox = (TextView) findViewById(R.id.myOutputBox);  
    myOutputBox.setText(s);  

    }  
});  

SSIS how to set connection string dynamically from a config file

Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.

You can add Environment variable also in this process

How to include external Python code to use in other files?

You will need to import the other file as a module like this:

import Math

If you don't want to prefix your Calculate function with the module name then do this:

from Math import Calculate

If you want to import all members of a module then do this:

from Math import *

Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

How do I test a private function or a class that has private methods, fields or inner classes?

In the Spring Framework you can test private methods using this method:

ReflectionTestUtils.invokeMethod()

For example:

ReflectionTestUtils.invokeMethod(TestClazz, "createTest", "input data");

How to create a notification with NotificationCompat.Builder?

Use this code

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
            PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                    (int) System.currentTimeMillis(), intent, 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.your_notification_icon)
                            .setContentTitle("Notification title")
                            .setContentText("Notification message!")
                            .setContentIntent(pIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

Emulate ggplot2 default color palette

It is just equally spaced hues around the color wheel, starting from 15:

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

For example:

n = 4
cols = gg_color_hue(n)

dev.new(width = 4, height = 4)
plot(1:n, pch = 16, cex = 2, col = cols)

enter image description here

How do I get the full url of the page I am on in C#

If you need the port number also, you can use

Request.Url.Authority

Example:

string url = Request.Url.Authority + HttpContext.Current.Request.RawUrl.ToString();

if (Request.ServerVariables["HTTPS"] == "on")
{
    url = "https://" + url;
}
else 
{
    url = "http://" + url;
}

Regex lookahead, lookbehind and atomic groups

Examples

Given the string foobarbarfoo:

bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar)     finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar    finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar    finds the 2nd bar ("bar" which does not have "foo" before it)

You can also combine them:

(?<=foo)bar(?=bar)    finds the 1st bar ("bar" with "foo" before it and "bar" after it)

Definitions

Look ahead positive (?=)

Find expression A where expression B follows:

A(?=B)

Look ahead negative (?!)

Find expression A where expression B does not follow:

A(?!B)

Look behind positive (?<=)

Find expression A where expression B precedes:

(?<=B)A

Look behind negative (?<!)

Find expression A where expression B does not precede:

(?<!B)A

Atomic groups (?>)

An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).

  • (?>foo|foot)s applied to foots will match its 1st alternative foo, then fail as s does not immediately follow, and stop as backtracking is disabled

A non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.

  • (foo|foot)s applied to foots will:

    1. match its 1st alternative foo, then fail as s does not immediately follow in foots, and backtrack to its 2nd alternative;
    2. match its 2nd alternative foot, then succeed as s immediately follows in foots, and stop.

Some resources

Online testers

How to get json key and value in javascript?

It looks like data not contains what you think it contains - check it.

_x000D_
_x000D_
let data={"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"};_x000D_
_x000D_
console.log( data["jobtitel"] );_x000D_
console.log( data.jobtitel );
_x000D_
_x000D_
_x000D_

Is a view faster than a simple query?

In my finding, using the view is a little bit faster than a normal query. My stored procedure was taking around 25 minutes (working with a different larger record sets and multiple joins) and after using the view (non-clustered), the performance was just a little bit faster but not significant at all. I had to use some other query optimization techniques/method to make it a dramatic change.

How do I add a border to an image in HTML?

as said above simple line of code will fix your problems

border: 1px solid #000;

There is another option to add border to your image and that with photoshop you can see how it's done with this tutorial below: http://bannercheapdesign.com/articles-and-tutorials/learn-how-to-add-border-to-your-banner-design-using-photoshop/

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

What do curly braces mean in Verilog?

As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]} are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".

{16{a[15]}}

is the same as

{ 
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}

In bit-blasted form,

assign result = {{16{a[15]}}, {a[15:0]}};

is the same as:

assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];

Remove new lines from string and replace with one empty space

I was surprised to see how little everyone knows about regex.

Strip newlines in php is

$str = preg_replace('/\r?\n$/', ' ', $str);

In perl

$str =~ s/\r?\n$/ /g;

Meaning replace any newline character at the end of the line (for efficiency) - optionally preceded by a carriage return - with a space.

\n or \015 is newline. \r or \012 is carriage return. ? in regex means match 1 or zero of the previous character. $ in regex means match end of line.

The original and best regex reference is perldoc perlre, every coder should know this doc pretty well: http://perldoc.perl.org/perlre.html Note not all features are supported by all languages.

Android emulator: could not get wglGetExtensionsStringARB error

For me changing the Emulated Performance setting to "Store a snapshot for faster startup" and unchecking "Use Host GPU" fixed the problem.

How to round down to nearest integer in MySQL?

SELECT FLOOR(12345.7344);

Read more here.

Nested JSON: How to add (push) new items to an object?

library is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.

Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.

What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.

Finding what branch a Git commit came from

A poor man's option is to use the tool tig1 on HEAD, search for the commit, and then visually follow the line from that commit back up until a merge commit is seen. The default merge message should specify what branch is getting merged to where :)

1 Tig is an ncurses-based text-mode interface for Git. It functions mainly as a Git repository browser, but it can also assist in staging changes for commit at chunk level and act as a pager for output from various Git commands.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

Random number c++ in some range

You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:

25 + ( std::rand() % ( 63 - 25 + 1 ) )

How to display list items on console window in C#

Console.WriteLine(string.Join<TYPE>("\n", someObjectList));

When should I use a table variable vs temporary table in sql server?

Variable table is available only to the current session, for example, if you need to EXEC another stored procedure within the current one you will have to pass the table as Table Valued Parameter and of course this will affect the performance, with temporary tables you can do this with only passing the temporary table name

To test a Temporary table:

  • Open management studio query editor
  • Create a temporary table
  • Open another query editor window
  • Select from this table "Available"

To test a Variable table:

  • Open management studio query editor
  • Create a Variable table
  • Open another query editor window
  • Select from this table "Not Available"

something else I have experienced is: If your schema doesn't have GRANT privilege to create tables then use variable tables.

How to roundup a number to the closest ten?

Use ROUND but with num_digits = -1

=ROUND(A1,-1)

Also applies to ROUNDUP and ROUNDDOWN

From Excel help:

  • If num_digits is greater than 0 (zero), then number is rounded to the specified number of decimal places.
  • If num_digits is 0, then number is rounded to the nearest integer.
  • If num_digits is less than 0, then number is rounded to the left of the decimal point.

EDIT: To get the numbers to always round up use =ROUNDUP(A1,-1)

Check if string ends with certain pattern

I tried all the different things mentioned here to get the index of the . character in a filename that ends with .[0-9][0-9]*, e.g. srcfile.1, srcfile.12, etc. Nothing worked. Finally, the following worked: int dotIndex = inputfilename.lastIndexOf(".");

Weird! This is with java -version:

openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-0ubuntu1.16.10.2-b11)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

Also, the official Java doc page for regex (from which there is a quote in one of the answers above) does not seem to specify how to look for the . character. Because \., \\., and [.] did not work for me, and I don't see any other options specified apart from these.

MVC4 input field placeholder

There are such of ways to Bind a Placeholder to View:

1) With use of MVC Data Annotations:

Model:

[Required]
[Display(Prompt = "Enter Your First Name")]
public string FirstName { get; set; }

Razor Syntax:

@Html.TextBoxFor(m => m.FirstName, new { placeholder = @Html.DisplayNameFor(n => n.UserName)})

2) With use of MVC Data Annotations But with DisplayName:

Model:

[Required]
[DisplayName("Enter Your First Name")]
public string FirstName { get; set; }

Razor Syntax:

@Html.TextBoxFor(m => m.FirstName, new { placeholder = @Html.DisplayNameFor(n => n.UserName)})

3) Without use of MVC Data Annotation (recommended):

Razor Syntax:

@Html.TextBoxFor(m => m.FirstName, new { @placeholder = "Enter Your First Name")

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Check build.gradle(Module: Android) fixed problem for me.

Modify it to workable version.

android {
    buildToolsVersion '23.0.1'
}

Insert content into iFrame

If you want all the CSS thats on your webpage in your IFrame, try this:

var headClone, iFrameHead;

// Create a clone of the web-page head
headClone = $('head').clone();

// Find the head of the the iFrame we are looking for
iFrameHead = $('#iframe').contents().find('head');

// Replace 'iFrameHead with your Web page 'head'
iFrameHead.replaceWith(headClone);

// You should now have all the Web page CSS in the Iframe

Good Luck.

How can I store HashMap<String, ArrayList<String>> inside a list?

First, let me fix a little bit your declaration:

List<Map<String, List<String>>> listOfMapOfList = 
    new HashList<Map<String, List<String>>>();

Please pay attention that I used concrete class (HashMap) only once. It is important to use interface where you can to be able to change the implementation later.

Now you want to add element to the list, don't you? But the element is a map, so you have to create it:

Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();

Now you want to populate the map. Fortunately you can use utility that creates lists for you, otherwise you have to create list separately:

mapOfList.put("mykey", Arrays.asList("one", "two", "three"));

OK, now we are ready to add the map into the list:

listOfMapOfList.add(mapOfList);

BUT:

Stop creating complicated collections right now! Think about the future: you will probably have to change the internal map to something else or list to set etc. This will probably cause you to re-write significant parts of your code. Instead define class that contains you data and then add it to one-dimentional collection:

Let's call your class Student (just as example):

public Student {
    private String firstName;
    private String lastName;
    private int studentId;

    private Colectiuon<String> courseworks = Collections.emtpyList();

    //constructors, getters, setters etc
}

Now you can define simple collection:

Collection<Student> students = new ArrayList<Student>();

If in future you want to put your students into map where key is the studentId, do it:

Map<Integer, Student> students = new HashMap<Integer, Student>();

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

How to access the value of a promise?

Parsing the comment a little differently than your current understanding might help:

// promiseB will be resolved immediately after promiseA is resolved

This states that promiseB is a promise but will be resolved immediately after promiseA is resolved. Another way of looking at this means that promiseA.then() returns a promise that is assigned to promiseB.

// and its value will be the result of promiseA incremented by 1

This means that the value that promiseA resolved to is the value that promiseB will receive as its successCallback value:

promiseB.then(function (val) {
  // val is now promiseA's result + 1
});

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer

Divide and Conquer works by dividing the problem into sub-problems, conquer each sub-problem recursively and combine these solutions.

Dynamic Programming

Dynamic Programming is a technique for solving problems with overlapping subproblems. Each sub-problem is solved only once and the result of each sub-problem is stored in a table ( generally implemented as an array or a hash table) for future references. These sub-solutions may be used to obtain the original solution and the technique of storing the sub-problem solutions is known as memoization.

You may think of DP = recursion + re-use

A classic example to understand the difference would be to see both these approaches towards obtaining the nth fibonacci number. Check this material from MIT.


Divide and Conquer approach Divide and Conquer approach

Dynamic Programming Approach enter image description here