Programs & Examples On #Wacom

Wacom is a company that produces graphics tablets and related products.

How do I output lists as a table in Jupyter notebook?

Ok, so this was a bit harder than I though:

def print_matrix(list_of_list):
    number_width = len(str(max([max(i) for i in list_of_list])))
    cols = max(map(len, list_of_list))
    output = '+'+('-'*(number_width+2)+'+')*cols + '\n'
    for row in list_of_list:
        for column in row:
            output += '|' + ' {:^{width}d} '.format(column, width = number_width)
        output+='|\n+'+('-'*(number_width+2)+'+')*cols + '\n'
    return output

This should work for variable number of rows, columns and number of digits (for numbers)

data = [[1,2,30],
        [4,23125,6],
        [7,8,999],
        ]
print print_matrix(data)
>>>>+-------+-------+-------+
    |   1   |   2   |  30   |
    +-------+-------+-------+
    |   4   | 23125 |   6   |
    +-------+-------+-------+
    |   7   |   8   |  999  |
    +-------+-------+-------+

onCreateOptionsMenu inside Fragments

Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar or Activity has it's own Toolbar, otherwise onCreateOptionsMenu in fragment does not get called.

If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with

(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)

which lets your fragment onCreateOptionsMenu to be called.

Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU) and item listener with

toolbar.setOnMenuItemClickListener {
   // do something
   true
}

Which Java library provides base64 encoding/decoding?

Guava also has Base64 (among other encodings and incredibly useful stuff)

Getting the SQL from a Django QuerySet

As an alternative to the other answers, django-devserver outputs SQL to the console.

Pushing from local repository to GitHub hosted remote

This worked for my GIT version 1.8.4:

  1. From the local repository folder, right click and select 'Git Commit Tool'.
  2. There, select the files you want to upload, under 'Unstaged Changes' and click 'Stage Changed' button. (You can initially click on 'Rescan' button to check what files are modified and not uploaded yet.)
  3. Write a Commit Message and click 'Commit' button.
  4. Now right click in the folder again and select 'Git Bash'.
  5. Type: git push origin master and enter your credentials. Done.

Can you get the column names from a SqlDataReader?

Use an extension method:

    public static List<string> ColumnList(this IDataReader dataReader)
    {
        var columns = new List<string>();
        for (int i = 0; i < dataReader.FieldCount; i++)
        {
            columns.Add(dataReader.GetName(i));
        }
        return columns;
    }

How to get the index of an item in a list in a single step?

That's all fine and good -- but what if you want to select an existing element as the default? In my issue there is no "--select a value--" option.

Here's my code -- you could make it into a one liner if you didn't want to check for no results I suppose...

private void LoadCombo(ComboBox cb, string itemType, string defVal = "")
{
    cb.DisplayMember = "Name";
    cb.ValueMember = "ItemCode";
    cb.DataSource = db.Items.Where(q => q.ItemTypeId == itemType).ToList();

    if (!string.IsNullOrEmpty(defVal))
    {
        var i = ((List<GCC_Pricing.Models.Item>)cb.DataSource).FindIndex(q => q.ItemCode == defVal);
        if (i>=0) cb.SelectedIndex = i;
    }
}

How to print a debug log?

I use cakephp so I use:

$this->log(YOUR_STRING_GOES_HERE, 'debug');

How to check if NSString begins with a certain character

As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.

NSString* myString = @"10:Username taken";

if([myString hasPrefix:@"10"]) {
      //display more elegant error message
}

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

The below should work properly, and for all browsers (thanks to @MattJohnson for the tip)

_x000D_
_x000D_
Date.prototype.toIsoString = function() {_x000D_
    var tzo = -this.getTimezoneOffset(),_x000D_
        dif = tzo >= 0 ? '+' : '-',_x000D_
        pad = function(num) {_x000D_
            var norm = Math.floor(Math.abs(num));_x000D_
            return (norm < 10 ? '0' : '') + norm;_x000D_
        };_x000D_
    return this.getFullYear() +_x000D_
        '-' + pad(this.getMonth() + 1) +_x000D_
        '-' + pad(this.getDate()) +_x000D_
        'T' + pad(this.getHours()) +_x000D_
        ':' + pad(this.getMinutes()) +_x000D_
        ':' + pad(this.getSeconds()) +_x000D_
        dif + pad(tzo / 60) +_x000D_
        ':' + pad(tzo % 60);_x000D_
}_x000D_
_x000D_
var dt = new Date();_x000D_
console.log(dt.toIsoString());
_x000D_
_x000D_
_x000D_

Convert Unicode data to int in python

int(limit) returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).

Do this instead:

limit = int(limit)

Or when definiting limit:

if 'limit' in user_data :
    limit = int(user_data['limit'])

How can I play sound in Java?

A bad example:

import  sun.audio.*;    //import the sun.audio package
import  java.io.*;

//** add this into your application code as appropriate
// Open an input stream  to the audio file.
InputStream in = new FileInputStream(Filename);

// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);         

// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);            

// Similarly, to stop the audio.
AudioPlayer.player.stop(as); 

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Running ASP.Net on a Linux based server

Since the technologies evolve and this question is top ranked in google, we need to include beyond the mono the new asp.net core, which is a complete rewrite of the asp.net to run for production in Linux and Windows and for development for Linux, Windows and Mac:

You can develop and run your ASP.NET Core apps cross-platform on Windows, Mac and Linux. ASP.NET Core is open source at GitHub.

How to show Bootstrap table with sort icon

You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).

To do so, you would

  1. need to include fontawesome:

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th's:

    <th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
    

Hope that helps.

Center a column using Twitter Bootstrap 3

This works. A hackish way probably, but it works nicely. It was tested for responsive (Y).

.centered {
    background-color: teal;
    text-align: center;
}

Desktop

Responsive

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

Getting date format m-d-Y H:i:s.u from milliseconds

php.net says:

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

So use as simple:

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";

Recommended and use dateTime() class from referenced:

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d H:i:s.u"); // note at point on "u"

Note u is microseconds (1 seconds = 1000000 µs).

Another example from php.net:

$d2=new DateTime("2012-07-08 11:14:15.889342");

Reference of dateTime() on php.net

I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds

How to modify JsonNode in Java?

I think you can just cast to ObjectNode and use put method. Like this

ObjectNode o = (ObjectNode) jsonNode; o.put("value", "NO");

Attempted to read or write protected memory

I had the same problem after upgrading from .NET 4.5 to .NET 4.5.1. What fixed it for me was running this command:

netsh winsock reset

MVC - Set selected value of SelectList

I wanted the dropdown to select the matching value of the id in the action method. The trick is to set the Selected property when creating the SelectListItem Collection. It would not work any other way, perhaps I missed something but in end, it is more elegant in my option.

You can write any method that returns a boolean to set the Selected value based on your requirements, in my case I used the existing Equal Method

public ActionResult History(long id)
        {
            var app = new AppLogic();
            var historyVM = new ActivityHistoryViewModel();

            historyVM.ProcessHistory = app.GetActivity(id);
            historyVM.Process = app.GetProcess(id);
            var processlist = app.GetProcessList();

            historyVM.ProcessList = from process in processlist
                                    select new SelectListItem
                                    {
                                        Text = process.ProcessName,
                                        Value = process.ID.ToString(),
                                        Selected = long.Equals(process.ID, id)                                    

                                    };

            var listitems = new List<SelectListItem>();

            return View(historyVM);
        }

What is the difference between the dot (.) operator and -> in C++?

Note that the -> operator cannot be used for certain things, for instance, accessing operator[].

#include <vector>

int main()
{
   std::vector<int> iVec;
   iVec.push_back(42);
   std::vector<int>* iVecPtr = &iVec;

   //int i = iVecPtr->[0]; // Does not compile
   int i = (*iVecPtr)[0]; // Compiles.
}

SQL Server database backup restore on lower version

You can not restore database (or attach) created in the upper version into lower version. The only way is to create a script for all objects and use the script to generate database.

enter image description here

select "Schema and Data" - if you want to Take both the things in to the Backup script file
select Schema Only - if only schema is needed.

enter image description here

Yes, now you have done with the Create Script with Schema and Data of the Database.

How to get the first element of an array?

In ES2015 and above, using array destructuring:

_x000D_
_x000D_
const arr = [42, 555, 666, 777]_x000D_
const [first] = arr_x000D_
console.log(first)
_x000D_
_x000D_
_x000D_

Difference between Node object and Element object?

Element inherits from Node, in the same way that Dog inherits from Animal.

An Element object "is-a" Node object, in the same way that a Dog object "is-a" Animal object.

Node is for implementing a tree structure, so its methods are for firstChild, lastChild, childNodes, etc. It is more of a class for a generic tree structure.

And then, some Node objects are also Element objects. Element inherits from Node. Element objects actually represents the objects as specified in the HTML file by the tags such as <div id="content"></div>. The Element class define properties and methods such as attributes, id, innerHTML, clientWidth, blur(), and focus().

Some Node objects are text nodes and they are not Element objects. Each Node object has a nodeType property that indicates what type of node it is, for HTML documents:

1: Element node
3: Text node
8: Comment node
9: the top level node, which is document

We can see some examples in the console:

> document instanceof Node
  true

> document instanceof Element
  false

> document.firstChild
  <html>...</html>

> document.firstChild instanceof Node
  true

> document.firstChild instanceof Element
  true

> document.firstChild.firstChild.nextElementSibling
  <body>...</body>

> document.firstChild.firstChild.nextElementSibling === document.body
  true

> document.firstChild.firstChild.nextSibling
  #text

> document.firstChild.firstChild.nextSibling instanceof Node
  true

> document.firstChild.firstChild.nextSibling instanceof Element
  false

> Element.prototype.__proto__ === Node.prototype
  true

The last line above shows that Element inherits from Node. (that line won't work in IE due to __proto__. Will need to use Chrome, Firefox, or Safari).

By the way, the document object is the top of the node tree, and document is a Document object, and Document inherits from Node as well:

> Document.prototype.__proto__ === Node.prototype
  true

Here are some docs for the Node and Element classes:
https://developer.mozilla.org/en-US/docs/DOM/Node
https://developer.mozilla.org/en-US/docs/DOM/Element

How to restart Activity in Android

If you are calling from some fragment so do below code.

Intent intent = getActivity().getIntent();
getActivity().finish();
startActivity(intent);

Keyboard shortcuts in WPF

Although the top answers are correct, I personally like to work with attached properties to enable the solution to be applied to any UIElement, especially when the Window is not aware of the element that should be focused. In my experience I often see a composition of several view models and user controls, where the window is often nothing more that the root container.

Snippet

public sealed class AttachedProperties
{
    // Define the key gesture type converter
    [System.ComponentModel.TypeConverter(typeof(System.Windows.Input.KeyGestureConverter))]
    public static KeyGesture GetFocusShortcut(DependencyObject dependencyObject)
    {
        return (KeyGesture)dependencyObject?.GetValue(FocusShortcutProperty);
    }

    public static void SetFocusShortcut(DependencyObject dependencyObject, KeyGesture value)
    {
        dependencyObject?.SetValue(FocusShortcutProperty, value);
    }

    /// <summary>
    /// Enables window-wide focus shortcut for an <see cref="UIElement"/>.
    /// </summary>
    // Using a DependencyProperty as the backing store for FocusShortcut.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty FocusShortcutProperty =
        DependencyProperty.RegisterAttached("FocusShortcut", typeof(KeyGesture), typeof(AttachedProperties), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, new PropertyChangedCallback(OnFocusShortcutChanged)));

    private static void OnFocusShortcutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is UIElement element) || e.NewValue == e.OldValue)
            return;

        var window = FindParentWindow(d);
        if (window == null)
            return;

        var gesture = GetFocusShortcut(d);
        if (gesture == null)
        {
            // Remove previous added input binding.
            for (int i = 0; i < window.InputBindings.Count; i++)
            {
                if (window.InputBindings[i].Gesture == e.OldValue && window.InputBindings[i].Command is FocusElementCommand)
                    window.InputBindings.RemoveAt(i--);
            }
        }
        else
        {
            // Add new input binding with the dedicated FocusElementCommand.
            // see: https://gist.github.com/shuebner20/349d044ed5236a7f2568cb17f3ed713d
            var command = new FocusElementCommand(element);
            window.InputBindings.Add(new InputBinding(command, gesture));
        }
    }
}

With this attached property you can define a focus shortcut for any UIElement. It will automatically register the input binding at the window containing the element.

Usage (XAML)

<TextBox x:Name="SearchTextBox"
         Text={Binding Path=SearchText}
         local:AttachedProperties.FocusShortcutKey="Ctrl+Q"/>

Source code

The full sample including the FocusElementCommand implementation is available as gist: https://gist.github.com/shuebner20/c6a5191be23da549d5004ee56bcc352d

Disclaimer: You may use this code everywhere and free of charge. Please keep in mind, that this is a sample that is not suitable for heavy usage. For example, there is no garbage collection of removed elements because the Command will hold a strong reference to the element.

How do I encode and decode a base64 string?

A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:

using System;

namespace Service.Support
{
    public static class Base64
    {
        public static string ToBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return Convert.ToBase64String(textAsBytes);
        }

        public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
        {
            if (encodedText == null)
            {
                decodedText = null;
                return false;
            }

            try
            {
                byte[] textAsBytes = Convert.FromBase64String(encodedText);
                decodedText = encoding.GetString(textAsBytes);
                return true;
            }
            catch (Exception)
            {
                decodedText = null;
                return false;   
            }
        }
    }
}

How to define a preprocessor symbol in Xcode

Go to your Target or Project settings, click the Gear icon at the bottom left, and select "Add User-Defined Setting". The new setting name should be GCC_PREPROCESSOR_DEFINITIONS, and you can type your definitions in the right-hand field.

Per Steph's comments, the full syntax is:

constant_1=VALUE constant_2=VALUE

Note that you don't need the '='s if you just want to #define a symbol, rather than giving it a value (for #ifdef statements)

JSON.NET Error Self referencing loop detected for type

For .NET Core 3.0, update the Startup.cs class as shown below.

public void ConfigureServices(IServiceCollection services)
{
...

services.AddControllers()
    .AddNewtonsoftJson(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

...
}

See: https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-core-3-0-preview-5/

What's the difference between TRUNCATE and DELETE in SQL

TRUNCATE

TRUNCATE SQL query removes all rows from a table, without logging the individual row deletions.

  • TRUNCATE is a DDL command.
  • TRUNCATE is executed using a table lock and whole table is locked for remove all records.
  • We cannot use WHERE clause with TRUNCATE.
  • TRUNCATE removes all rows from a table.
  • Minimal logging in transaction log, so it is faster performance wise.
  • TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.
  • To use Truncate on a table you need at least ALTER permission on the table.
  • Truncate uses less transaction space than the Delete statement.
  • Truncate cannot be used with indexed views.
  • TRUNCATE is faster than DELETE.

DELETE

To execute a DELETE queue, delete permissions are required on the target table. If you need to use a WHERE clause in a DELETE, select permissions are required as well.

  • DELETE is a DML command.
  • DELETE is executed using a row lock, each row in the table is locked for deletion.
  • We can use where clause with DELETE to filter & delete specific records.
  • The DELETE command is used to remove rows from a table based on WHERE condition.
  • It maintain the log, so it slower than TRUNCATE.
  • The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row.
  • Identity of column keep DELETE retains the identity.
  • To use Delete you need DELETE permission on the table.
  • Delete uses the more transaction space than Truncate statement.
  • Delete can be used with indexed views.

Setting TIME_WAIT TCP

I have been load testing a server application (on linux) by using a test program with 20 threads.

In 959,000 connect / close cycles I had 44,000 failed connections and many thousands of sockets in TIME_WAIT.

I set SO_LINGER to 0 before the close call and in subsequent runs of the test program had no connect failures and less than 20 sockets in TIME_WAIT.

How do I open a URL from C++?

I was having the exact same problem in Windows.

I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:

'open' is not recognized as an internal or external command

After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.

Linux: xdg-open <URL>

Windows: start <URL>


For those of you that are using Windows, as I am, you can use the following:

std::string op = std::string("start ").append(url);
system(op.c_str());

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

In regards to Python optimization, in addition to using PyPy (for pretty impressive speed-ups with zero change to your code), you could use PyPy's translation toolchain to compile an RPython-compliant version, or Cython to build an extension module, both of which are faster than the C version in my testing, with the Cython module nearly twice as fast. For reference I include C and PyPy benchmark results as well:

C (compiled with gcc -O3 -lm)

% time ./euler12-c 
842161320

./euler12-c  11.95s 
 user 0.00s 
 system 99% 
 cpu 11.959 total

PyPy 1.5

% time pypy euler12.py
842161320
pypy euler12.py  
16.44s user 
0.01s system 
99% cpu 16.449 total

RPython (using latest PyPy revision, c2f583445aee)

% time ./euler12-rpython-c
842161320
./euler12-rpy-c  
10.54s user 0.00s 
system 99% 
cpu 10.540 total

Cython 0.15

% time python euler12-cython.py
842161320
python euler12-cython.py  
6.27s user 0.00s 
system 99% 
cpu 6.274 total

The RPython version has a couple of key changes. To translate into a standalone program you need to define your target, which in this case is the main function. It's expected to accept sys.argv as it's only argument, and is required to return an int. You can translate it by using translate.py, % translate.py euler12-rpython.py which translates to C and compiles it for you.

# euler12-rpython.py

import math, sys

def factorCount(n):
    square = math.sqrt(n)
    isquare = int(square)
    count = -1 if isquare == square else 0
    for candidate in xrange(1, isquare + 1):
        if not n % candidate: count += 2
    return count

def main(argv):
    triangle = 1
    index = 1
    while factorCount(triangle) < 1001:
        index += 1
        triangle += index
    print triangle
    return 0

if __name__ == '__main__':
    main(sys.argv)

def target(*args):
    return main, None

The Cython version was rewritten as an extension module _euler12.pyx, which I import and call from a normal python file. The _euler12.pyx is essentially the same as your version, with some additional static type declarations. The setup.py has the normal boilerplate to build the extension, using python setup.py build_ext --inplace.

# _euler12.pyx
from libc.math cimport sqrt

cdef int factorCount(int n):
    cdef int candidate, isquare, count
    cdef double square
    square = sqrt(n)
    isquare = int(square)
    count = -1 if isquare == square else 0
    for candidate in range(1, isquare + 1):
        if not n % candidate: count += 2
    return count

cpdef main():
    cdef int triangle = 1, index = 1
    while factorCount(triangle) < 1001:
        index += 1
        triangle += index
    print triangle

# euler12-cython.py
import _euler12
_euler12.main()

# setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("_euler12", ["_euler12.pyx"])]

setup(
  name = 'Euler12-Cython',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules
)

I honestly have very little experience with either RPython or Cython, and was pleasantly surprised at the results. If you are using CPython, writing your CPU-intensive bits of code in a Cython extension module seems like a really easy way to optimize your program.

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

How to set different colors in HTML in one statement?

How about using FONT tag?

Like:

H<font color="red">E</font>LLO.

Can't show example here, because this site doesn't allow font tag use.

Span style is fast and easy too.

Update Row if it Exists Else Insert Logic with Entity Framework

The magic happens when calling SaveChanges() and depends on the current EntityState. If the entity has an EntityState.Added, it will be added to the database, if it has an EntityState.Modified, it will be updated in the database. So you can implement an InsertOrUpdate() method as follows:

public void InsertOrUpdate(Blog blog) 
{ 
    using (var context = new BloggingContext()) 
    { 
        context.Entry(blog).State = blog.BlogId == 0 ? 
                                   EntityState.Added : 
                                   EntityState.Modified; 

        context.SaveChanges(); 
    } 
}

More about EntityState

If you can't check on Id = 0 to determine if it's a new entity or not, check the answer of Ladislav Mrnka.

jQuery autoComplete view all on click?

this is the only thing that works for me. List shows everytime and closes upon selection:

$("#example")
.autocomplete(...)
.focus(function()
{
  var self = this;

  window.setTimeout(function()
  {
    if (self.value.length == 0)
      $(self).autocomplete('search', '');
  });
})

catch specific HTTP error in python

Tims answer seems to me as misleading. Especially when urllib2 does not return expected code. For example this Error will be fatal (believe or not - it is not uncommon one when downloading urls):

AttributeError: 'URLError' object has no attribute 'code'

Fast, but maybe not the best solution would be code using nested try/except block:

import urllib2
try:
    urllib2.urlopen("some url")
except urllib2.HTTPError, err:
    try:
        if err.code == 404:
            # Handle the error
        else:
            raise
    except:
        ...

More information to the topic of nested try/except blocks Are nested try/except blocks in python a good programming practice?

How to use WPF Background Worker

  1. Add using
using System.ComponentModel;
  1. Declare Background Worker:
private readonly BackgroundWorker worker = new BackgroundWorker();
  1. Subscribe to events:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
  1. Implement two methods:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
  // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender, 
                                           RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}
  1. Run worker async whenever your need.
worker.RunWorkerAsync();
  1. Track progress (optional, but often useful)

    a) subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork

    b) set worker.WorkerReportsProgress = true; (credits to @zagy)

SQL query to group by day

For SQL Server:

GROUP BY datepart(year,datefield), 
    datepart(month,datefield), 
    datepart(day,datefield)

or faster (from Q8-Coder):

GROUP BY dateadd(DAY,0, datediff(day,0, created))

For MySQL:

GROUP BY year(datefield), month(datefield), day(datefield)

or better (from Jon Bright):

GROUP BY date(datefield)

For Oracle:

GROUP BY to_char(datefield, 'yyyy-mm-dd')

or faster (from IronGoofy):

GROUP BY trunc(created);

For Informix (by Jonathan Leffler):

GROUP BY date_column
GROUP BY EXTEND(datetime_column, YEAR TO DAY)

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

The profiler trace puts it into perspective.

  • Query A: 1.3 secs CPU, 1.4 secs duration
  • Query B: 2.3 secs CPU, 1.2 secs duration

Query B is using parallelism: CPU > duration eg the query uses 2 CPUs, average 1.15 secs each

Query A is probably not: CPU < duration

This explains cost relative to batch: 17% of the for the simpler, non-parallel query plan.

The optimiser works out that query B is more expensive and will benefit from parallelism, even though it takes extra effort to do so.

Remember though, that query B uses 100% of 2 CPUS (so 50% for 4 CPUs) for one second or so. Query A uses 100% of a single CPU for 1.5 seconds.

The peak for query A is lower, at the expense of increased duration. With one user, who cares? With 100, perhaps it makes a difference...

What is ViewModel in MVC?

A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.

You might only want specific properties, so this allows you to only load those and not additional unneccesary properties

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

A quick fix for capistrano user is to put this line to Capfile

# Uncomment if you are using Rails' asset pipeline
load 'deploy/assets'

Object of class stdClass could not be converted to string

What I was looking for is a way to fetch the data

so I used this $data = $this->db->get('table_name')->result_array();

and then fetched my data just as you operate on array objects.

$data[0]['field_name']

No need to worry about type casting or anything just straight to the point.

So it worked for me.

Is there any way to prevent input type="number" getting negative values?

This code is working fine for me. Can you please check:

<input type="number" name="test" min="0" oninput="validity.valid||(value='');">

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

In my case the issue was that Virtual directory was not created.

  1. Right click on web project file and go to properties
  2. Navigate to Web
  3. Scroll down to Project Url
  4. Click Create Virtual Directory button to create virtual directory

enter image description here

How to find time complexity of an algorithm

Loosely speaking, time complexity is a way of summarising how the number of operations or run-time of an algorithm grows as the input size increases.

Like most things in life, a cocktail party can help us understand.

O(N)

When you arrive at the party, you have to shake everyone's hand (do an operation on every item). As the number of attendees N increases, the time/work it will take you to shake everyone's hand increases as O(N).

Why O(N) and not cN?

There's variation in the amount of time it takes to shake hands with people. You could average this out and capture it in a constant c. But the fundamental operation here --- shaking hands with everyone --- would always be proportional to O(N), no matter what c was. When debating whether we should go to a cocktail party, we're often more interested in the fact that we'll have to meet everyone than in the minute details of what those meetings look like.

O(N^2)

The host of the cocktail party wants you to play a silly game where everyone meets everyone else. Therefore, you must meet N-1 other people and, because the next person has already met you, they must meet N-2 people, and so on. The sum of this series is x^2/2+x/2. As the number of attendees grows, the x^2 term gets big fast, so we just drop everything else.

O(N^3)

You have to meet everyone else and, during each meeting, you must talk about everyone else in the room.

O(1)

The host wants to announce something. They ding a wineglass and speak loudly. Everyone hears them. It turns out it doesn't matter how many attendees there are, this operation always takes the same amount of time.

O(log N)

The host has laid everyone out at the table in alphabetical order. Where is Dan? You reason that he must be somewhere between Adam and Mandy (certainly not between Mandy and Zach!). Given that, is he between George and Mandy? No. He must be between Adam and Fred, and between Cindy and Fred. And so on... we can efficiently locate Dan by looking at half the set and then half of that set. Ultimately, we look at O(log_2 N) individuals.

O(N log N)

You could find where to sit down at the table using the algorithm above. If a large number of people came to the table, one at a time, and all did this, that would take O(N log N) time. This turns out to be how long it takes to sort any collection of items when they must be compared.

Best/Worst Case

You arrive at the party and need to find Inigo - how long will it take? It depends on when you arrive. If everyone is milling around you've hit the worst-case: it will take O(N) time. However, if everyone is sitting down at the table, it will take only O(log N) time. Or maybe you can leverage the host's wineglass-shouting power and it will take only O(1) time.

Assuming the host is unavailable, we can say that the Inigo-finding algorithm has a lower-bound of O(log N) and an upper-bound of O(N), depending on the state of the party when you arrive.

Space & Communication

The same ideas can be applied to understanding how algorithms use space or communication.

Knuth has written a nice paper about the former entitled "The Complexity of Songs".

Theorem 2: There exist arbitrarily long songs of complexity O(1).

PROOF: (due to Casey and the Sunshine Band). Consider the songs Sk defined by (15), but with

V_k = 'That's the way,' U 'I like it, ' U
U   = 'uh huh,' 'uh huh'

for all k.

When to use pthread_exit() and when to use pthread_join() in Linux?

Hmm.

POSIX pthread_exit description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:

After a thread has terminated, the result of access to local (auto) variables of the thread is 
undefined. Thus, references to local variables of the exiting thread should not be used for 
the pthread_exit() value_ptr parameter value.

Which seems contrary to the idea that local main() thread variables will remain accessible.

How to change the style of the title attribute inside an anchor tag?

A jsfiddle for custom tooltip pattern is Here

It is based on CSS Positioning and pseduo class selectors

Check MDN docs for cross-browser support of pseudo classes

    <!-- HTML -->
<p>
    <a href="http://www.google.com/" class="tooltip">
    I am a 
        <span> (This website rocks) </span></a>&nbsp; a developer.
</p>

    /*CSS*/
a.tooltip {
    position: relative;
}

a.tooltip span {
    display: none;    
}

a.tooltip:hover span, a.tooltip:focus span {
    display:block;
    position:absolute;
    top:1em;
    left:1.5em;
    padding: 0.2em 0.6em;
    border:1px solid #996633;
    background-color:#FFFF66;
    color:#000;
}

How to tell if UIViewController's view is visible

Here's @progrmr's solution as a UIViewController category:

// UIViewController+Additions.h

@interface UIViewController (Additions)

- (BOOL)isVisible;

@end


// UIViewController+Additions.m

#import "UIViewController+Additions.h"

@implementation UIViewController (Additions)

- (BOOL)isVisible {
    return [self isViewLoaded] && self.view.window;
}

@end

The meaning of NoInitialContextException error

Specifically, I got this issue when attempting to retrieve the default (no-args) InitialContext within an embedded Tomcat7 instance, in SpringBoot.

The solution for me, was to tell Tomcat to enableNaming.

i.e.

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {
        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }
    };
}

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

Parent table data missing causes the problem. In your problem non availability of data in "dbo.Sup_Item_Cat" causes the problem

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

How to concatenate string and int in C?

Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

By default , maven looks at these folders for java and test classes respectively - src/main/java and src/test/java

When the src is specified with the test classes under source and the scope for junit dependency in pom.xml is mentioned as test - org.unit will not be found by maven.

How can I drop a table if there is a foreign key constraint in SQL Server?

BhupeshC and murat , this is what I was looking for. However @SQL varchar(4000) wasn't big enough. So, small change

DECLARE @cmd varchar(4000)

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 

select 'ALTER TABLE ['+s.name+'].['+t.name+'] DROP CONSTRAINT [' + RTRIM(f.name) +'];' FROM sys.Tables t INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id INNER JOIN sys.schemas s ON s.schema_id = f.schema_id

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @cmd
WHILE @@FETCH_STATUS = 0
BEGIN
    -- EXEC (@cmd)
    PRINT @cmd
    FETCH NEXT FROM MY_CURSOR INTO @cmd
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

GO

How to pass datetime from c# to sql correctly?

I had many issues involving C# and SqlServer. I ended up doing the following:

  1. On SQL Server I use the DateTime column type
  2. On c# I use the .ToString("yyyy-MM-dd HH:mm:ss") method

Also make sure that all your machines run on the same timezone.

Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...

Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).

EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.

What is the shortest function for reading a cookie by name in JavaScript?

code from google analytics ga.js

function c(a){
    var d=[],
        e=document.cookie.split(";");
    a=RegExp("^\\s*"+a+"=\\s*(.*?)\\s*$");
    for(var b=0;b<e.length;b++){
        var f=e[b].match(a);
        f&&d.push(f[1])
    }
    return d
}

Get output parameter value in ADO.NET

Not my code, but a good example i think

source: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624

using System; 
using System.Data; 
using System.Data.SqlClient; 


class OutputParams 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 

    using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;")) 
    { 
        SqlCommand cmd = new SqlCommand("CustOrderOne", cn); 
        cmd.CommandType=CommandType.StoredProcedure ; 

        SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ; 
        parm.Value="ALFKI"; 
        parm.Direction =ParameterDirection.Input ; 
        cmd.Parameters.Add(parm); 

        SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar); 
        parm2.Size=50; 
        parm2.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm2); 

        SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int); 
        parm3.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm3);

        cn.Open(); 
        cmd.ExecuteNonQuery(); 
        cn.Close(); 

        Console.WriteLine(cmd.Parameters["@ProductName"].Value); 
        Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
        Console.ReadLine(); 
    } 
} 

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Long story short, it probably doesn't matter. Use whichever you think looks nicest.

Longer answer, using Oracle's Java 7 JDK specifically, since this isn't defined at the JLS:

String.valueOf or Character.toString work the same way, so use whichever you feel looks nicer. In fact, Character.toString simply calls String.valueOf (source).

So the question is, should you use one of those or String.substring. Here again it doesn't matter much. String.substring uses the original string's char[] and so allocates one object fewer than String.valueOf. This also prevents the original string from being GC'ed until the one-character string is available for GC (which can be a memory leak), but in your example, they'll both be available for GC after each iteration, so that doesn't matter. The allocation you save also doesn't matter -- a char[1] is cheap to allocate, and short-lived objects (as the one-char string will be) are cheap to GC, too.

If you have a large enough data set that the three are even measurable, substring will probably give a slight edge. Like, really slight. But that "if... measurable" contains the real key to this answer: why don't you just try all three and measure which one is fastest?

How to remove item from list in C#?

List<T> has two methods you can use.

RemoveAt(int index) can be used if you know the index of the item. For example:

resultlist.RemoveAt(1);

Or you can use Remove(T item):

var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);

When you are not sure the item really exists you can use SingleOrDefault. SingleOrDefault will return null if there is no item (Single will throw an exception when it can't find the item). Both will throw when there is a duplicate value (two items with the same id).

var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
    resultList.Remove(itemToRemove);

Bootstrap 3.0 Popovers and tooltips

You just need to enable the tooltip:

$('some id or class that you add to the above a tag').popover({
    trigger: "hover" 
})

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

I believe python arrays just admit values. So convert it to list:

kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()

How do I install Composer on a shared hosting?

This tutorial worked for me, resolving my issues with /usr/local/bin permission issues and php-cli (which composer requires, and may aliased differently on shared hosting).

First run these commands to download and install composer:

cd ~
mkdir bin
mkdir bin/composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar bin/composer

Determine the location of your php-cli (needed later on):

which php-cli

(If the above fails, use which php)

It should return the path, such as /usr/bin/php-cli, /usr/php/54/usr/bin/php-cli, etc.

edit ~/.bashrc and make sure this line is at the top, adding it if it is not:

[ -z "$PS1" ] && return

and then add this alias to the bottom (using the php-cli path that you determined earlier):

alias composer="/usr/bin/php-cli ~/bin/composer/composer.phar"

Finish with these commands:

source ~/.bashrc
composer --version

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

Download a specific tag with Git

I'm not a git expert, but I think this should work:

git clone http://git.abc.net/git/abc.git
cd abc
git checkout my_abc 

OR

git clone http://git.abc.net/git/abc.git
cd abc
git checkout -b new_branch my_abc

The second variation establishes a new branch based on the tag, which lets you avoid a 'detached HEAD'. (git-checkout manual)

Every git repo contains the entire revision history, so cloning the repo gives you access to the latest commit, plus everything that came before, including the tag you're looking for.

Oracle ORA-12154: TNS: Could not resolve service name Error?

Going on the assumption you're using TNSNAMES naming, here's a couple of things to do:

  • Create/modify the tnsnames.ora file in the network/admin subdirectory associated with OraHome90 to include an entry for your oracle database:
> SERVICENAME_alias =
>    (DESCRIPTION =
>     (ADDRESS = (PROTOCOL = TCP)(HOST = HOST.XYZi.com)(PORT = 1521))
>     (CONNECT_DATA = (SERVICE_NAME = SERVICENAME))

This is assuming you're using the standard Oracle port of 1521. Note that servicename_alias can be any name you want to use on the local system. You may also find that you need to specify (SID = SERVICENAME) instead of (SERVICENAME=SERVICENAME).

  • Execute tnsping servicename_alias to verify connectivity. Get this working before going any further. This will tell you if you're past the 12154 error.
  • Assuming a good connection, create an ODBC DSN using the control panel, specifying the ODBC driver for Oracle of your choice (generally there's a Microsoft ODBC driver at least, and it should work adequately as a proof of concept). I'll assume the name you gave of DATASOURCE. Use the servicename_alias as the Server name in the ODBC configuration.
  • At this point you should be able to connect to your database via Access. I am not a VB programmer, but I know you should be able to go to File->Get External Data->Link Tables and connect to your ODBC source. I would assume your code would work as well.

Can you delete multiple branches in one command with Git?

You can use git gui to delete multiple branches at once. From Command Prompt/Bash -> git gui -> Remote -> Delete branch ... -> select remote branches you want to remove -> Delete.

How to collapse blocks of code in Eclipse?

If you want folding an all your editors, I found you can enable Folding in

Preferences > Editors > Structured Text Editors

Enable Folding

Error 0x80005000 and DirectoryServices

The same error occurs if in DirectoryEntry.Patch is nothing after the symbols "LDAP//:". It is necessary to check the directoryEntry.Path before directorySearcher.FindOne(). Unless explicitly specified domain, and do not need to "LDAP://".

private void GetUser(string userName, string domainName)
{
     DirectoryEntry dirEntry = new DirectoryEntry();

     if (domainName.Length > 0)
     {
          dirEntry.Path = "LDAP://" + domainName;
     }

     DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
     dirSearcher.SearchScope = SearchScope.Subtree;
     dirSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(sn={0}*)(givenName={0})(sAMAccountName={0}*)))", userName);
     var searchResults = dirSearcher.FindAll();
     //var searchResults = dirSearcher.FindOne();

     if (searchResults.Count == 0)
     {
          MessageBox.Show("User not found");
     }
     else
     {
          foreach (SearchResult sr in searchResults)
          {
              var de = sr.GetDirectoryEntry();
              string user = de.Properties["SAMAccountName"][0].ToString();
              MessageBox.Show(user); 
          }        
     }
}

How can I put CSS and HTML code in the same file?

Or also you can do something like this.

<div style="background=#aeaeae; float: right">

</div>

We can add any CSS inside the style attribute of HTML tags.

Python: Find in list

Instead of using list.index(x) which returns the index of x if it is found in list or returns a #ValueError message if x is not found, you could use list.count(x) which returns the number of occurrences of x in list (validation that x is indeed in the list) or it returns 0 otherwise (in the absence of x). The cool thing about count() is that it doesn't break your code or require you to throw an exception for when x is not found

undefined reference to 'std::cout'

Assuming code.cpp is the source code, the following will not throw errors:

make code
./code

Here the first command compiles the code and creates an executable with the same name, and the second command runs it. There is no need to specify g++ keyword in this case.

How to automatically redirect HTTP to HTTPS on Apache servers?

Actually, your topic is belongs on https://serverfault.com/ but you can still try to check these .htaccess directives:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1

android.content.Context.getPackageName()' on a null object reference

You only need to do this:

Intent myIntent = new Intent(MainActivity.this, nextActivity.class);

Sum of values in an array using jQuery

    var arr = ["20.0","40.1","80.2","400.3"],
    sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0; });

Worked perfectly for what i needed. Thanks vol7ron

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Spring Boot 2.2.2 / Gradle:

Gradle (build.gradle):

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

Entity (User.class):

LocalDate dateOfBirth;

Code:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);

process.waitFor() never returns

Here is a method that works for me. NOTE: There is some code within this method that may not apply to you, so try and ignore it. For example "logStandardOut(...), git-bash, etc".

private String exeShellCommand(String doCommand, String inDir, boolean ignoreErrors) {
logStandardOut("> %s", doCommand);

ProcessBuilder builder = new ProcessBuilder();
StringBuilder stdOut = new StringBuilder();
StringBuilder stdErr = new StringBuilder();

boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
if (isWindows) {
  String gitBashPathForWindows = "C:\\Program Files\\Git\\bin\\bash";
  builder.command(gitBashPathForWindows, "-c", doCommand);
} else {
  builder.command("bash", "-c", doCommand);
}

//Do we need to change dirs?
if (inDir != null) {
  builder.directory(new File(inDir));
}

//Execute it
Process process = null;
BufferedReader brStdOut;
BufferedReader brStdErr;
try {
  //Start the command line process
  process = builder.start();

  //This hangs on a large file
  // https://stackoverflow.com/questions/5483830/process-waitfor-never-returns
  //exitCode = process.waitFor();

  //This will have both StdIn and StdErr
  brStdOut = new BufferedReader(new InputStreamReader(process.getInputStream()));
  brStdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

  //Get the process output
  String line = null;
  String newLineCharacter = System.getProperty("line.separator");

  while (process.isAlive()) {
    //Read the stdOut
    while ((line = brStdOut.readLine()) != null) {
      stdOut.append(line + newLineCharacter);
    }

    //Read the stdErr
    while ((line = brStdErr.readLine()) != null) {
      stdErr.append(line + newLineCharacter);
    }

    //Nothing else to read, lets pause for a bit before trying again
    process.waitFor(100, TimeUnit.MILLISECONDS);
  }

  //Read anything left, after the process exited
  while ((line = brStdOut.readLine()) != null) {
    stdOut.append(line + newLineCharacter);
  }

  //Read anything left, after the process exited
  while ((line = brStdErr.readLine()) != null) {
    stdErr.append(line + newLineCharacter);
  }

  //cleanup
  if (brStdOut != null) {
    brStdOut.close();
  }

  if (brStdErr != null) {
    brStdOut.close();
  }

  //Log non-zero exit values
  if (!ignoreErrors && process.exitValue() != 0) {
    String exMsg = String.format("%s%nprocess.exitValue=%s", stdErr, process.exitValue());
    throw new ExecuteCommandException(exMsg);
  }

} catch (ExecuteCommandException e) {
  throw e;
} catch (Exception e) {
  throw new ExecuteCommandException(stdErr.toString(), e);
} finally {
  //Log the results
  logStandardOut(stdOut.toString());
  logStandardError(stdErr.toString());
}

return stdOut.toString();

}

jQuery .each() index?

$('#list option').each(function(intIndex){
//do stuff
});

How to run Nginx within a Docker container without halting?

Here you have an example of a Dockerfile that runs nginx. As mentionned by Charles, it uses the daemon off configuration:

https://github.com/darron/docker-nginx-php5/blob/master/Dockerfile#L17

Failed to resolve: com.google.firebase:firebase-core:16.0.1

This is rare, but there is a chance your project's gradle offline mode is enable, disable offline mode with the following steps;

  • In android studio, locate the file tab of the header and click
  • In the drop own menu, select settings
  • In the dialog produced, select "Build, Execution, Deploy" and then select "Gradle"
  • Finally uncheck the "offline work" check box and apply changes

If this doesn't work leave a comment describing your Logcat response and i'll try to help more.

Show diff between commits

  1. gitk --all
  2. Select the first commit
  3. Right click on the other, then diff selected → this

How to sum columns in a dataTable?

I doubt that this is what you want but your question is a little bit vague

Dim totalCount As Int32 = DataTable1.Columns.Count * DataTable1.Rows.Count

If all your columns are numeric-columns you might want this:

You could use DataTable.Compute to Sum all values in the column.

 Dim totalCount As Double
 For Each col As DataColumn In DataTable1.Columns
     totalCount += Double.Parse(DataTable1.Compute(String.Format("SUM({0})", col.ColumnName), Nothing).ToString)
 Next

After you've edited your question and added more informations, this should work:

 Dim totalRow = DataTable1.NewRow
 For Each col As DataColumn In DataTable1.Columns
     totalRow(col.ColumnName) = Double.Parse(DataTable1.Compute("SUM(" & col.ColumnName & ")", Nothing).ToString)
 Next
 DataTable1.Rows.Add(totalRow)

Hidden Features of C#?

This trick for calling private methods using Delegate.CreateDelegate is extremely neat.

var subject = new Subject();
var doSomething = (Func<String, String>)
    Delegate.CreateDelegate(typeof(Func<String, String>), subject, "DoSomething");
Console.WriteLine(doSomething("Hello Freggles"));

Here's a context where it's useful

Get the last three chars from any string - Java

This method would be helpful :

String rightPart(String text,int length)
{
    if (text.length()<length) return text;
    String raw = "";
    for (int i = 1; i <= length; i++) {
        raw += text.toCharArray()[text.length()-i];
    }
    return new StringBuilder(raw).reverse().toString();
}

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

The HTTP_HOST is obtained from the HTTP request header and this is what the client actually used as "target host" of the request. The SERVER_NAME is defined in server config. Which one to use depends on what you need it for. You should now however realize that the one is a client-controlled value which may thus not be reliable for use in business logic and the other is a server-controlled value which is more reliable. You however need to ensure that the webserver in question has the SERVER_NAME correctly configured. Taking Apache HTTPD as an example, here's an extract from its documentation:

If no ServerName is specified, then the server attempts to deduce the hostname by performing a reverse lookup on the IP address. If no port is specified in the ServerName, then the server will use the port from the incoming request. For optimal reliability and predictability, you should specify an explicit hostname and port using the ServerName directive.


Update: after checking the answer of Pekka on your question which contains a link to bobince's answer that PHP would always return HTTP_HOST's value for SERVER_NAME, which goes against my own PHP 4.x + Apache HTTPD 1.2.x experiences from a couple of years ago, I blew some dust from my current XAMPP environment on Windows XP (Apache HTTPD 2.2.1 with PHP 5.2.8), started it, created a PHP page which prints the both values, created a Java test application using URLConnection to modify the Host header and tests taught me that this is indeed (incorrectly) the case.

After first suspecting PHP and digging in some PHP bug reports regarding the subject, I learned that the root of the problem is in web server used, that it incorrectly returned HTTP Host header when SERVER_NAME was requested. So I dug into Apache HTTPD bug reports using various keywords regarding the subject and I finally found a related bug. This behaviour was introduced since around Apache HTTPD 1.3. You need to set UseCanonicalName directive to on in the <VirtualHost> entry of the ServerName in httpd.conf (also check the warning at the bottom of the document!).

<VirtualHost *>
    ServerName example.com
    UseCanonicalName on
</VirtualHost> 

This worked for me.

Summarized, SERVER_NAME is more reliable, but you're dependent on the server config!

$(this).val() not working to get text from span using jquery

Instead of .val() use .text(), like this:

$(".ui-datepicker-month").live("click", function () {
    var monthname =  $(this).text();
    alert(monthname);
});

Or in jQuery 1.7+ use on() as live is deprecated:

$(document).on('click', '.ui-datepicker-month', function () {
    var monthname =  $(this).text();
    alert(monthname);
});

.val() is for input type elements (including textareas and dropdowns), since you're dealing with an element with text content, use .text() here.

How to do case insensitive string comparison?

Since no answer clearly provided a simple code snippet for using RegExp, here's my attempt:

function compareInsensitive(str1, str2){ 
  return typeof str1 === 'string' && 
    typeof str2 === 'string' && 
    new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}

It has several advantages:

  1. Verifies parameter type (any non-string parameter, like undefined for example, would crash an expression like str1.toUpperCase()).
  2. Does not suffer from possible internationalization issues.
  3. Escapes the RegExp string.

Disable form autofill in Chrome without disabling autocomplete

I stumbled upon the weird chrome autofill behaviour today. It happened to enable on fields called: "embed" and "postpassword" (filling there login and password) with no apparent reason. Those fields had already autocomplete set to off.

None of the described methods seemed to work. None of the methods from the another answer worked as well. I came upon my own idea basing on Steele's answer (it might have actually worked, but I require the fixed post data format in my application):

Before the real password, add those two dummy fields:

<input type='text' style='display: none'>
<input type='password' style='display: none'>

Only this one finally disabled autofill altogether for my form.

It's a shame, that disabling such a basic behavior is that hard and hacky.

Is multiplication and division using shift operators in C actually faster?

Short answer: Not likely.

Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.

Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.

open() in Python does not create a file if it doesn't exist

>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

r+ means read/write

How to parse XML using shellscript?

Here's a solution using xml_grep (because xpath wasn't part of our distributable and I didn't want to add it to all production machines)...

If you are looking for a specific setting in an XML file, and if all elements at a given tree level are unique, and there are no attributes, then you can use this handy function:

# File to be parsed
xmlFile="xxxxxxx"

# use xml_grep to find settings in an XML file
# Input ($1): path to setting
function getXmlSetting() {

    # Filter out the element name for parsing
    local element=`echo $1 | sed 's/^.*\///'`

    # Verify the element is not empty
    local check=${element:?getXmlSetting invalid input: $1}

    # Parse out the CDATA from the XML element
    # 1) Find the element (xml_grep)
    # 2) Remove newlines (tr -d \n)
    # 3) Extract CDATA by looking for *element> CDATA <element*
    # 4) Remove leading and trailing spaces
    local getXmlSettingResult=`xml_grep --cond $1 $xmlFile 2>/dev/null | tr -d '\n' | sed -n -e "s/.*$element>[[:space:]]*\([^[:space:]].*[^[:space:]]\)[[:space:]]*<\/$element.*/\1/p"`

    # Return the result
    echo $getXmlSettingResult
}

#EXAMPLE
logPath=`getXmlSetting //config/logs/path`
check=${logPath:?"XML file missing //config/logs/path"}

This will work with this structure:

<config>
  <logs>
     <path>/path/to/logs</path>
  <logs>
</config>

It will also work with this (but it won't keep the newlines):

<config>
  <logs>
     <path>
          /path/to/logs
     </path>
  <logs>
</config>

If you have duplicate <config> or <logs> or <path>, then it will only return the last one. You can probably modify the function to return an array if it finds multiple matches.

FYI: This code works on RedHat 6.3 with GNU BASH 4.1.2, but I don't think I'm doing anything particular to that, so should work everywhere.

NOTE: For anybody new to scripting, make sure you use the right types of quotes, all three are used in this code (normal single quote '=literal, backward single quote `=execute, and double quote "=group).

ActionController::UnknownFormat

Update the create action as below:

def create
  ...
  respond_to do |format|
    if @reservation.save
      format.html do
        redirect_to '/'
      end
      format.json { render json: @reservation.to_json }
    else
      format.html { render 'new'} ## Specify the format in which you are rendering "new" page
      format.json { render json: @reservation.errors } ## You might want to specify a json format as well
    end
  end
end

You are using respond_to method but anot specifying the format in which a new page is rendered. Hence, the error ActionController::UnknownFormat .

INNER JOIN vs INNER JOIN (SELECT . FROM)

You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)

How to Implement DOM Data Binding in JavaScript

Changing an element's value can trigger a DOM event. Listeners that respond to events can be used to implement data binding in JavaScript.

For example:

function bindValues(id1, id2) {
  const e1 = document.getElementById(id1);
  const e2 = document.getElementById(id2);
  e1.addEventListener('input', function(event) {
    e2.value = event.target.value;
  });
  e2.addEventListener('input', function(event) {
    e1.value = event.target.value;
  });
}

Here is code and a demo that shows how DOM elements can be bound with each other or with a JavaScript object.

Is there a vr (vertical rule) in html?

I know I am adding my answer very late, but it would be worth I am sure. You can achieve vertical line using flex and hr

See my codepen here.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

Recursively find all files newer than a given time

You can find every file what is created/modified in the last day, use this example:

find /directory -newermt $(date +%Y-%m-%d -d '1 day ago') -type f -print

for finding everything in the last week, use '1 week ago' or '7 day ago' anything you want

How to get sp_executesql result into a variable?

This worked for me:

DECLARE @SQL NVARCHAR(4000)

DECLARE @tbl Table (
    Id int,
    Account varchar(50),
    Amount int
) 

-- Lots of code to Create my dynamic sql statement

insert into @tbl EXEC sp_executesql @SQL

select * from @tbl

Why is this jQuery click function not working?

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

i.e.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

In testing IE7/8/9 I was getting an ActiveX warning trying to use this code snippet:

filter:progid:DXImageTransform.Microsoft.gradient

After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.

What's the best way to detect a 'touch screen' device using JavaScript?

Extent jQuery support object:

jQuery.support.touch = 'ontouchend' in document;

And now you can check it anywhere, like this:

if( jQuery.support.touch )
   // do touch stuff

Easiest way to copy a table from one database to another?

use below steps to copy and insert some columns from one database table to another database table-

  1. CREATE TABLE tablename ( columnname datatype (size), columnname datatype (size));

2.INSERT INTO db2.tablename SELECT columnname1,columnname2 FROM db1.tablename;

Python Pandas iterate over rows and access column names

I also like itertuples()

for row in df.itertuples():
    print(row.A)
    print(row.Index)

since row is a named tuples, if you meant to access values on each row this should be MUCH faster

speed run :

df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
st=time.time()
for index, row in df.iterrows():
    row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
    row.A
print(time.time() - st)
0.48400020599365234

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

Remove

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency> 

slf4j-log4j12 is the log4j binding for slf4j you dont need to add another log4j dependency.

Added
Provide the log4j configuration in log4j.properties and add it to your class path. There are sample configurations here

or you can change your binding to

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
</dependency>

if you are configuring slf4j due to some dependencies requiring it.

Can I limit the length of an array in JavaScript?

var  arrLength = arr.length;
if(arrLength > maxNumber){
    arr.splice( 0, arrLength - maxNumber);
}

This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

The problem with:

arr.slice(0,5)

...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

The problem with:

if (arr.length > 4) arr.length = 4;

...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

Truncating a table in a stored procedure

try the below code

execute immediate 'truncate table tablename' ;

onclick go full screen

It's possible with JavaScript.

var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
  elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
}

Just get column names from hive table

If you simply want to see the column names this one line should provide it without changing any settings:

describe database.tablename;

However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:

use database;
describe tablename;

module.exports vs exports in Node.js

var a = {},md={};

//Firstly,the exports and module.exports point the same empty Object

exp = a;//exports =a;
md.exp = a;//module.exports = a;

exp.attr = "change";

console.log(md.exp);//{attr:"change"}

//If you point exp to other object instead of point it's property to other object. The md.exp will be empty Object {}

var a ={},md={};
exp =a;
md.exp =a;

exp = function(){ console.log('Do nothing...'); };

console.log(md.exp); //{}

Building executable jar with maven?

If you don't want execute assembly goal on package, you can use next command:

mvn package assembly:single

Here package is keyword.

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

Add st, nd, rd and th (ordinal) suffix to a number

I strongly recommend this, it is super easy and straightforward to read. I hope it help?

  • It avoid the use of negative integer i.e number less than 1 and return false
  • It return 0 if input is 0
function numberToOrdinal(n) {

  let result;

  if(n < 0){
    return false;
  }else if(n === 0){
    result = "0";
  }else if(n > 0){

    let nToString = n.toString();
    let lastStringIndex = nToString.length-1;
    let lastStringElement = nToString[lastStringIndex];

    if( lastStringElement == "1" && n % 100 !== 11 ){
      result = nToString + "st";
    }else if( lastStringElement == "2" && n % 100 !== 12 ){
      result = nToString + "nd";
    }else if( lastStringElement == "3" && n % 100 !== 13 ){
      result = nToString + "rd";
    }else{
      result = nToString + "th";
    }

  }

  return result;
}

console.log(numberToOrdinal(-111));
console.log(numberToOrdinal(0));
console.log(numberToOrdinal(11));
console.log(numberToOrdinal(15));
console.log(numberToOrdinal(21));
console.log(numberToOrdinal(32));
console.log(numberToOrdinal(43));
console.log(numberToOrdinal(70));
console.log(numberToOrdinal(111));
console.log(numberToOrdinal(300));
console.log(numberToOrdinal(101));

OUTPUT

false
0
11th
15th
21st
32nd
43rd
70th
111th
300th
101st

How to convert seconds to HH:mm:ss in moment.js

This is similar to the answer mplungjan referenced from another post, but more concise:

_x000D_
_x000D_
const secs = 456;_x000D_
_x000D_
const formatted = moment.utc(secs*1000).format('HH:mm:ss');_x000D_
_x000D_
document.write(formatted);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

Artisan migrate could not find driver

if you've installed php and mysql in your linux machine, php needs php-mysql extention to communicate with mysql. so make sure you've also installed this extention using:

sudo yum install php-mysql in redhat based machines.

and

sudo apt-get install php-mysql in debian machines.

Call function with setInterval in jQuery?

setInterval(function() {
    updatechat();
}, 2000);

function updatechat() {
    alert('hello world');
}

git remote add with other SSH port

Rather than using the ssh:// protocol prefix, you can continue using the conventional URL form for accessing git over SSH, with one small change. As a reminder, the conventional URL is:

git@host:path/to/repo.git

To specify an alternative port, put brackets around the user@host part, including the port:

[git@host:port]:path/to/repo.git

But if the port change is merely temporary, you can tell git to use a different SSH command instead of changing your repository’s remote URL:

export GIT_SSH_COMMAND='ssh -p port'
git clone git@host:path/to/repo.git # for instance

Display open transactions in MySQL

How can I display these open transactions and commit or cancel them?

There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).

You display threads using

SHOW FULL PROCESSLIST  

See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html

It will not help you, because you cannot commit a transaction from a broken connection.

What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html

4.5.1.6.3. Disabling mysql Auto-Reconnect

If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.

This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:

Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html

How to diagnose and fix this
To check for auto-reconnection:

If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call mysql_thread_id() to get the original connection identifier before calling mysql_ping(), then call mysql_thread_id() again to see whether the identifier has changed.

Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.

Run a single test method with maven

You can run specific test class(es) and method(s) using the following syntax:

  1. full package : mvn test -Dtest="com.oracle.tests.**"

  2. all method in a class : mvn test -Dtest=CLASS_NAME1

  3. single method from single class :mvn test -Dtest=CLASS_NAME1#METHOD_NAME1

  4. multiple method from multiple class : mvn test -Dtest=CLASS_NAME1#METHOD_NAME1,CLASS_NAME2#METHOD_NAME2

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

Note: localhost is the hostname for an address using the local (loopback) network interface, and 127.0.0.1 is its IP in the IPv4 network standard (it's ::1 in IPv6). 0.0.0.0 is the IPv4 standard "current network" IP address.

I experienced this error with a Docker setup. I had a Docker container running on an external server, and I'd (correctly) mapped its ports out as 127.0.0.1:9232:9232. By port-forwarding ssh remote -L 9232:127.0.0.1:9232, I'd expected to be able to communicate with the remote server's port 9232 as if it were my own local port.

It turned out that the Docker container was internally running its process on 127.0.0.1:9232 rather than 0.0.0.0:9232, and so even though I'd specified the container's port-mappings correctly, they weren't on the correct interface for being mapped out.

How to convert .pfx file to keystore with private key?

I found this page which tells you how to import a PFX to JKS (Java Key Store):

keytool -importkeystore -srckeystore PFX_P12_FILE_NAME -srcstoretype pkcs12 -srcstorepass PFX_P12_FILE -srcalias SOURCE_ALIAS -destkeystore KEYSTORE_FILE -deststoretype jks -deststorepass PASSWORD -destalias ALIAS_NAME

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

To stop seeing those cast_sender.js errors, edit the youtube link in the iframe src and change embed to v

C# looping through an array

Here is a more general solution:

int increment = 3;
for(int i = 0; i < theData.Length; i += increment)
{
   for(int j = 0; j < increment; j++)
   {
      if(i+j < theData.Length) {
         //theData[i + j] for the current index
      }
   }

}

Java error: Only a type can be imported. XYZ resolves to a package

I had the same error message and my way to deal with it is as follows:

  1. First go check the file directory where your Tomcat is publishing your web application, e.g. D:\Java\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\myDatatable\WEB-INF\classes, in which we normally put our classes. If this is not the place where you put your classes, then you have to find out where by default it is by right click your web application root name-->Build Path-->Configure Build Bath...-->Then check the "Source" Tab and find out the field value of "Default output folder". This shall be the place where Tomcat put your classes.
  2. You would see that XYZ class is not yet built. In order to build it, you could go to Menu "Project"-->"Clean..."-->Select your web application to clean.
  3. After it's completed, try restart your tomcat server and go check the file directory again. Your class should be there. At least it works for me. Hope it helps.

How to check if element is visible after scrolling?

This method will return true if any part of the element is visible on the page. It worked better in my case and may help someone else.

function isOnScreen(element) {
  var elementOffsetTop = element.offset().top;
  var elementHeight = element.height();

  var screenScrollTop = $(window).scrollTop();
  var screenHeight = $(window).height();

  var scrollIsAboveElement = elementOffsetTop + elementHeight - screenScrollTop >= 0;
  var elementIsVisibleOnScreen = screenScrollTop + screenHeight - elementOffsetTop >= 0;

  return scrollIsAboveElement && elementIsVisibleOnScreen;
}

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

I just had the same problem and the same message. I was able to get it fixed by importing to the Java Building Path the hamcrest-all-1.3.jar archive. I'm using a JUnit 4.12 version.

C++ Object Instantiation

Well, the reason to use the pointer would be exactly the same that the reason to use pointers in C allocated with malloc: if you want your object to live longer than your variable!

It is even highly recommended to NOT use the new operator if you can avoid it. Especially if you use exceptions. In general it is much safer to let the compiler free your objects.

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'

python location on mac osx

On Mac OS X, it's in the Python framework in /System/Library/Frameworks/Python.framework/Resources.

Full path is:

/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python

Btw it's easy to find out where you can find a specific binary: which Python will show you the path of your Python binary (which is probably the same as I posted above).

TypeError: 'undefined' is not a function (evaluating '$(document)')

You can use both jQuery and $ in below snippet. it worked for me

jQuery( document ).ready(function( $ ) {
  // jQuery(document)
  // $(document)
});

How to set an "Accept:" header on Spring RestTemplate request?

I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also specify the HTTP method you want to use.)

For example,

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

HttpEntity<String> entity = new HttpEntity<>("body", headers);

restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

I prefer this solution because it's strongly typed, ie. exchange expects an HttpEntity.

However, you can also pass that HttpEntity as a request argument to postForObject.

HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class); 

This is mentioned in the RestTemplate#postForObject Javadoc.

The request parameter can be a HttpEntity in order to add additional HTTP headers to the request.

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

Regular Expression to match string starting with a specific word

If you wish to match only lines beginning with stop use

^stop

If you wish to match lines beginning with the word stop followed by a space

^stop\s

Or, if you wish to match lines beginning with the word stop but followed by either a space or any other non word character you can use (your regex flavor permitting)

^stop\W

On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)

^\w

If your flavor does not have the \w shortcut, you can use

^[a-zA-Z0-9]+

Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.

Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode.)

How can I conditionally import an ES6 module?

2020 Update

You can now call the import keyword as a function (i.e. import()) to load a module at runtime.

Example:

const mymodule = await import(modulename);

or:

import(modulename)
    .then(mymodule => /* ... */);

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports

Simple URL GET/POST function in Python

I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)

#!/usr/bin/env python3
import http.client
import json

print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)


print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)


print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)


print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

another alternative, just in case you want to have a shell script which creates the database if it does not exist and otherwise just keeps it as it is:

psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'my_db'" | grep -q 1 || psql -U postgres -c "CREATE DATABASE my_db"

I found this to be helpful in devops provisioning scripts, which you might want to run multiple times over the same instance.

For those of you who would like an explanation:

-c = run command in database session, command is given in string
-t = skip header and footer
-q = silent mode for grep 
|| = logical OR, if grep fails to find match run the subsequent command

How to reference Microsoft.Office.Interop.Excel dll?

You can also try installing it in Visual Studio via Package Manager.

Run Install-Package Microsoft.Office.Interop.Excel in the Package Console. This will automatically add it as a project reference.

Use is like this:

Using Excel=Microsoft.Office.Interop.Excel;

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Just another way of doing it.

[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]

echo key and value of an array without and with loop

Without a loop, just for the kicks of it...


You can either convert the array to a non-associative one, by doing:

$page = array_values($page);

And then acessing each element by it's zero-based index:

echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'

Or you can use a slightly more complicated version:

$value = array_slice($page, 0, 1);

echo key($value); // Home
echo current($value); // index.html

$value = array_slice($page, 1, 1);

echo key($value); // Service
echo current($value); // services.html

mean() warning: argument is not numeric or logical: returning NA

The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean() function. Therefore, check your data using str(data.frame&column) function to see what data type you have, and convert it to numeric format if necessary. For example, if your data is Character convert it with as.numeric(data.frame$column), or as a factor with as.numeric(as.character(data.frame$column)). The mean function does not work with types other than numeric.

How to change the application launcher icon on Flutter?

Setting the launcher icons like a native developer

I was having some trouble using and understanding the flutter_launcher_icons package. This answer is how you would do it if you were creating an app for Android or iOS natively. It is pretty fast and easy once you have done it a few times.

Android

Android launcher icons have both a foreground and a background layer.

enter image description here

(image adapted from Android documentation)

The easiest way to create launcher icons for Android is to use the Asset Studio that is available right in Android Studio. You don't even have to leave your Flutter project. (VS Code users, you might consider using Android Studio just for this step. It's really very convenient and it doesn't hurt to be familiar with another IDE.)

Right click on the android folder in the project outline. Go to New > Image Asset. (Try right clicking the android/app folder if you don't see Image Asset as an option. Also see the comments below for more suggestions.) Now you can select an image to create your launcher icon from.

Note: I usually use a 1024x1024 pixel image but you should certainly use nothing smaller that 512x512. If you are using Gimp or Inkscape, you should have two layers, one for the foreground and one for the background. The foreground image should have transparent areas for the background layer to show through.

enter image description here

(lion clipart from here)

This will replace the current launcher icons. You can find the generated icons in the mipmap folders:

If you would prefer to create the launcher icons manually, see this answer for help.

Finally, make sure that the launcher icon name in the AndroidManifest is the same as what you called it above (ic_launcher by default):

application android:icon="@mipmap/ic_launcher"

Run the app in the emulator to confirm that the launcher icon was created successfully.

iOS

I always used to individually resize my iOS icons by hand, but if you have a Mac, there is a free app in the Mac App Store called Icon Set Creator. You give it an image (of at least 1024x1024 pixels) and it will spit out all the sizes that you need (plus the Contents.json file). Thanks to this answer for the suggestion.

iOS icons should not have any transparency. See more guidelines here.

After you have created the icon set, start Xcode (assuming you have a Mac) and use it to open the ios folder in your Flutter project. Then go to Runner > Assets.xcassets and delete the AppIcon item.

enter image description here

After that right-click and choose Import.... Choose the icon set that you just created.

That's it. Confirm that the icon was created by running the app in the simulator.

If you don't have a Mac...

You can still create all of the images by hand. In your Flutter project go to ios/Runner/Assets.xcassets/AppIcon.appiconset.

The image sizes that you need are the multiplied sizes in the filename. For example, [email protected] would be 29 times 3, that is, 87 pixels square. You either need to keep the same icon names or edit the JSON file.

How to subtract X days from a date using Java calendar?

Someone recommended Joda Time so - I have been using this CalendarDate class http://calendardate.sourceforge.net

It's a somewhat competing project to Joda Time, but much more basic at only 2 classes. It's very handy and worked great for what I needed since I didn't want to use a package bigger than my project. Unlike the Java counterparts, its smallest unit is the day so it is really a date (not having it down to milliseconds or something). Once you create the date, all you do to subtract is something like myDay.addDays(-5) to go back 5 days. You can use it to find the day of the week and things like that. Another example:

CalendarDate someDay = new CalendarDate(2011, 10, 27);
CalendarDate someLaterDay = today.addDays(77);

And:

//print 4 previous days of the week and today
String dayLabel = "";
CalendarDate today = new CalendarDate(TimeZone.getDefault());
CalendarDateFormat cdf = new CalendarDateFormat("EEE");//day of the week like "Mon"
CalendarDate currDay = today.addDays(-4);
while(!currDay.isAfter(today)) {
    dayLabel = cdf.format(currDay);
    if (currDay.equals(today))
        dayLabel = "Today";//print "Today" instead of the weekday name
    System.out.println(dayLabel);
    currDay = currDay.addDays(1);//go to next day
}

YouTube iframe embed - full screen

Noticed mine worked on chrome. Got it to work in Firefox by going to <about:config> and setting full-screen-api.allow-trusted-requests-only to false.

After full screen worked once, I could set that back to true, and full screen still worked which was quite perplexing.

Getting the location from an IP address

I wrote a bot using an API from ipapi.co, here's how you can get location for an IP address (e.g. 1.2.3.4) in php :

Set header :

$opts = array('http'=>array('method'=>"GET", 'header'=>"User-Agent: mybot.v0.7.1"));
$context = stream_context_create($opts);

Get JSON response

echo file_get_contents('https://ipapi.co/1.2.3.4/json/', false, $context);

of get a specific field (country, timezone etc.)

echo file_get_contents('https://ipapi.co/1.2.3.4/country/', false, $context);

mysqli_real_connect(): (HY000/2002): No such file or directory

I had the same problem. In my /etc/mysql/my.cnf was no path more to mysqld.sock defined. So I started a search to find it with: find / -type s | grep mysqld.sock but it could not be found. I reinstalled mysql with: apt install mysql-server-5.7 (please check before execute the current sql-server-version).

This solved my problem.

NoSql vs Relational database

From mongodb.com:

NoSQL databases differ from older, relational technology in four main areas:

Data models: A NoSQL database lets you build an application without having to define the schema first unlike relational databases which make you define your schema before you can add any data to the system. No predefined schema makes NoSQL databases much easier to update as your data and requirements change.

Data structure: Relational databases were built in an era where data was fairly structured and clearly defined by their relationships. NoSQL databases are designed to handle unstructured data (e.g., texts, social media posts, video, email) which makes up much of the data that exists today.

Scaling: It’s much cheaper to scale a NoSQL database than a relational database because you can add capacity by scaling out over cheap, commodity servers. Relational databases, on the other hand, require a single server to host your entire database. To scale, you need to buy a bigger, more expensive server.

Development model: NoSQL databases are open source whereas relational databases typically are closed source with licensing fees baked into the use of their software. With NoSQL, you can get started on a project without any heavy investments in software fees upfront.

Difference between fprintf, printf and sprintf?

In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The FILE type contains information about the stream. Normally, you don't mess with a FILE object's contents directly, you just pass a pointer to it to the various I/O routines.

There are three standard streams: stdin is a pointer to the standard input stream, stdout is a pointer to the standard output stream, and stderr is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:

$ myprog < inputfile.dat > output.txt 2> errors.txt

In this example, stdin now points to inputfile.dat, stdout points to output.txt, and stderr points to errors.txt.

fprintf writes formatted text to the output stream you specify.

printf is equivalent to writing fprintf(stdout, ...) and writes formatted text to wherever the standard output stream is currently pointing.

sprintf writes formatted text to an array of char, as opposed to a stream.

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

It is defenetly not a appropriate answer, but it is a small hint.

If you want to make use of static files in your App. You should put them as resources or as assets. But, if U have memory concerns like to keep your APK small, then you need to change your App design in such a way that,

instead of putting them as resources, while running your App(after installation) you can take the files(defenately different files as user may not keep files what you need) from SD Card. For this U can use ContentResolver to take audio, Image files on user selection.

With this you can give the user another feature like he can load audio/image files to the app on his own choice.

Remove border radius from Select tag in bootstrap 3

I had the same issue and while user1732055's answer fixes the border, it removes the dropdown arrows. I solved this by removing the border from the select element and creating a wrapper span which has a border.

html:

<span class="select-wrapper">
    <select class="form-control no-radius">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
</span>

css:

select.no-radius{
    border:none;
}    
.select-wrapper{
    border: 1px solid black;
    border-radius: 0px;
}

https://jsfiddle.net/Lrqh0drd/6/

Display Parameter(Multi-value) in Report

I didn't know about the join function - Nice! I had written a function that I placed in the code section (report properties->code tab:

Public Function ShowParmValues(ByVal parm as Parameter) as string
   Dim s as String 

      For i as integer = 0 to parm.Count-1
         s &= CStr(parm.value(i)) & IIF( i < parm.Count-1, ", ","")
      Next
  Return s
End Function  

ORA-00060: deadlock detected while waiting for resource

You can get deadlocks on more than just row locks, e.g. see this. The scripts may be competing for other resources, such as index blocks.

I've gotten around this in the past by engineering the parallelism in such a way that different instances are working on portions of the workload that are less likely to affect blocks that are close to each other; for example, for an update of a large table, instead of setting up the parallel slaves using something like MOD(n,10), I'd use TRUNC(n/10) which mean that each slave worked on a contiguous set of data.

There are, of course, much better ways of splitting up a job for parallelism, e.g. DBMS_PARALLEL_EXECUTE.

Not sure why you're getting "PL/SQL successfully completed", perhaps your scripts are handling the exception?

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

Float a div in top right corner without overlapping sibling header

This worked for me:

h1 {
    display: inline;
    overflow: hidden;
}
div {
    position: relative;
    float: right;
}

It's similar to the approach of the media object, by Stubbornella.

Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)

How to solve javax.net.ssl.SSLHandshakeException Error?

First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, using OpenSSL to download it, or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)

Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At $JAVA_HOME/jre/lib/security/ for JREs or $JAVA_HOME/lib/security for JDKs, there's a file named cacerts, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:

keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>

It will most likely ask you for a password. The default password as shipped with Java is changeit. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key).

How to generate gcc debug symbol outside the build target?

NOTE: Programs compiled with high-optimization levels (-O3, -O4) cannot generate many debugging symbols for optimized variables, in-lined functions and unrolled loops, regardless of the symbols being embedded (-g) or extracted (objcopy) into a '.debug' file.

Alternate approaches are

  1. Embed the versioning (VCS, git, svn) data into the program, for compiler optimized executables (-O3, -O4).
  2. Build a 2nd non-optimized version of the executable.

The first option provides a means to rebuild the production code with full debugging and symbols at a later date. Being able to re-build the original production code with no optimizations is a tremendous help for debugging. (NOTE: This assumes testing was done with the optimized version of the program).

Your build system can create a .c file loaded with the compile date, commit, and other VCS details. Here is a 'make + git' example:

program: program.o version.o 

program.o: program.cpp program.h 

build_version.o: build_version.c    

build_version.c: 
    @echo "const char *build1=\"VCS: Commit: $(shell git log -1 --pretty=%H)\";" > "$@"
    @echo "const char *build2=\"VCS: Date: $(shell git log -1 --pretty=%cd)\";" >> "$@"
    @echo "const char *build3=\"VCS: Author: $(shell git log -1 --pretty="%an %ae")\";" >> "$@"
    @echo "const char *build4=\"VCS: Branch: $(shell git symbolic-ref HEAD)\";" >> "$@"
    # TODO: Add compiler options and other build details

.TEMPORARY: build_version.c

After the program is compiled you can locate the original 'commit' for your code by using the command: strings -a my_program | grep VCS

VCS: PROGRAM_NAME=my_program
VCS: Commit=190aa9cace3b12e2b58b692f068d4f5cf22b0145
VCS: BRANCH=refs/heads/PRJ123_feature_desc
VCS: AUTHOR=Joe Developer  [email protected]
VCS: COMMIT_DATE=2013-12-19

All that is left is to check-out the original code, re-compile without optimizations, and start debugging.

Load HTML file into WebView

The easiest way would probably be to put your web resources into the assets folder then call:

webView.loadUrl("file:///android_asset/filename.html");

For Complete Communication between Java and Webview See This

Update: The assets folder is usually the following folder: <project>/src/main/assets This can be changed in the asset folder configuration setting in your <app>.iml file as:

<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” /> See Article Where to place the assets folder in Android Studio

What does the "map" method do in Ruby?

map, along with select and each is one of Ruby's workhorses in my code.

It allows you to run an operation on each of your array's objects and return them all in the same place. An example would be to increment an array of numbers by one:

[1,2,3].map {|x| x + 1 }
#=> [2,3,4]

If you can run a single method on your array's elements you can do it in a shorthand-style like so:

  1. To do this with the above example you'd have to do something like this

    class Numeric
      def plusone
        self + 1
      end
    end
    [1,2,3].map(&:plusone)
    #=> [2,3,4]
    
  2. To more simply use the ampersand shortcut technique, let's use a different example:

    ["vanessa", "david", "thomas"].map(&:upcase)
    #=> ["VANESSA", "DAVID", "THOMAS"]
    

Transforming data in Ruby often involves a cascade of map operations. Study map & select, they are some of the most useful Ruby methods in the primary library. They're just as important as each.

(map is also an alias for collect. Use whatever works best for you conceptually.)

More helpful information:

If the Enumerable object you're running each or map on contains a set of Enumerable elements (hashes, arrays), you can declare each of those elements inside your block pipes like so:

[["audi", "black", 2008], ["bmw", "red", 2014]].each do |make, color, year|
  puts "make: #{make}, color: #{color}, year: #{year}"
end
# Output:
# make: audi, color: black, year: 2008
# make: bmw, color: red, year: 2014

In the case of a Hash (also an Enumerable object, a Hash is simply an array of tuples with special instructions for the interpreter). The first "pipe parameter" is the key, the second is the value.

{:make => "audi", :color => "black", :year => 2008}.each do |k,v|
    puts "#{k} is #{v}"
end
#make is audi
#color is black
#year is 2008

To answer the actual question:

Assuming that params is a hash, this would be the best way to map through it: Use two block parameters instead of one to capture the key & value pair for each interpreted tuple in the hash.

params = {"one" => 1, "two" => 2, "three" => 3}
params.each do |k,v|
  puts "#{k}=#{v}"
end
# one=1
# two=2
# three=3

Delete all rows in table

Truncate table is faster than delete * from XXX. Delete is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.

Checking for empty or null List<string>

Try and use:

if(myList.Any())
{

}

Note: this assmumes myList is not null.

What is the best IDE to develop Android apps in?

If you do android native code development using NDK, give Visual Studio a try. (Not a typo!!!) Check out: http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html

and: http://code.google.com/p/vs-android/

Difference between agile and iterative and incremental development

Some important and successfully executed software projects like Google Chrome and Mozilla Firefox are fine examples of both iterative and incremental software development.

I will quote fine ars technica article which describes this approach: http://arstechnica.com/information-technology/2010/07/chrome-team-sets-six-week-cadence-for-new-major-versions/

According to Chrome program manager Anthony Laforge, the increased pace is designed to address three main goals. One is to get new features out to users faster. The second is make the release schedule predictable and therefore easier to plan which features will be included and which features will be targeted for later releases. Third, and most counterintuitive, is to cut the level of stress for Chrome developers. Laforge explains that the shorter, predictable time periods between releases are more like "trains leaving Grand Central Station." New features that are ready don't have to wait for others that are taking longer to complete—they can just hop on the current release "train." This can in turn take the pressure off developers to rush to get other features done, since another release train will be coming in six weeks. And they can rest easy knowing their work isn't holding the train from leaving the station.<<

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I did something really stupid (and maybe you did too).

I was trying to call System.Web.Mvc.Html.Partial("<Partial Page>")

System.Web.Mvc.Html is a namespace and not a class and I didn't read my error message so well, so I interpreted my error as the class Html does not exist in the namespace System.Web.Mvc and that's how I ended up here (stupid I know).

All I needed to do was add a using statement @using System.Web.Mvc.Html to my page and then @Html.Partial worked as expected.

What is the '.well' equivalent class in Bootstrap 4

This worked best for me:

<div class="card bg-light p-3">
 <p class="mb-0">Some text here</p>
</div>

How to position a CSS triangle using ::after?

You can set triangle with position see this code for reference

.top-left-corner {
    width: 0px;
    height: 0px;
    border-top: 0px solid transparent;
    border-bottom: 55px solid transparent;
    border-left: 55px solid #289006;
    position: absolute;
    left: 0px;
    top: 0px;
}

How do I overload the [] operator in C#

I believe this is what you are looking for:

Indexers (C# Programming Guide)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get => arr[i];
        set => arr[i] = value;
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

Excel VBA date formats

Format converts the values to strings. IsDate still returns true because it can parse that string and get a valid date.

If you don't want to change the cells to string, don't use Format. (IOW, don't convert them to strings in the first place.) Use the Cell.NumberFormat, and set it to the date format you want displayed.

ActiveCell.NumberFormat = "mm/dd/yy"   ' Outputs 10/28/13
ActiveCell.NumberFormat = "dd/mm/yyyy" ' Outputs 28/10/2013

Can I get Unix's pthread.h to compile in Windows?

pthread.h isn't on Windows. But Windows has extensive threading functionality, beginning with CreateThread.

My advice is don't get caught looking at WinAPI through the lens of another system's API. These systems are different. It's like insisting on riding the Win32 bike with your comfortable Linux bike seat. Well, the seat might not fit right and in some cases it'll just fall off.

Threads pretty much work the same on different systems, you have ThreadPools and mutexes. Having worked with both pthreads and Windows threads, I can say the Windows threading offers quite a bit more functionality than pthread does.

Learning another API is pretty easy, just think in terms of the concepts (mutex, etc), then look up how to create one of those on MSDN.

How to use SSH to run a local shell script on a remote machine?

You can use runoverssh:

sudo apt install runoverssh
runoverssh -s localscript.sh user host1 host2 host3...

-s runs a local script remotely


Useful flags:
-g use a global password for all hosts (single password prompt)
-n use SSH instead of sshpass, useful for public-key authentication

Regular expression to match a dot

A . in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so \.

Travel/Hotel API's?

In my search for hotel APIs I have found only one API giving unrestricted open access to their hotel database and allowing you to book their hotels:

Expedia's EAN http://developer.ean.com/

You need to sign for their affiliate program, which is very easy. You get immediate access to their hotel databases plus you can make availability/booking requests with several response options, including JSON, which is more convenient and lightweight than the (unfortunately) more widespread XML.

As you immediately access their API, you can start developing and testing, but still need their approval to launch the site, basically to make sure it provides the needed quality and security, which is reasonable.

They also offer "deep linking", i.e. you may customize your requests by adding parameters. Then if it sufficient for your purpose (for mine it is not), you don't even need to store their content on your server.


I have also signed for HotelsCombined program: (link removed as this site doesn't seem to let me put more links)

However, they do not immediately allow you to use their API even for testing. From their answer:

"Apologies for the inconvenience caused, but it’s simply a business decision to limit access to our rich hotel content. Please kindly check back within the next 2-3 months, where we will be able to judge your traffic, and in turn judge your status on standard data feeds."


I have also signed for Booking.com affiliate program: (link removed as this site doesn't seem to let me put more links)

Unfortunately, again, they limit access, from their answer: "Please do note that, since there's a high amount of time and cost involved in the XML integration, we are only able to offer the XML integration to a small amount of partners with a high potential."


I did not explore Tripadvisor as they seem only to offer top 10 hotels and only as widgets, but most importantly for me, they wouldn't allow booking through them.

I've checked the hotelbase.org mentioned above, they have very extensive list but not as rich as by Expedia, also they don't seem to have images and don't allow booking either.

Fastest way to convert string to integer in PHP

You can simply convert long string into integer by using FLOAT

$float = (float)$num;

Or if you want integer not floating val then go with

$float = (int)$num;

For ex.

(int)   "1212.3"   = 1212 
(float) "1212.3"   = 1212.3

Split string into array of character strings

An efficient way of turning a String into an array of one-character Strings would be to do this:

String[] res = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
    res[i] = Character.toString(str.charAt(i));
}

However, this does not take account of the fact that a char in a String could actually represent half of a Unicode code-point. (If the code-point is not in the BMP.) To deal with that you need to iterate through the code points ... which is more complicated.

This approach will be faster than using String.split(/* clever regex*/), and it will probably be faster than using Java 8+ streams. It is probable faster than this:

String[] res = new String[str.length()];
int 0 = 0;
for (char ch: str.toCharArray[]) {
    res[i++] = Character.toString(ch);
}  

because toCharArray has to copy the characters to a new array.

In a unix shell, how to get yesterday's date into a variable?

ksh93:

dt=${ printf "%(%a %d/%m/%Y)T" yesterday; }

or:

dt=$(printf "%(%a %d/%m/%Y)T" yesterday)

The first one runs in the same process, the second one in a subshell.

UTF-8 problems while reading CSV file with fgetcsv

Try this:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>

C# "as" cast vs classic cast

I suppose it is useful if the result of the cast will be passed to a method that you know will handle null references without throwing and ArgumentNullException or suchlike.

I tend to find very little use for as, since:

obj as T

Is slower than:

if (obj is T)
    ...(T)obj...

The use of as is very much an edge-case scenario for me, so I can't think of any general rules for when I would use it over just casting and handling the (more informative) casting exception further up the stack.

How to parse JSON in Scala using standard Scala classes?

You can do like this! Very easy to parse JSON code :P

package org.sqkb.service.common.bean

import java.text.SimpleDateFormat

import org.json4s
import org.json4s.JValue
import org.json4s.jackson.JsonMethods._
//import org.sqkb.service.common.kit.{IsvCode}

import scala.util.Try

/**
  *
  */
case class Order(log: String) {

  implicit lazy val formats = org.json4s.DefaultFormats

  lazy val json: json4s.JValue = parse(log)

  lazy val create_time: String = (json \ "create_time").extractOrElse("1970-01-01 00:00:00")
  lazy val site_id: String = (json \ "site_id").extractOrElse("")
  lazy val alipay_total_price: Double = (json \ "alipay_total_price").extractOpt[String].filter(_.nonEmpty).getOrElse("0").toDouble
  lazy val gmv: Double = alipay_total_price
  lazy val pub_share_pre_fee: Double = (json \ "pub_share_pre_fee").extractOpt[String].filter(_.nonEmpty).getOrElse("0").toDouble
  lazy val profit: Double = pub_share_pre_fee

  lazy val trade_id: String = (json \ "trade_id").extractOrElse("")
  lazy val unid: Long = Try((json \ "unid").extractOpt[String].filter(_.nonEmpty).get.toLong).getOrElse(0L)
  lazy val cate_id1: Int = (json \ "cate_id").extractOrElse(0)
  lazy val cate_id2: Int = (json \ "subcate_id").extractOrElse(0)
  lazy val cate_id3: Int = (json \ "cate_id3").extractOrElse(0)
  lazy val cate_id4: Int = (json \ "cate_id4").extractOrElse(0)
  lazy val coupon_id: Long = (json \ "coupon_id").extractOrElse(0)

  lazy val platform: Option[String] = Order.siteMap.get(site_id)


  def time_fmt(fmt: String = "yyyy-MM-dd HH:mm:ss"): String = {
    val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val date = dateFormat.parse(this.create_time)
    new SimpleDateFormat(fmt).format(date)
  }

}

Bind a function to Twitter Bootstrap Modal Close

if you want to fire a function on every modal close, you can use this method,

$(document).ready(function (){
    $('.modal').each(function (){
        $(this).on('hidden.bs.modal', function () {
            //fires when evey popup close. Ex. resetModal();
        });
    });
});

So you don't need to specify modal ids every time.

Java Object Null Check for method

You can add a guard condition to the method to ensure books is not null and then check for null when iterating the array:

public static double calculateInventoryTotal(Book[] books)
{
    if(books == null){
        throw new IllegalArgumentException("Books cannot be null");
    }

    double total = 0;

    for (int i = 0; i < books.length; i++)
    {
        if(books[i] != null){
            total += books[i].getPrice();
        }
    }

    return total;
}

Unable to merge dex

android {
    defaultConfig {
        ...
        minSdkVersion 15 
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

Get element of JS object with an index

Object.keys(city)[0];   //return the key name at index 0
Object.values(city)[0]  //return the key values at index 0

Difference between clean, gradlew clean

You can also use

./gradlew clean build (Mac and Linux) -With ./

gradlew clean build (Windows) -Without ./

it removes build folder, as well configure your modules and then build your project.

i use it before release any new app on playstore.

AddTransient, AddScoped and AddSingleton Services Differences

TL;DR

Transient objects are always different; a new instance is provided to every controller and every service.

Scoped objects are the same within a request, but different across different requests.

Singleton objects are the same for every object and every request.

For more clarification, this example from .NET documentation shows the difference:

To demonstrate the difference between these lifetime and registration options, consider a simple interface that represents one or more tasks as an operation with a unique identifier, OperationId. Depending on how we configure the lifetime for this service, the container will provide either the same or different instances of the service to the requesting class. To make it clear which lifetime is being requested, we will create one type per lifetime option:

using System;

namespace DependencyInjectionSample.Interfaces
{
    public interface IOperation
    {
        Guid OperationId { get; }
    }

    public interface IOperationTransient : IOperation
    {
    }

    public interface IOperationScoped : IOperation
    {
    }

    public interface IOperationSingleton : IOperation
    {
    }

    public interface IOperationSingletonInstance : IOperation
    {
    }
}

We implement these interfaces using a single class, Operation, that accepts a GUID in its constructor, or uses a new GUID if none is provided:

using System;
using DependencyInjectionSample.Interfaces;
namespace DependencyInjectionSample.Classes
{
    public class Operation : IOperationTransient, IOperationScoped, IOperationSingleton, IOperationSingletonInstance
    {
        Guid _guid;
        public Operation() : this(Guid.NewGuid())
        {

        }

        public Operation(Guid guid)
        {
            _guid = guid;
        }

        public Guid OperationId => _guid;
    }
}

Next, in ConfigureServices, each type is added to the container according to its named lifetime:

services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();

Note that the IOperationSingletonInstance service is using a specific instance with a known ID of Guid.Empty, so it will be clear when this type is in use. We have also registered an OperationService that depends on each of the other Operation types, so that it will be clear within a request whether this service is getting the same instance as the controller, or a new one, for each operation type. All this service does is expose its dependencies as properties, so they can be displayed in the view.

using DependencyInjectionSample.Interfaces;

namespace DependencyInjectionSample.Services
{
    public class OperationService
    {
        public IOperationTransient TransientOperation { get; }
        public IOperationScoped ScopedOperation { get; }
        public IOperationSingleton SingletonOperation { get; }
        public IOperationSingletonInstance SingletonInstanceOperation { get; }

        public OperationService(IOperationTransient transientOperation,
            IOperationScoped scopedOperation,
            IOperationSingleton singletonOperation,
            IOperationSingletonInstance instanceOperation)
        {
            TransientOperation = transientOperation;
            ScopedOperation = scopedOperation;
            SingletonOperation = singletonOperation;
            SingletonInstanceOperation = instanceOperation;
        }
    }
}

To demonstrate the object lifetimes within and between separate individual requests to the application, the sample includes an OperationsController that requests each kind of IOperation type as well as an OperationService. The Index action then displays all of the controller’s and service’s OperationId values.

using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;
using Microsoft.AspNetCore.Mvc;

namespace DependencyInjectionSample.Controllers
{
    public class OperationsController : Controller
    {
        private readonly OperationService _operationService;
        private readonly IOperationTransient _transientOperation;
        private readonly IOperationScoped _scopedOperation;
        private readonly IOperationSingleton _singletonOperation;
        private readonly IOperationSingletonInstance _singletonInstanceOperation;

        public OperationsController(OperationService operationService,
            IOperationTransient transientOperation,
            IOperationScoped scopedOperation,
            IOperationSingleton singletonOperation,
            IOperationSingletonInstance singletonInstanceOperation)
        {
            _operationService = operationService;
            _transientOperation = transientOperation;
            _scopedOperation = scopedOperation;
            _singletonOperation = singletonOperation;
            _singletonInstanceOperation = singletonInstanceOperation;
        }

        public IActionResult Index()
        {
            // ViewBag contains controller-requested services
            ViewBag.Transient = _transientOperation;
            ViewBag.Scoped = _scopedOperation;
            ViewBag.Singleton = _singletonOperation;
            ViewBag.SingletonInstance = _singletonInstanceOperation;

            // Operation service has its own requested services
            ViewBag.Service = _operationService;
            return View();
        }
    }
}

Now two separate requests are made to this controller action:

First Request

Second Request

Observe which of the OperationId values varies within a request, and between requests.

  • Transient objects are always different; a new instance is provided to every controller and every service.

  • Scoped objects are the same within a request, but different across different requests

  • Singleton objects are the same for every object and every request (regardless of whether an instance is provided in ConfigureServices)

Multiple controllers with AngularJS in single page app

I'm currently in the process of building a single page application. Here is what I have thus far that I believe would be answering your question. I have a base template (base.html) that has a div with the ng-view directive in it. This directive tells angular where to put the new content in. Note that I'm new to angularjs myself so I by no means am saying this is the best way to do it.

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

app.config(function($routeProvider, $locationProvider) {                        
  $routeProvider                                                                
       .when('/home/', {                                            
         templateUrl: "templates/home.html",                                               
         controller:'homeController',                                
        })                                                                      
        .when('/about/', {                                       
            templateUrl: "templates/about.html",     
            controller: 'aboutController',  
        }) 
        .otherwise({                      
            template: 'does not exists'   
        });      
});

app.controller('homeController', [              
    '$scope',                              
    function homeController($scope,) {        
        $scope.message = 'HOME PAGE';                  
    }                                                
]);                                                  

app.controller('aboutController', [                  
    '$scope',                               
    function aboutController($scope) {        
        $scope.about = 'WE LOVE CODE';                       
    }                                                
]); 

base.html

<html>
<body>

    <div id="sideMenu">
        <!-- MENU CONTENT -->
    </div>

    <div id="content" ng-view="">
        <!-- Angular view would show here -->
    </div>

<body>
</html>

How to access at request attributes in JSP?

Using JSTL:

<c:set var="message" value='${requestScope["Error_Message"]}' />

Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.

<c:out value="${message}"/>

Dart: mapping a list (list.map)

Yes, You can do it this way too

 List<String> listTab = new List();
 map.forEach((key, val) {
  listTab.add(val);
 });

 //your widget//
 bottom: new TabBar(
  controller: _controller,
  isScrollable: true,
  tabs: listTab
  ,
),

Adding iOS UITableView HeaderView (not section header)

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];
    headerView.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
    headerView.layer.borderColor=[UIColor blackColor].CGColor;
    headerView.layer.borderWidth=1.0f;

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,100,20)];

    headerLabel.textAlignment = NSTextAlignmentRight;
    headerLabel.text = @"LeadCode ";
    //headerLabel.textColor=[UIColor whiteColor];
    headerLabel.backgroundColor = [UIColor clearColor];


    [headerView addSubview:headerLabel];

    UILabel *headerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];

    headerLabel1.textAlignment = NSTextAlignmentRight;
    headerLabel1.text = @"LeadName";
    headerLabel.textColor=[UIColor whiteColor];
    headerLabel1.backgroundColor = [UIColor clearColor];

    [headerView addSubview:headerLabel1];

    return headerView;

}

What does it mean when an HTTP request returns status code 0?

If you are testing on local PC, it won't work. To test Ajax example you need to place the HTML files on a web server.

Synchronous XMLHttpRequest warning and <script>

In my case this was caused by the flexie script which was part of the "CDNJS Selections" app offered by Cloudflare.

According to Cloudflare "This app is being deprecated in March 2015". I turned it off and the message disappeared instantly.

You can access the apps by visiting https://www.cloudflare.com/a/cloudflare-apps/yourdomain.com

Convert javascript array to string

Four methods to convert an array to a string.

Coercing to a string

var arr = ['a', 'b', 'c'] + [];  // "a,b,c"

var arr = ['a', 'b', 'c'] + '';  // "a,b,c"

Calling .toString()

var arr = ['a', 'b', 'c'].toString();  // "a,b,c"

Explicitly joining using .join()

var arr = ['a', 'b', 'c'].join();  // "a,b,c" (Defaults to ',' seperator)

var arr = ['a', 'b', 'c'].join(',');  // "a,b,c"

You can use other separators, for example, ', '

var arr = ['a', 'b', 'c'].join(', ');  // "a, b, c"

Using JSON.stringify()

This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.

var arr = JSON.stringify(['a', 'b', 'c']);  // '["a","b","c"]'

Brew doctor says: "Warning: /usr/local/include isn't writable."

This worked for me on macOS 10.12

sudo chown -R $(whoami) /usr/local

I had the problem updating homebrew with the following error:

/usr/local is not writable. You should change the ownership
and permissions of /usr/local back to your user account:
  sudo chown -R $(whoami) /usr/local

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

How to get document height and width without using jquery

If you want to get the full width of the page, including overflow, use document.body.scrollWidth.

Remove legend ggplot 2.2

There might be another solution to this:
Your code was:

geom_point(aes(..., show.legend = FALSE))

You can specify the show.legend parameter after the aes call:

geom_point(aes(...), show.legend = FALSE)

then the corresponding legend should disappear