Programs & Examples On #Ironruby

IronRuby is an open-source implementation of the Ruby programming language which is tightly integrated with the .NET Framework.

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

Quick answer : Add proxy configuration with parameter for both install/update

gem install --http-proxy http://host:port/ package_name

gem update --http-proxy http://host:port/ package_name

How to autosize a textarea using Prototype?

My solution not using jQuery (because sometimes they don't have to be the same thing) is below. Though it was only tested in Internet Explorer 7, so the community can point out all the reasons this is wrong:

textarea.onkeyup = function () { this.style.height = this.scrollHeight + 'px'; }

So far I really like how it's working, and I don't care about other browsers, so I'll probably apply it to all my textareas:

// Make all textareas auto-resize vertically
var textareas = document.getElementsByTagName('textarea');

for (i = 0; i<textareas.length; i++)
{
    // Retain textarea's starting height as its minimum height
    textareas[i].minHeight = textareas[i].offsetHeight;

    textareas[i].onkeyup = function () {
        this.style.height = Math.max(this.scrollHeight, this.minHeight) + 'px';
    }
    textareas[i].onkeyup(); // Trigger once to set initial height
}

How to create Select List for Country and States/province in MVC

So many ways to do this... for #NetCore use Lib..

    using System;
    using System.Collections.Generic;
    using System.Linq; // only required when .AsEnumerable() is used
    using System.ComponentModel.DataAnnotations;
    using Microsoft.AspNetCore.Mvc.Rendering;

Model...

namespace MyProject.Models
{
  public class MyModel
  {
    [Required]
    [Display(Name = "State")]
    public string StatePick { get; set; }
    public string state { get; set; }
    [StringLength(35, ErrorMessage = "State cannot be longer than 35 characters.")]
    public SelectList StateList { get; set; }
  }
}

Controller...

namespace MyProject.Controllers
{
    /// <summary>
    /// create SelectListItem from strings
    /// </summary>
    /// <param name="isValue">defaultValue is SelectListItem.Value is true, SelectListItem.Text if false</param>
    /// <returns></returns>
    private SelectListItem newItem(string value, string text, string defaultValue = "", bool isValue = false)
    {
        SelectListItem ss = new SelectListItem();
        ss.Text = text;
        ss.Value = value;

        // select default by Value or Text
        if (isValue && ss.Value == defaultValue || !isValue && ss.Text == defaultValue)
        {
            ss.Selected = true;
        }

        return ss;
    }

    /// <summary>
    /// this pulls the state name from _context and sets it as the default for the selectList
    /// </summary>
    /// <param name="myState">sets default value for list of states</param>
    /// <returns></returns>
    private SelectList getStateList(string myState = "")
    {
        List<SelectListItem> states = new List<SelectListItem>();
        SelectListItem chosen = new SelectListItem();

        // set default selected state to OHIO
        string defaultValue = "OH";
        if (!string.IsNullOrEmpty(myState))
        {
            defaultValue = myState;
        }

        try
        {
            states.Add(newItem("AL", "Alabama", defaultValue, true));
            states.Add(newItem("AK", "Alaska", defaultValue, true));
            states.Add(newItem("AZ", "Arizona", defaultValue, true));
            states.Add(newItem("AR", "Arkansas", defaultValue, true));
            states.Add(newItem("CA", "California", defaultValue, true));
            states.Add(newItem("CO", "Colorado", defaultValue, true));
            states.Add(newItem("CT", "Connecticut", defaultValue, true));
            states.Add(newItem("DE", "Delaware", defaultValue, true));
            states.Add(newItem("DC", "District of Columbia", defaultValue, true));
            states.Add(newItem("FL", "Florida", defaultValue, true));
            states.Add(newItem("GA", "Georgia", defaultValue, true));
            states.Add(newItem("HI", "Hawaii", defaultValue, true));
            states.Add(newItem("ID", "Idaho", defaultValue, true));
            states.Add(newItem("IL", "Illinois", defaultValue, true));
            states.Add(newItem("IN", "Indiana", defaultValue, true));
            states.Add(newItem("IA", "Iowa", defaultValue, true));
            states.Add(newItem("KS", "Kansas", defaultValue, true));
            states.Add(newItem("KY", "Kentucky", defaultValue, true));
            states.Add(newItem("LA", "Louisiana", defaultValue, true));
            states.Add(newItem("ME", "Maine", defaultValue, true));
            states.Add(newItem("MD", "Maryland", defaultValue, true));
            states.Add(newItem("MA", "Massachusetts", defaultValue, true));
            states.Add(newItem("MI", "Michigan", defaultValue, true));
            states.Add(newItem("MN", "Minnesota", defaultValue, true));
            states.Add(newItem("MS", "Mississippi", defaultValue, true));
            states.Add(newItem("MO", "Missouri", defaultValue, true));
            states.Add(newItem("MT", "Montana", defaultValue, true));
            states.Add(newItem("NE", "Nebraska", defaultValue, true));
            states.Add(newItem("NV", "Nevada", defaultValue, true));
            states.Add(newItem("NH", "New Hampshire", defaultValue, true));
            states.Add(newItem("NJ", "New Jersey", defaultValue, true));
            states.Add(newItem("NM", "New Mexico", defaultValue, true));
            states.Add(newItem("NY", "New York", defaultValue, true));
            states.Add(newItem("NC", "North Carolina", defaultValue, true));
            states.Add(newItem("ND", "North Dakota", defaultValue, true));
            states.Add(newItem("OH", "Ohio", defaultValue, true));
            states.Add(newItem("OK", "Oklahoma", defaultValue, true));
            states.Add(newItem("OR", "Oregon", defaultValue, true));
            states.Add(newItem("PA", "Pennsylvania", defaultValue, true));
            states.Add(newItem("RI", "Rhode Island", defaultValue, true));
            states.Add(newItem("SC", "South Carolina", defaultValue, true));
            states.Add(newItem("SD", "South Dakota", defaultValue, true));
            states.Add(newItem("TN", "Tennessee", defaultValue, true));
            states.Add(newItem("TX", "Texas", defaultValue, true));
            states.Add(newItem("UT", "Utah", defaultValue, true));
            states.Add(newItem("VT", "Vermont", defaultValue, true));
            states.Add(newItem("VA", "Virginia", defaultValue, true));
            states.Add(newItem("WA", "Washington", defaultValue, true));
            states.Add(newItem("WV", "West Virginia", defaultValue, true));
            states.Add(newItem("WI", "Wisconsin", defaultValue, true));
            states.Add(newItem("WY", "Wyoming", defaultValue, true));

            foreach (SelectListItem state in states)
            {
                if (state.Selected)
                {
                    chosen = state;
                    break;
                }
            }
        }
        catch (Exception err)
        {
            string ss = "ERR!   " + err.Source + "   " + err.GetType().ToString() + "\r\n" + err.Message.Replace("\r\n", "   ");
            ss = this.sendError("Online getStateList Request", ss, _errPassword);
            // return error
        }

        // .AsEnumerable() is not required in the pass.. it is an extension of Linq
        SelectList myList = new SelectList(states.AsEnumerable(), "Value", "Text", chosen);

        object val = myList.SelectedValue;

        return myList;
    }

    public ActionResult pickState(MyModel pData)
    {
        if (pData.StateList == null)
        {
            if (String.IsNullOrEmpty(pData.StatePick)) // state abbrev, value collected onchange
            {
                pData.StateList = getStateList();
            }
            else
            {
                pData.StateList = getStateList(pData.StatePick);
            }

            // assign values to state list items
            try
            {
                SelectListItem si = (SelectListItem)pData.StateList.SelectedValue;
                pData.state = si.Value;
                pData.StatePick = si.Value;
            }
            catch { }
        } 
    return View(pData);
    }
}

pickState.cshtml...

@model MyProject.Models.MyModel

@{
ViewBag.Title = "United States of America";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.Title - Where are you...</h2>

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>

    <div class="editor-label">
        @Html.DisplayNameFor(model => model.state)
    </div>
    <div class="display-field">            
        @Html.DropDownListFor(m => m.StatePick, Model.StateList, new { OnChange = "state.value = this.value;" })
        @Html.EditorFor(model => model.state)
        @Html.ValidationMessageFor(model => model.StateList)
    </div>         
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

Convert INT to VARCHAR SQL

SELECT cast(CAST([field_name] AS bigint) as nvarchar(255)) FROM table_name

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Create a BufferedImage from file and make it TYPE_INT_ARGB

BufferedImage in = ImageIO.read(img);

BufferedImage newImage = new BufferedImage(
    in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = newImage.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();

How to use Git for Unity3D source control?

The following is an excerpt from my personal blog .

Using Git with 3D Games

Update Oct 2015: GitHub has since released a plugin for Git called Git LFS that directly deals with the below problem. You can now easily and efficiently version large binary files!

Git can work fine with 3D games out of the box. However the main caveat here is that versioning large (>5 MB) media files can be a problem over the long term as your commit history bloats. We have solved this potential issue in our projects by only versioning the binary asset when it is considered final. Our 3D artists use Dropbox to work on WIP assets, both for the reason above and because it's much faster and simpler (not many artists will actively want to use Git!).

Git Workflow

Your Git workflow is very much something you need to decide for yourself given your own experiences as a team and how you work together. However. I would strongly recommend the appropriately named Git Flow methodology as described by the original author here.

I won't go into too much depth here on how the methodology works as the author describes it perfectly and in quite few words too so it's easy to get through. I have been using with my team for awhile now, and it's the best workflow we've tried so far.

Git GUI Client Application

This is really a personal preference here as there are quite a few options in terms of Git GUI or whether to use a GUI at all. But I would like to suggest the free SourceTree application as it plugs in perfectly with the Git Flow extension. Read the SourceTree tutorial here on implementing the Git Flow methodology in their application.

Unity3D Ignore Folders

For an up to date version checkout Github maintained Unity.gitignore file without OS specifics.

# =============== #
# Unity generated #
# =============== #
Temp/
Library/

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
obj/
*.svd
*.userprefs
/*.csproj
*.pidb
*.suo
/*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

Unity3D Settings

For versions of Unity 3D v4.3 and up:

  1. (Skip this step in v4.5 and up) Enable External option in Unity ? Preferences ? Packages ? Repository.
  2. Open the Edit menu and pick Project Settings ? Editor:
    1. Switch Version Control Mode to Visible Meta Files.
    2. Switch Asset Serialization Mode to Force Text.
  3. Save the scene and project from File menu.

Want you migrate your existing repo to LFS?

Check out my blog post for steps on how to do it here.

Additional Configuration

One of the few major annoyances one has with using Git with Unity3D projects is that Git doesn't care about directories and will happily leave empty directories around after removing files from them. Unity3D will make *.meta files for these directories and can cause a bit of a battle between team members when Git commits keep adding and removing these meta files.

Add this Git post-merge hook to the /.git/hooks/ folder for repositories with Unity3D projects in them. After any Git pull/merge, it will look at what files have been removed, check if the directory it existed in is empty, and if so delete it.

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

How to center the elements in ConstraintLayout

just add

android:gravity="center"

and done :)

Reverse engineering from an APK file to a project

There is a new way to do this.

Android Studio 2.2 has APK Analyzer it will give lot of info about apk, checkout it here :- http://android-developers.blogspot.in/2016/05/android-studio-22-preview-new-ui.html

Ap

How to index characters in a Golang string?

The general solution to interpreting a char as a string is string("HELLO"[1]).

Rich's solution also works, of course.

jquery <a> tag click event

All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.

Export and import table dump (.sql) using pgAdmin

  1. In pgAdmin, select the required target schema in object tree (databases->your_db_name->schemas->your_target_schema)
  2. Click on Plugins/PSQL Console (in top-bar)
  3. Write \i /path/to/yourfile.sql
  4. Press enter

Deny direct access to all .php files except index.php

An easy solution is to rename all non-index.php files to .inc, then deny access to *.inc files. I use this in a lot of my projects and it works perfectly fine.

How to implement the Softmax function in Python

This also works with np.reshape.

   def softmax( scores):
        """
        Compute softmax scores given the raw output from the model

        :param scores: raw scores from the model (N, num_classes)
        :return:
            prob: softmax probabilities (N, num_classes)
        """
        prob = None

        exponential = np.exp(
            scores - np.max(scores, axis=1).reshape(-1, 1)
        )  # subract the largest number https://jamesmccaffrey.wordpress.com/2016/03/04/the-max-trick-when-computing-softmax/
        prob = exponential / exponential.sum(axis=1).reshape(-1, 1)

        

        return prob

Number of elements in a javascript object

function count(){
    var c= 0;
    for(var p in this) if(this.hasOwnProperty(p))++c;
    return c;
}

var O={a: 1, b: 2, c: 3};

count.call(O);

C# : "A first chance exception of type 'System.InvalidOperationException'"

Consider using System.Windows.Forms.Timer instead of System.Threading.Timer for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.

In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.

127 Return code from $?

A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:

   For  the shell’s purposes, a command which exits with a zero exit status has succeeded.  An exit status
   of zero indicates success.  A non-zero exit status indicates failure.  When a command terminates  on  a
   fatal signal N, bash uses the value of 128+N as the exit status.
   If  a command is not found, the child process created to execute it returns a status of 127.  If a com-
   mand is found but is not executable, the return status is 126.

   If a command fails because of an error during expansion or redirection, the exit status is greater than
   zero.

   Shell  builtin  commands  return  a  status of 0 (true) if successful, and non-zero (false) if an error
   occurs while they execute.  All builtins return an exit status of 2 to indicate incorrect usage.

   Bash itself returns the exit status of the last command executed, unless  a  syntax  error  occurs,  in
   which case it exits with a non-zero value.  See also the exit builtin command below.

Polling the keyboard (detect a keypress) in python

Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:

import msvcrt 

def kbfunc(): 
   x = msvcrt.kbhit()
   if x: 
      ret = ord(msvcrt.getch()) 
   else: 
      ret = 0 
   return ret

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Tested with: log4j-ap 2.13.2, log4j-core 2.13.2.

  1. Keep XML file directly under below folder structure. src/main/java
  2. In the POM:
    <build>   
 <resources>       
             <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>             
            </resource>
 </resources>  
</build>
  1. Clean and build.

Chmod 777 to a folder and all contents

If you are going for a console command it would be:

chmod -R 777 /www/store. The -R (or --recursive) options make it recursive.

Or if you want to make all the files in the current directory have all permissions type:

chmod -R 777 ./

If you need more info about chmod command see: File permission

Passing a 2D array to a C++ function

Single dimensional array decays to a pointer pointer pointing to the first element in the array. While a 2D array decays to a pointer pointing to first row. So, the function prototype should be -

void myFunction(double (*myArray) [10]);

I would prefer std::vector over raw arrays.

How to reload apache configuration for a site without restarting apache?

It should be possible using the command

sudo /etc/init.d/apache2 reload

I hope that helps.

No newline at end of file

Your original file probably had no newline character.

However, some editors like gedit in linux silently adds newline at end of file. You cannot get rid of this message while using this kind of editors.

What I tried to overcome this issue is to open file with visual studio code editor

This editor clearly shows the last line and you can delete the line as you wish.

How does one add keyboard languages and switch between them in Linux Mint 16?

Mint 18.2 (Cinnamon)
Menu > Keyboard Preferences > Layouts > Options > Switching to another layout:

Menu > Keyboard Preferences > Layouts > Options > Switching to another layout

How do you get the selected value of a Spinner?

This is another way:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int pos, long arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

NodeJS w/Express Error: Cannot GET /

You typically want to render templates like this:

app.get('/', function(req, res){
  res.render('index.ejs');
});

However you can also deliver static content - to do so use:

app.use(express.static(__dirname + '/public'));

Now everything in the /public directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm in the public folder if will be available by visiting /default.htm

Take a look through the express API and Connect Static middleware docs for more info.

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

The URL syntax is the same regardless of the platform in use

String url = "https://www.google.com/maps/search/?api=1&query=" + latitude + ","+ 
longitude;

In Android or iOS the URL launches Google Maps in the Maps app, If the Google Maps app is not installed, the URL launches Google Maps in a browser and performs the requested action.

On any other device, the URL launches Google Maps in a browser and performs the requested action.

here's the link for official documentation https://developers.google.com/maps/documentation/urls/guide

Two HTML tables side by side, centered on the page

Off the top of my head, you might try using the "margin: 0 auto" for #outer rather than #inner.

I often add background-color to my DIVs to see how they're laying out on the view. That might be a good way to diagnose what's going onn here.

Regex pattern including all special characters

Please don't do that... little Unicode BABY ANGELs like this one are dying! ??? (? these are not images) (nor is the arrow!)

?

And you are killing 20 years of DOS :-) (the last smiley is called WHITE SMILING FACE... Now it's at 263A... But in ancient times it was ALT-1)

and his friend

?

BLACK SMILING FACE... Now it's at 263B... But in ancient times it was ALT-2

Try a negative match:

Pattern regex = Pattern.compile("[^A-Za-z0-9]");

(this will ok only A-Z "standard" letters and "standard" 0-9 digits.)

How to get just the responsive grid from Bootstrap 3?

Just choose Grid system and "responsive utilities" it gives you this: http://jsfiddle.net/7LVzs/

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

Implemented in JavaScript (ES6):

/**
    * Calculate x and y in circle's circumference
    * @param {Object} input - The input parameters
    * @param {number} input.radius - The circle's radius
    * @param {number} input.angle - The angle in degrees
    * @param {number} input.cx - The circle's origin x
    * @param {number} input.cy - The circle's origin y
    * @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){

    angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
    const x = cx + radius * Math.sin(angle);
    const y = cy + radius * Math.cos(angle);
    return [ x, y ];

}

Usage:

const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );

Codepen

_x000D_
_x000D_
/**
 * Calculate x and y in circle's circumference
 * @param {Object} input - The input parameters
 * @param {number} input.radius - The circle's radius
 * @param {number} input.angle - The angle in degrees
 * @param {number} input.cx - The circle's origin x
 * @param {number} input.cy - The circle's origin y
 * @returns {Array[number,number]} The calculated x and y
 */
function pointsOnCircle({ radius, angle, cx, cy }){
  angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
  const x = cx + radius * Math.sin(angle);
  const y = cy + radius * Math.cos(angle);
  return [ x, y ];
}

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

function draw( x, y ){

  ctx.clearRect( 0, 0, canvas.width, canvas.height );
  ctx.beginPath();
  ctx.strokeStyle = "orange";
  ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
  ctx.lineWidth = 3;
  ctx.stroke();
  ctx.closePath();

  ctx.beginPath();
  ctx.fillStyle = "indigo";
  ctx.arc( x, y, 6, 0, 2 * Math.PI);
  ctx.fill();
  ctx.closePath();
  
}

let angle = 0;  // In degrees
setInterval(function(){

  const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
  console.log( x, y );
  draw( x, y );
  document.querySelector("#degrees").innerHTML = angle + "&deg;";
  document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();

}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
_x000D_
_x000D_

How do I list one filename per output line in Linux?

Easy, as long as your filenames don't include newlines:

find . -maxdepth 1

If you're piping this into another command, you should probably prefer to separate your filenames by null bytes, rather than newlines, since null bytes cannot occur in a filename (but newlines may):

find . -maxdepth 1 -print0

Printing that on a terminal will probably display as one line, because null bytes are not normally printed. Some programs may need a specific option to handle null-delimited input, such as sort's -z. Your own script similarly would need to account for this.

Parse JSON response using jQuery

jQuery.ajax({
            type: 'GET',
            url: "../struktur2/load.php",
            async: false,
            contentType: "application/json",
            dataType: 'json',
            success: function(json) {
              items = json;
            },
            error: function(e) {
              console.log("jQuery error message = "+e.message);
            }
        });

Reading all files in a directory, store them in objects, and send the object

Another version with Promise's modern method. It's shorter that the others responses based on Promise :

const readFiles = (dirname) => {

  const readDirPr = new Promise( (resolve, reject) => {
    fs.readdir(dirname, 
      (err, filenames) => (err) ? reject(err) : resolve(filenames))
  });

  return readDirPr.then( filenames => Promise.all(filenames.map((filename) => {
      return new Promise ( (resolve, reject) => {
        fs.readFile(dirname + filename, 'utf-8',
          (err, content) => (err) ? reject(err) : resolve(content));
      })
    })).catch( error => Promise.reject(error)))
};

readFiles(sourceFolder)
  .then( allContents => {

    // handle success treatment

  }, error => console.log(error));

Page redirect with successful Ajax request

You can just redirect in your success handler, like this:

window.location.href = "thankyou.php";

Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:

setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);

Intro to GPU programming

CUDA is an excellent framework to start with. It lets you write GPGPU kernels in C. The compiler will produce GPU microcode from your code and send everything that runs on the CPU to your regular compiler. It is NVIDIA only though and only works on 8-series cards or better. You can check out CUDA zone to see what can be done with it. There are some great demos in the CUDA SDK. The documentation that comes with the SDK is a pretty good starting point for actually writing code. It will walk you through writing a matrix multiplication kernel, which is a great place to begin.

Unable to add window -- token null is not valid; is your activity running?

If you're using getApplicationContext() as Context in Activity for the dialog like this

Dialog dialog = new Dialog(getApplicationContext());

then use YourActivityName.this

Dialog dialog = new Dialog(YourActivityName.this);

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How to measure time taken between lines of code in python?

I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.

import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)

Output:

0 days 00:05:32.541600

I would recommend using this if time precision is not the most important, otherwise use time library:

%timeit pd.Timestamp.now() outputs 3.29 µs ± 214 ns per loop

%timeit time.time() outputs 154 ns ± 13.3 ns per loop

Fail to create Android virtual Device, "No system image installed for this Target"

As a workaround, go to sdk installation directory and perform the following steps:

  • Navigate to system-images/android-19/default
  • Move everything in there to system-images/android-19/

The directory structure should look like this: enter image description here

And it should work!

How do I crop an image in Java?

The solution I found most useful for cropping a buffered image uses the getSubImage(x,y,w,h);

My cropping routine ended up looking like this:

  private BufferedImage cropImage(BufferedImage src, Rectangle rect) {
      BufferedImage dest = src.getSubimage(0, 0, rect.width, rect.height);
      return dest; 
   }

Returning JSON object as response in Spring Boot

If you need to return a JSON object using a String, then the following should work:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
...

@RestController
@RequestMapping("/student")
public class StudentController {

    @GetMapping
    @RequestMapping("/")
    public ResponseEntity<JsonNode> get() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree("{\"id\": \"132\", \"name\": \"Alice\"}");
        return ResponseEntity.ok(json);
    }
    ...
}

Sequelize.js delete query?

I've searched deep into the code, step by step into the following files:

https://github.com/sdepold/sequelize/blob/master/test/Model/destroy.js

https://github.com/sdepold/sequelize/blob/master/lib/model.js#L140

https://github.com/sdepold/sequelize/blob/master/lib/query-interface.js#L207-217

https://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js

What I found:

There isn't a deleteAll method, there's a destroy() method you can call on a record, for example:

Project.find(123).on('success', function(project) {
  project.destroy().on('success', function(u) {
    if (u && u.deletedAt) {
      // successfully deleted the project
    }
  })
})

How do I iterate over a JSON structure?

If this is your dataArray:

var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];

then:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
         var ID = this.id;
         var CLASS = this.class;
});

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

Label points in geom_point

The ggrepel package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel() (draws rectangles around the text) or geom_text_repel() functions.

library(ggplot2)
library(ggrepel)

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep = ",")

nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) + 
  geom_point(color = "blue", size = 3)

### geom_label_repel
nbaplot + 
  geom_label_repel(aes(label = Name),
                  box.padding   = 0.35, 
                  point.padding = 0.5,
                  segment.color = 'grey50') +
  theme_classic()

enter image description here

### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to 
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) + 
  geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77", 
                                      nba$PTS < 18 ~ "#d95f02",
                                      TRUE ~ "#7570b3"), 
             size = 3, alpha = 0.8) +
  geom_text_repel(data          = subset(nba, PTS > 25),
                  nudge_y       = 32 - subset(nba, PTS > 25)$PTS,
                  size          = 4,
                  box.padding   = 1.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  geom_label_repel(data         = subset(nba, PTS < 18),
                  nudge_y       = 16 - subset(nba, PTS < 18)$PTS,
                  size          = 4,
                  box.padding   = 0.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
  scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
  theme_classic(base_size = 16)

Edit: To use ggrepel with lines, see this and this.

Created on 2019-05-01 by the reprex package (v0.2.0).

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

How to get an MD5 checksum in PowerShell

Here is a pretty print example attempting to verify the SHA256 fingerprint. I downloaded gpg4win v3.0.3 using PowerShell v4 (requires Get-FileHash).

Download the package from https://www.gpg4win.org/download.html, open PowerShell, grab the hash from the download page, and run:

cd ${env:USERPROFILE}\Downloads
$file = "gpg4win-3.0.3.exe"

# Set $hash to the hash reference from the download page:
$hash = "477f56212ee60cc74e0c5e5cc526cec52a069abff485c89c2d57d1b4b6a54971"

# If you have an MD5 hash: # $hashAlgo="MD5"
$hashAlgo = "SHA256"

$computed_hash = (Get-FileHash -Algorithm $hashAlgo $file).Hash.ToUpper()
if ($computed_hash.CompareTo($hash.ToUpper()) -eq 0 ) {
    Write-Output "Hash matches for file $file" 
} 
else { 
    Write-Output ("Hash DOES NOT match for file {0}: `nOriginal hash: {1} `nComputed hash: {2}" -f ($file, $hash.ToUpper(), $computed_hash)) 
}

Output:

Hash matches for file gpg4win-3.0.3.exe

Firefox and SSL: sec_error_unknown_issuer

Firefox is more stringent than other browsers and will require proper installation of an intermediate server certificate. This can be supplied by the cert authority the certificate was purchased from. the intermediate cert is typically installed in the same location as the server cert and requires the proper entry in the httpd.conf file.

while many are chastising Firefox for it's (generally) exclusive 'flagging' of this, it's actually demonstrating a higher level of security standards.

How to use a class object in C++ as a function parameter

I was asking the same too. Another solution is you could overload your method:

void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);

in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself

void remove_id(EmployeeClass _obj) {
    int saveId = _obj->id;
    ...
};

void remove_id(ProductClass _obj) {
    int saveId = _obj->id;
    ...
};

void remove_id(DepartmentClass _obj) {
    int saveId = _obj->id;
    ...
};

Quickly create a large file on a Linux system

One approach: if you can guarantee unrelated applications won't use the files in a conflicting manner, just create a pool of files of varying sizes in a specific directory, then create links to them when needed.

For example, have a pool of files called:

  • /home/bigfiles/512M-A
  • /home/bigfiles/512M-B
  • /home/bigfiles/1024M-A
  • /home/bigfiles/1024M-B

Then, if you have an application that needs a 1G file called /home/oracle/logfile, execute a "ln /home/bigfiles/1024M-A /home/oracle/logfile".

If it's on a separate filesystem, you will have to use a symbolic link.

The A/B/etc files can be used to ensure there's no conflicting use between unrelated applications.

The link operation is about as fast as you can get.

Fatal error: Call to undefined function: ldap_connect()

Add path of your PHP to Windows System Path. The path should contain php.exe.

After adding the path open a new command prompt and make sure php.exe is in path by typing

C:\>php --help

Once you see proper help message from above, enable the php_ldap.dll extension in php.ini

Also copy php_ldap.dll from php/ext directory to apache/bin folder

Restart wamp and phpinfo() will now show ldap enabled.

How do I loop through children objects in javascript?

In ECS6, one may use Array.from():

const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
listArray.forEach((item) => {console.log(item)});

adb shell command to make Android package uninstall dialog appear

In my case, I do an adb shell pm list packages to see first what are the packages/apps installed in my Android device or emulator, then upon locating the desired package/app, I do an adb shell pm uninstall -k com.package.name.

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Can't connect to local MySQL server through socket homebrew

Just to add to these answers, In my case I had no local mySQL server, it was running inside a docker container. So the socket file does not exist and will not be accessible for the "mysql" client.

The sock file gets created by mysqld and mysql uses this to communicate with it. However if your mySql server is not running local, it does not require the sock file.

By specifying a host name/ip the sock file is not required e.g.

mysql --host=127.0.0.1 --port=3306 --user=xyz --password=xyz

net::ERR_INSECURE_RESPONSE in Chrome

I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell and change the date manually.

How do you represent a JSON array of strings?

Basically yes, JSON is just a javascript literal representation of your value so what you said is correct.

You can find a pretty clear and good explanation of JSON notation on http://json.org/

Bootstrap 3.0 Sliding Menu from left

I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

div.hardware-accelarate {
     -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
         -ms-transform: translate3d(0,0,0);
          -o-transform: translate3d(0,0,0);
             transform: translate3d(0,0,0);
}

I've made a plunkr setup for ya'll to test and tweak...

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Create directories using make file

Or, KISS.

DIRS=build build/bins

... 

$(shell mkdir -p $(DIRS))

This will create all the directories after the Makefile is parsed.

How do I concatenate two lists in Python?

It's worth noting that the itertools.chain function accepts variable number of arguments:

>>> l1 = ['a']; l2 = ['b', 'c']; l3 = ['d', 'e', 'f']
>>> [i for i in itertools.chain(l1, l2)]
['a', 'b', 'c']
>>> [i for i in itertools.chain(l1, l2, l3)]
['a', 'b', 'c', 'd', 'e', 'f']

If an iterable (tuple, list, generator, etc.) is the input, the from_iterable class method may be used:

>>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
>>> [i for i in itertools.chain.from_iterable(il)]
['a', 'b', 'c', 'd', 'e', 'f']

How to convert dd/mm/yyyy string into JavaScript Date object?

var date = new Date("enter your  date");//2018-01-17 14:58:29.013

Just one line is enough no need to do any kind of split, join, etc.:

$scope.ssdate=date.toLocaleDateString();//  mm/dd/yyyy format

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

You can do it like this

new DirectoryInfo(path).GetFiles().Where(Current => Regex.IsMatch(Current.Extension, "\\.(aspx|ascx)", RegexOptions.IgnoreCase)

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

How to round a floating point number up to a certain decimal place?

I have this code:

tax = (tax / 100) * price

and then this code:

tax = round((tax / 100) * price, 2)

round worked for me

Best way to parse RSS/Atom feeds with PHP

I would like introduce simple script to parse RSS:

$i = 0; // counter
$url = "http://www.banki.ru/xml/news.rss"; // url to parse
$rss = simplexml_load_file($url); // XML parser

// RSS items loop

print '<h2><img style="vertical-align: middle;" src="'.$rss->channel->image->url.'" /> '.$rss->channel->title.'</h2>'; // channel title + img with src

foreach($rss->channel->item as $item) {
if ($i < 10) { // parse only 10 items
    print '<a href="'.$item->link.'">'.$item->title.'</a><br />';
}

$i++;
}

printing out a 2-D array in Matrix format

public class Matrix 
{
   public static void main(String[] args)
   {
      double Matrix [] []={
         {0*1,0*2,0*3,0*4),
         {0*1,1*1,2*1,3*1),
         {0*2,1*2,2*2,3*2),
         {0*3,1*3,2*3,3*3)
      };

      int i,j;
      for(i=0;i<4;i++)
      {
         for(j=0;j<4;j++)
            System.out.print(Matrix [i] [j] + " ");
         System.out.println();
      }
   }
}

Way to get all alphabetic chars in an array in PHP?

range for A-Z but if you want to go for example from A to DU then:

 function generateAlphabet($na) {
        $sa = "";
        while ($na >= 0) {
            $sa = chr($na % 26 + 65) . $sa;
            $na = floor($na / 26) - 1;
        }
        return $sa;
    }

    $alphabet = Array();
    for ($na = 0; $na < 125; $na++) {
        $alphabet[]=generateAlphabet($na);
    }

    print_r($alphabet);

your answer will look like:

Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G [7] => H [8] => I [9] => J [10] => K [11] => L [12] => M [13] => N [14] => O [15] => P [16] => Q [17] => R [18] => S [19] => T [20] => U [21] => V [22] => W [23] => X [24] => Y [25] => Z [26] => AA [27] => AB [28] => AC [29] => AD [30] => AE [31] => AF [32] => AG [33] => AH [34] => AI [35] => AJ [36] => AK [37] => AL [38] => AM [39] => AN [40] => AO [41] => AP [42] => AQ [43] => AR [44] => AS [45] => AT [46] => AU [47] => AV [48] => AW [49] => AX [50] => AY [51] => AZ [52] => BA [53] => BB [54] => BC [55] => BD [56] => BE [57] => BF [58] => BG [59] => BH [60] => BI [61] => BJ [62] => BK [63] => BL [64] => BM [65] => BN [66] => BO [67] => BP [68] => BQ [69] => BR [70] => BS [71] => BT [72] => BU [73] => BV [74] => BW [75] => BX [76] => BY [77] => BZ [78] => CA [79] => CB [80] => CC [81] => CD [82] => CE [83] => CF [84] => CG [85] => CH [86] => CI [87] => CJ [88] => CK [89] => CL [90] => CM [91] => CN [92] => CO [93] => CP [94] => CQ [95] => CR [96] => CS [97] => CT [98] => CU [99] => CV [100] => CW [101] => CX [102] => CY [103] => CZ [104] => DA [105] => DB [106] => DC [107] => DD [108] => DE [109] => DF [110] => DG [111] => DH [112] => DI [113] => DJ [114] => DK [115] => DL [116] => DM [117] => DN [118] => DO [119] => DP [120] => DQ [121] => DR [122] => DS [123] => DT [124] => DU ) 

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Try [^- ], \s will match 5 other characters beside the space (like tab, newline, formfeed, carriage return).

HTML - how can I show tooltip ONLY when ellipsis is activated

Here's a Vanilla JavaScript solution:

_x000D_
_x000D_
(function init() {_x000D_
_x000D_
  var cells = document.getElementsByClassName("cell");_x000D_
_x000D_
  for(let index = 0; index < cells.length; ++index) {_x000D_
    let cell = cells.item(index);_x000D_
    cell.addEventListener('mouseenter', setTitleIfNecessary, false);_x000D_
  }_x000D_
_x000D_
  function setTitleIfNecessary() {_x000D_
    if(this.offsetWidth < this.scrollWidth) {_x000D_
      this.setAttribute('title', this.innerHTML);_x000D_
    }_x000D_
  }_x000D_
_x000D_
})();
_x000D_
.cell {_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
  width: 120px; _x000D_
}
_x000D_
<div class="cell">hello world!</div>_x000D_
<div class="cell">hello mars! kind regards, world</div>
_x000D_
_x000D_
_x000D_

AngularJS - Find Element with attribute

Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.

So in your myDirective

return {
    link: function (scope, element, attr) {
        element.html('Hello world');
    }
}

If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers

angular.element(document.querySelectorAll("[my-directive]"));

however you would need to use jquery to support IE8 and backwards

angular.element($("[my-directive]"));

or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Just check if the request has a status code 200. So for example:

if status != 200:
    print("An error has occured. [Status code", status, "]")
else:
    data = response.json() #Only convert to Json when status is OK.
    if not data["elements"]:
        print("Empty JSON")
    else:
        "You can extract data here"

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

In my android device I had different flavors of the same app install. This gives me error INSTALL FAILED CONFLICTING PROVIDER. so I uninstall my all flavors of the same app. and tried

adb install -r /Users/demo-debug-92acfc5.apk

It solved my problem.

MYSQL Truncated incorrect DOUBLE value

It seems mysql handles the type casting gracefully with SELECT statements. The shop_id field is of type varchar but the select statements works

select * from shops where shop_id = 26244317283;

But when you try updating the fields

update stores set store_url = 'https://test-url.com' where shop_id = 26244317283;

It fails with error Truncated incorrect DOUBLE value: '1t5hxq9'

You need to put the shop_id 26244317283 in quotes '26244317283' for the query to work since the field is of type varchar not int

update stores set store_url = 'https://test-url.com' where shop_id = '26244317283';

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Centering text in a table in Twitter Bootstrap

If it's just once, you shouldn't alter your style sheet. Just edit that particular td:

<td style="text-align: center;">

Cheers

Throwing exceptions in a PHP Try Catch block

function _modulename_getData($field, $table) {
  try {
    if (empty($field)) {
      throw new Exception("The field is undefined."); 
    }
    // rest of code here...
  }
  catch (Exception $e) {
    /*
        Here you can either echo the exception message like: 
        echo $e->getMessage(); 

        Or you can throw the Exception Object $e like:
        throw $e;
    */
  }
}

Python not working in command prompt?

Kalle posted a link to a page that has this video on it, but it's done on XP. If you use Windows 7:

  1. Press the windows key.
  2. Type "system env". Press enter.
  3. Press alt + n
  4. Press alt + e
  5. Press right, and then ; (that's a semicolon)
  6. Without adding a space, type this at the end: C:\Python27
  7. Hit enter twice. Hit esc.
  8. Use windows key + r to bring up the run dialog. Type in python and press enter.

How to make <input type="date"> supported on all browsers? Any alternatives?

I was having problems with this, maintaining the UK dd/mm/yyyy format, I initially used the answer from adeneo https://stackoverflow.com/a/18021130/243905 but that didnt work in safari for me so changed to this, which as far as I can tell works all over - using the jquery-ui datepicker, jquery validation.

if ($('[type="date"]').prop('type') !== 'date') {
    //for reloading/displaying the ISO format back into input again
    var val = $('[type="date"]').each(function () {
        var val = $(this).val();
        if (val !== undefined && val.indexOf('-') > 0) {
            var arr = val.split('-');
            $(this).val(arr[2] + '/' + arr[1] + '/' + arr[0]);
        }
    });

    //add in the datepicker
    $('[type="date"]').datepicker(datapickeroptions);

    //stops the invalid date when validated in safari
    jQuery.validator.methods["date"] = function (value, element) {
        var shortDateFormat = "dd/mm/yy";
        var res = true;
        try {
            $.datepicker.parseDate(shortDateFormat, value);
        } catch (error) {
            res = false;
        }
        return res;
    }
}

Determine on iPhone if user has enabled push notifications

In Xamarin, all above solution does not work for me. This is what I use instead:

public static bool IsRemoteNotificationsEnabled() {
    return UIApplication.SharedApplication.CurrentUserNotificationSettings.Types != UIUserNotificationType.None;
}

It's getting a live update also after you've changed the notification status in Settings.

C++ Dynamic Shared Library on Linux

myclass.h

#ifndef __MYCLASS_H__
#define __MYCLASS_H__

class MyClass
{
public:
  MyClass();

  /* use virtual otherwise linker will try to perform static linkage */
  virtual void DoSomething();

private:
  int x;
};

#endif

myclass.cc

#include "myclass.h"
#include <iostream>

using namespace std;

extern "C" MyClass* create_object()
{
  return new MyClass;
}

extern "C" void destroy_object( MyClass* object )
{
  delete object;
}

MyClass::MyClass()
{
  x = 20;
}

void MyClass::DoSomething()
{
  cout<<x<<endl;
}

class_user.cc

#include <dlfcn.h>
#include <iostream>
#include "myclass.h"

using namespace std;

int main(int argc, char **argv)
{
  /* on Linux, use "./myclass.so" */
  void* handle = dlopen("myclass.so", RTLD_LAZY);

  MyClass* (*create)();
  void (*destroy)(MyClass*);

  create = (MyClass* (*)())dlsym(handle, "create_object");
  destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");

  MyClass* myClass = (MyClass*)create();
  myClass->DoSomething();
  destroy( myClass );
}

On Mac OS X, compile with:

g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user

On Linux, compile with:

g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user

If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object and destroy_object. Your main application would not need to be changed in any way.

How do I concatenate two strings in C?

C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.

Use strcat to concatenate two strings. You could use the following function to do it:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.

Call the function like this:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.

Laravel 4: Redirect to a given url

Both Redirect::to() and Redirect::away() should work.

Difference

Redirect::to() does additional URL checks and generations. Those additional steps are done in Illuminate\Routing\UrlGenerator and do the following, if the passed URL is not a fully valid URL (even with protocol):

Determines if URL is secure
rawurlencode() the URL
trim() URL

src : https://medium.com/@zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f

phonegap open link in browser

None of these answers are explicit enough to get external links to open in each platform. As per the inAppBrowser docs:

Install

cordova plugin add cordova-plugin-inappbrowser

Overwrite window.open (optional, but recommended for simplicity)

window.open = cordova.InAppBrowser.open;

If you don't overwrite window.open, you will be using the native window.open function, and can't expect to get the same results cross-platform.

Use it to open links in default browser

window.open(your_href_value, '_system');

Note that the target for the inAppBrowser (which is what the plugin name suggests it is to be used for) is '_blank', instead of '_system'.


Without the steps above, I was not able to get links to open in the default browser app cross-platform.

Extra credit

Here's an example (live) click handler for the links:

document.addEventListener('click', function (e) {
    if (e.target.tagName === 'A' &&
        e.target.href.match(/^https?:\/\//)) {
        e.preventDefault();
        window.open(e.target.href, '_system');
    }
});

auto refresh for every 5 mins

Install an interval:

<script type="text/javascript">    
    setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>

How do I turn a C# object into a JSON string in .NET?

If you are in an ASP.NET MVC web controller it's as simple as:

string ladAsJson = Json(Lad);

Can't believe no one has mentioned this.

How to reset Jenkins security settings from the command line?

For one who is using macOS, the new version just can be installed by homebrew. so for resting, this command line must be using:

brew services restart jenkins-lts

CSS Layout - Dynamic width DIV

Or, if you know the width of the two "side" images and don't want to deal with floats:

<div class="container">
    <div class="left-panel"><img src="myleftimage" /></div>
    <div class="center-panel">Content goes here...</div>
    <div class="right-panel"><img src="myrightimage" /></div>
</div>

CSS:

.container {
    position:relative;
    padding-left:50px;
    padding-right:50px;
}

.container .left-panel {
    width: 50px;
    position:absolute;
    left:0px;
    top:0px;
}

.container .right-panel {
    width: 50px;
    position:absolute;
    right:0px;
    top:0px;
}

.container .center-panel {
    background: url('mymiddleimage');
}

Notes:

Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.

JavaScript split String with white space

You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.

var string = "text to split";
    string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
    stringArray.push(string[i]);
    if(i != string.length-1){
        stringArray.push(" ");
    }
}

Update: Removed trailing space.

git - pulling from specific branch

This worked perfectly for me, although fetching all branches could be a bit too much:

git init
git remote add origin https://github.com/Vitosh/VBA_personal.git
git fetch --all
git checkout develop

enter image description here

Convert XML String to Object

You can use xsd.exe to create schema bound classes in .Net then XmlSerializer to Deserialize the string : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx

NoClassDefFoundError in Java: com/google/common/base/Function

When I caught the exception java.lang.NoClassDefFoundError: com/google/common/base/Function it was caused by errors in Project Libraries.

Please check it in your project settings. For Intellij IDEA go to File - Project Structure and select Modules tab. All I needed to do to resolve this exception was re-adding the selenium library

"Keep Me Logged In" - the best approach

Security Notice: Basing the cookie off an MD5 hash of deterministic data is a bad idea; it's better to use a random token derived from a CSPRNG. See ircmaxell's answer to this question for a more secure approach.

Usually I do something like this:

  1. User logs in with 'keep me logged in'
  2. Create session
  3. Create a cookie called SOMETHING containing: md5(salt+username+ip+salt) and a cookie called somethingElse containing id
  4. Store cookie in database
  5. User does stuff and leaves ----
  6. User returns, check for somethingElse cookie, if it exists, get the old hash from the database for that user, check of the contents of cookie SOMETHING match with the hash from the database, which should also match with a newly calculated hash (for the ip) thus: cookieHash==databaseHash==md5(salt+username+ip+salt), if they do, goto 2, if they don't goto 1

Off course you can use different cookie names etc. also you can change the content of the cookie a bit, just make sure it isn't to easily created. You can for example also create a user_salt when the user is created and also put that in the cookie.

Also you could use sha1 instead of md5 (or pretty much any algorithm)

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

Solution using only javascript

function saveFile(fileName,urlFile){
    let a = document.createElement("a");
    a.style = "display: none";
    document.body.appendChild(a);
    a.href = urlFile;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

let textData = `El contenido del archivo
que sera descargado`;
let blobData = new Blob([textData], {type: "text/plain"});
let url = window.URL.createObjectURL(blobData);
//let url = "pathExample/localFile.png"; // LocalFileDownload
saveFile('archivo.txt',url);

Django DoesNotExist

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

Can (domain name) subdomains have an underscore "_" in it?

A note on terminology, in furtherance to Bortzmeyer's answer

One should be clear about definitions. As used here:

  • domain name is the identifier of a resource in a DNS database
  • label is the part of a domain name in between dots
  • hostname is a special type of domain name which identifies Internet hosts

The hostname is subject to the restrictions of RFC 952 and the slight relaxation of RFC 1123

RFC 2181 makes clear that there is a difference between a domain name and a hostname:

...[the fact that] any binary label can have an MX record does not imply that any binary name can be used as the host part of an e-mail address...

So underscores in hostnames are a no-no, underscores in domain names are a-ok.

In practice, one may well see hostnames with underscores. As the Robustness Principle says: "Be conservative in what you send, liberal in what you accept".

A note on encoding

In the 21st century, it turns out that hostnames as well as domain names may be internationalized! This means resorting to encodings in case of labels that contain characters that are outside the allowed set.

In particular, it allows one to encode the _ in hostnames (Update 2017-07: This is doubtful, see comments. The _ still cannot be used in hostnames. Indeed, it cannot even be used in internationalized labels.)

The first RFC for internationalization was RFC 3490 of March 2003, "Internationalizing Domain Names in Applications (IDNA)". Today, we have:

  • RFC 5890 "IDNA: Definitions and Document Framework"
  • RFC 5891 "IDNA: Protocol"
  • RFC 5892 "The Unicode Code Points and IDNA"
  • RFC 5893 "Right-to-Left Scripts for IDNA"
  • RFC 5894 "IDNA: Background, Explanation, and Rationale"
  • RFC 5895 "Mapping Characters for IDNA 2008"

You may also want to check the Wikipedia Entry

RFC 5890 introduces the term LDH (Letter-Digit-Hypen) label for labels used in hostnames and says:

This is the classical label form used, albeit with some additional restrictions, in hostnames (RFC 952). Its syntax is identical to that described as the "preferred name syntax" in Section 3.5 of RFC 1034 as modified by RFC 1123. Briefly, it is a string consisting of ASCII letters, digits, and the hyphen with the further restriction that the hyphen cannot appear at the beginning or end of the string. Like all DNS labels, its total length must not exceed 63 octets.

Going back to simpler times, this Internet draft is an early proposal for hostname internationalization. Hostnames with international characters may be encoded using, for example, 'RACE' encoding.

The author of the 'RACE encoding' proposal notes:

According to RFC 1035, host parts must be case-insensitive, start and end with a letter or digit, and contain only letters, digits, and the hyphen character ("-"). This, of course, excludes any internationalized characters, as well as many other characters in the ASCII character repertoire. Further, domain name parts must be 63 octets or shorter in length.... All post-converted name parts that contain internationalized characters begin with the string "bq--". (...) The string "bq--" was chosen because it is extremely unlikely to exist in host parts before this specification was produced.

How to create a list of objects?

In Python, the name of the class refers to the class instance. Consider:

class A: pass
class B: pass
class C: pass

lst = [A, B, C]

# instantiate second class
b_instance = lst[1]()
print b_instance

Recommended Fonts for Programming?

I think the anti-aliasing blur on Consolas is caused by monitors which do not have ClearType enabled. Consolas was designed for ClearType.

[Jeff A: indeed, you can see screenshots of this in a post I wrote on this topic.]

Java method: Finding object in array list given a known attribute value

List<YourClass> list = ArrayList<YourClass>();


List<String> userNames = list.stream().map(m -> m.getUserName()).collect(Collectors.toList());

output: ["John","Alex"]

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

check to make the field you are referencing to is an exact match with foreign key, in my case one was unsigned and the other was signed so i just changed them to match and this worked

ALTER TABLE customer_information ADD CONSTRAINT fk_customer_information1 FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE

Reference - What does this error mean in PHP?

HTTP Error 500 - Internal server error

The HTTP status code 500 and the typical Apache or browser warning is a very broad message. It's not the actual error. To figure out if it's a webserver misconfiguration (.htaccess) or a PHP fatal error, you have to look at the error.log.

Apache error page: "More information about this error may be available in the server error log."

You can typically find the webservers log under:

  • /var/log/apache2 on Linux servers, often used for local and virtual hosts.
  • /var/www/_user12345_/logs or similar on shared hosting plans.
    Usually there's a logs/ directory alongside each htdocs/ folder.
  • C:\xampp\apache\logs\error.log for WAMP/XAMPP distributions of Apache+PHP.
  • Alternatively just use a file search feature to locate anything called "error.log".
    Or look into your Apache httpd.conf and its ErrorLog directive.
  • /var/log/nginx/nginx_error.log for NGINX.
  • C:\inetpub\logs\LogFiles for IIS.
  • Luckily this is uncommon still, but journalctl -r -u apache2.service could also hold parts of the log on Linux setups.

It's a text file. Search for the entry most closely matching the error time, and use the significant part of the error message (from "PHP Error: …" until "in line…") for further googling.

[Mon 22:10] [:error] [pid 12345] [client 127.0.0.1] FastCGI: server "/fcgi/p73" stderr: PHP message:PHP Error: Unfiltered inputvariable $_JSON['pokestop_lng'] in filyfile.php on line 845

For FPM setups you will often just see fatal PHP errors here. Whereas older mod_php (shared hosting) configurations often mix in warnings and notices (which usually are also worth inspecting).

If not configured to use the system or Apache logging mechanism, you may also want to look at PHP's error.log. Generally it's simpler to leave the defaults and just enable error_display + error_reporting to reveal the concrete error. The HTTP 500 catch-all page after all is just a variation of PHP's white screen of death.

See also:

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

How to horizontally align ul to center of div?

ul {
width: 90%; 
    list-style-type:none;
    margin:auto;
    padding:0;
    position:relative;
    left:5%;
}

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

Getting the current Fragment instance in the viewpager

Based on what he answered @chahat jain :

"When we use the viewPager, a good way to access the fragment instance in activity is instantiateItem(viewpager,index). //index- index of fragment of which you want instance."

If you want to do that in kotlin

val fragment =  mv_viewpager.adapter!!.instantiateItem(mv_viewpager, 0) as Fragment
                if ( fragment is YourFragmentFragment)
                 {
                    //DO somthign 
                 }

0 to the fragment instance of 0

//=========================================================================// //#############################Example of uses #################################// //=========================================================================//

Here is a complete example to get a losest vision about

here is my veiewPager in the .xml file

   ...
    <android.support.v4.view.ViewPager
                android:id="@+id/mv_viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="5dp"/>
    ...

And the home activity where i insert the tab

...
import kotlinx.android.synthetic.main.movie_tab.*

class HomeActivity : AppCompatActivity() {

    lateinit var  adapter:HomeTabPagerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
       ...
    }



    override fun onCreateOptionsMenu(menu: Menu) :Boolean{
            ...

        mSearchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
          ...

            override fun onQueryTextChange(newText: String): Boolean {

                if (mv_viewpager.currentItem  ==0)
                {
                    val fragment =  mv_viewpager.adapter!!.instantiateItem(mv_viewpager, 0) as Fragment
                    if ( fragment is ListMoviesFragment)
                        fragment.onQueryTextChange(newText)
                }
                else
                {
                    val fragment =  mv_viewpager.adapter!!.instantiateItem(mv_viewpager, 1) as Fragment
                    if ( fragment is ListShowFragment)
                        fragment.onQueryTextChange(newText)
                }
                return true
            }
        })
        return super.onCreateOptionsMenu(menu)
    }
        ...

}

Xcode 6.1 Missing required architecture X86_64 in file

I use lipo command to combine two built static libraries manually.

EX: I have a static library(libXYZ.a) to build.

I run build for Generic iOS Device and got Product in Debug-iphoneos/

$ lipo -info Debug-iphoneos/libXYZ.a
Architectures in the fat file: Debug-iphoneos/libXYZ.a are: armv7 arm64

Then I run build for any iOS Simulator and got Product in Debug-iphonesimulator/

$ lipo -info Debug-iphonesimulator/libXYZ.a
Architectures in the fat file: Debug-iphonesimulator/libXYZ.a are: i386 x86_64

Finally I combine into one to contain all architectures.

$ lipo -create Debug-iphoneos/libXYZ.a Debug-iphonesimulator/libXYZ.a -output libXYZ.a
$ lipo -info libXYZ.a
Architectures in the fat file: libXYZ.a are: armv7 i386 x86_64 arm64

how to show calendar on text box click in html

Starting with HTML5, <input type="date" /> will do just fine.

Demo: http://jsfiddle.net/8N6KH/

Sending cookies with postman

Even after toggling it did not work. I closed and restarted the browser after adding the postman plugin, logged into the site to generate cookies afresh and then it worked for me.

How to convert Varchar to Int in sql server 2008?

Try with below command, and it will ask all values to INT

select case when isnumeric(YourColumn + '.0e0') = 1 then cast(YourColumn as int) else NULL end /* case */ from YourTable

Better way to find control in ASP.NET

FindControl does not search within nested controls recursively. It does only find controls that's NamigContainer is the Control on that you are calling FindControl.

Theres a reason that ASP.Net does not look into your nested controls recursively by default:

  • Performance
  • Avoiding errors
  • Reusability

Consider you want to encapsulate your GridViews, Formviews, UserControls etc. inside of other UserControls for reusability reasons. If you would have implemented all logic in your page and accessed these controls with recursive loops, it'll very difficult to refactor that. If you have implemented your logic and access methods via the event-handlers(f.e. RowDataBound of GridView), it'll be much simpler and less error-prone.

How can I share Jupyter notebooks with non-programmers?

Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.

frequent issues arising in android view, Error parsing XML: unbound prefix

You just need to add proper name space in your root tag . xmlns:android="http://schemas.android.com/apk/res/android" Android elemets are declared in this name space.Its same as importing class or package.

Expression ___ has changed after it was checked

Can't you use ngOnInit because you just changing the member variable message?

If you want to access a reference to a child component @ViewChild(ChildComponent), you indeed need to wait for it with ngAfterViewInit.

A dirty fix is to call the updateMessage() in the next event loop with e.g. setTimeout.

ngAfterViewInit() {
  setTimeout(() => {
    this.updateMessage();
  }, 1);
}

Error: Could not find or load main class in intelliJ IDE

Elaborating on Brad Turek's solution... One of the default IntelliJ Java project templates expects a file called Main defining the class Main and main() method entry point. If the method is contained in another file (and class), change the Run configuration:

Run Configuration Window

  1. With the project open in IntelliJ, use the Run:Edit Configurations... menu to open the build configuration window.
  2. If the entry for Main class doesn't list the name of your file containing the class exposing the main() entry method, enter the correct file name. (The configuration in the image is wrong, which is why it's red in the configuration panel.)
  3. My main() entry method is in the class (and file) ScrabbleTest. So changing Main class: to ScrabbleTest fixes the runtime error.

As others have noted you have to ReBuild using the new configuration. I am using a package, but that doesn't seem to make a difference IME. Hope this helps.

highlight the navigation menu for the current page

Css classes are here

<style type="text/css">
.mymenu
{
    background-color: blue;
    color: white;
}
.newmenu
{
    background-color: red;
    color: white;
}
</style>

Make your HTML like this, Set url as id

  <div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
  <div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>

Here write javascript, put this javascript after the HTML code.

    function menuHighlight() {
       var url = window.location.href;
       $('#'+tabst).addClass('new_current');
    }
    menuHighlight();

How to update multiple columns in single update statement in DB2

The update statement in all versions of SQL looks like:

update table
    set col1 = expr1,
        col2 = expr2,
        . . .
        coln = exprn
    where some condition

So, the answer is that you separate the assignments using commas and don't repeat the set statement.

What is the scope of variables in JavaScript?

TLDR

JavaScript has lexical (also called static) scoping and closures. This means you can tell the scope of an identifier by looking at the source code.

The four scopes are:

  1. Global - visible by everything
  2. Function - visible within a function (and its sub-functions and blocks)
  3. Block - visible within a block (and its sub-blocks)
  4. Module - visible within a module

Outside of the special cases of global and module scope, variables are declared using var (function scope), let (block scope), and const (block scope). Most other forms of identifier declaration have block scope in strict mode.

Overview

Scope is the region of the codebase over which an identifier is valid.

A lexical environment is a mapping between identifier names and the values associated with them.

Scope is formed of a linked nesting of lexical environments, with each level in the nesting corresponding to a lexical environment of an ancestor execution context.

These linked lexical environments form a scope "chain". Identifier resolution is the process of searching along this chain for a matching identifier.

Identifier resolution only occurs in one direction: outwards. In this way, outer lexical environments cannot "see" into inner lexical environments.

There are three pertinent factors in deciding the scope of an identifier in JavaScript:

  1. How an identifier was declared
  2. Where an identifier was declared
  3. Whether you are in strict mode or non-strict mode

Some of the ways identifiers can be declared:

  1. var, let and const
  2. Function parameters
  3. Catch block parameter
  4. Function declarations
  5. Named function expressions
  6. Implicitly defined properties on the global object (i.e., missing out var in non-strict mode)
  7. import statements
  8. eval

Some of the locations identifiers can be declared:

  1. Global context
  2. Function body
  3. Ordinary block
  4. The top of a control structure (e.g., loop, if, while, etc.)
  5. Control structure body
  6. Modules

Declaration Styles

var

Identifiers declared using var have function scope, apart from when they are declared directly in the global context, in which case they are added as properties on the global object and have global scope. There are separate rules for their use in eval functions.

let and const

Identifiers declared using let and const have block scope, apart from when they are declared directly in the global context, in which case they have global scope.

Note: let, const and var are all hoisted. This means that their logical position of definition is the top of their enclosing scope (block or function). However, variables declared using let and const cannot be read or assigned to until control has passed the point of declaration in the source code. The interim period is known as the temporal dead zone.

_x000D_
_x000D_
function f() {
    function g() {
        console.log(x)
    }
    let x = 1
    g()
}
f() // 1 because x is hoisted even though declared with `let`!
_x000D_
_x000D_
_x000D_

Function parameter names

Function parameter names are scoped to the function body. Note that there is a slight complexity to this. Functions declared as default arguments close over the parameter list, and not the body of the function.

Function declarations

Function declarations have block scope in strict mode and function scope in non-strict mode. Note: non-strict mode is a complicated set of emergent rules based on the quirky historical implementations of different browsers.

Named function expressions

Named function expressions are scoped to themselves (e.g., for the purpose of recursion).

Implicitly defined properties on the global object

In non-strict mode, implicitly defined properties on the global object have global scope, because the global object sits at the top of the scope chain. In strict mode, these are not permitted.

eval

In eval strings, variables declared using var will be placed in the current scope, or, if eval is used indirectly, as properties on the global object.

Examples

The following will throw a ReferenceError because the namesx, y, and z have no meaning outside of the function f.

_x000D_
_x000D_
function f() {
    var x = 1
    let y = 1
    const z = 1
}
console.log(typeof x) // undefined (because var has function scope!)
console.log(typeof y) // undefined (because the body of the function is a block)
console.log(typeof z) // undefined (because the body of the function is a block)
_x000D_
_x000D_
_x000D_

The following will throw a ReferenceError for y and z, but not for x, because the visibility of x is not constrained by the block. Blocks that define the bodies of control structures like if, for, and while, behave similarly.

_x000D_
_x000D_
{
    var x = 1
    let y = 1
    const z = 1
}
console.log(x) // 1
console.log(typeof y) // undefined because `y` has block scope
console.log(typeof z) // undefined because `z` has block scope
_x000D_
_x000D_
_x000D_

In the following, x is visible outside of the loop because var has function scope:

_x000D_
_x000D_
for(var x = 0; x < 5; ++x) {}
console.log(x) // 5 (note this is outside the loop!)
_x000D_
_x000D_
_x000D_

...because of this behavior, you need to be careful about closing over variables declared using var in loops. There is only one instance of variable x declared here, and it sits logically outside of the loop.

The following prints 5, five times, and then prints 5 a sixth time for the console.log outside the loop:

_x000D_
_x000D_
for(var x = 0; x < 5; ++x) {
    setTimeout(() => console.log(x)) // closes over the `x` which is logically positioned at the top of the enclosing scope, above the loop
}
console.log(x) // note: visible outside the loop
_x000D_
_x000D_
_x000D_

The following prints undefined because x is block-scoped. The callbacks are run one by one asynchronously. New behavior for let variables means that each anonymous function closed over a different variable named x (unlike it would have done with var), and so integers 0 through 4 are printed.:

_x000D_
_x000D_
for(let x = 0; x < 5; ++x) {
    setTimeout(() => console.log(x)) // `let` declarations are re-declared on a per-iteration basis, so the closures capture different variables
}
console.log(typeof x) // undefined
_x000D_
_x000D_
_x000D_

The following will NOT throw a ReferenceError because the visibility of x is not constrained by the block; it will, however, print undefined because the variable has not been initialised (because of the if statement).

_x000D_
_x000D_
if(false) {
    var x = 1
}
console.log(x) // here, `x` has been declared, but not initialised
_x000D_
_x000D_
_x000D_

A variable declared at the top of a for loop using let is scoped to the body of the loop:

_x000D_
_x000D_
for(let x = 0; x < 10; ++x) {} 
console.log(typeof x) // undefined, because `x` is block-scoped
_x000D_
_x000D_
_x000D_

The following will throw a ReferenceError because the visibility of x is constrained by the block:

_x000D_
_x000D_
if(false) {
    let x = 1
}
console.log(typeof x) // undefined, because `x` is block-scoped
_x000D_
_x000D_
_x000D_

Variables declared using var, let or const are all scoped to modules:

// module1.js

var x = 0
export function f() {}

//module2.js

import f from 'module1.js'

console.log(x) // throws ReferenceError

The following will declare a property on the global object because variables declared using var within the global context are added as properties to the global object:

_x000D_
_x000D_
var x = 1
console.log(window.hasOwnProperty('x')) // true
_x000D_
_x000D_
_x000D_

let and const in the global context do not add properties to the global object, but still have global scope:

_x000D_
_x000D_
let x = 1
console.log(window.hasOwnProperty('x')) // false
_x000D_
_x000D_
_x000D_

Function parameters can be considered to be declared in the function body:

_x000D_
_x000D_
function f(x) {}
console.log(typeof x) // undefined, because `x` is scoped to the function
_x000D_
_x000D_
_x000D_

Catch block parameters are scoped to the catch-block body:

_x000D_
_x000D_
try {} catch(e) {}
console.log(typeof e) // undefined, because `e` is scoped to the catch block
_x000D_
_x000D_
_x000D_

Named function expressions are scoped only to the expression itself:

_x000D_
_x000D_
(function foo() { console.log(foo) })()
console.log(typeof foo) // undefined, because `foo` is scoped to its own expression
_x000D_
_x000D_
_x000D_

In non-strict mode, implicitly defined properties on the global object are globally scoped. In strict mode, you get an error.

_x000D_
_x000D_
x = 1 // implicitly defined property on the global object (no "var"!)

console.log(x) // 1
console.log(window.hasOwnProperty('x')) // true
_x000D_
_x000D_
_x000D_

In non-strict mode, function declarations have function scope. In strict mode, they have block scope.

_x000D_
_x000D_
'use strict'
{
    function foo() {}
}
console.log(typeof foo) // undefined, because `foo` is block-scoped
_x000D_
_x000D_
_x000D_

How it works under the hood

Scope is defined as the lexical region of code over which an identifier is valid.

In JavaScript, every function-object has a hidden [[Environment]] reference that is a reference to the lexical environment of the execution context (stack frame) within which it was created.

When you invoke a function, the hidden [[Call]] method is called. This method creates a new execution context and establishes a link between the new execution context and the lexical environment of the function-object. It does this by copying the [[Environment]] value on the function-object, into an outer reference field on the lexical environment of the new execution context.

Note that this link between the new execution context and the lexical environment of the function object is called a closure.

Thus, in JavaScript, scope is implemented via lexical environments linked together in a "chain" by outer references. This chain of lexical environments is called the scope chain, and identifier resolution occurs by searching up the chain for a matching identifier.

Find out more.

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.

var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

No need for array. Just use something like this:

Sub ARRAYER()

    Dim Rng As Range
    Dim Number_of_Sims As Long
    Dim i As Long
    Number_of_Sims = 10

    Set Rng = Range("C4:G4")
    For i = 1 To Number_of_Sims
       Rng.Offset(i, 0).Value = Rng.Value
       Worksheets("Sheetname").Calculate   'replacing Sheetname with name of your sheet
    Next

End Sub

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

This error occurs when the client URL and server URL don't match, including the port number. In this case you need to enable your service for CORS which is cross origin resource sharing.

If you are hosting a Spring REST service then you can find it in the blog post CORS support in Spring Framework.

If you are hosting a service using a Node.js server then

  1. Stop the Node.js server.
  2. npm install cors --save
  3. Add following lines to your server.js

    var cors = require('cors')
    
    app.use(cors()) // Use this after the variable declaration
    

Python error "ImportError: No module named"

For me, it was something really stupid. I installed the library using pip3 install but was running my program as python program.py as opposed to python3 program.py.

How to create a data file for gnuplot?

This error usually means the file couldn't be found.

Can you see the file from the command line?

  1. Try specifying the full pathname.
  2. check line ending type (use 0x0d).
  3. is file open in another program?
  4. do you have read access to it?

Warning :-Presenting view controllers on detached view controllers is discouraged

Try this code

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:<your ViewController object>];

[self.view.window.rootViewController presentViewController:navigationController animated:YES completion:nil];

Show loading image while $.ajax is performed

You can add ajax start and complete event, this is work for when you click on button event

 $(document).bind("ajaxSend", function () {
            $(":button").html('<i class="fa fa-spinner fa-spin"></i> Loading');
            $(":button").attr('disabled', 'disabled');
        }).bind("ajaxComplete", function () {
            $(":button").html('<i class="fa fa-check"></i> Show');
            $(":button").removeAttr('disabled', 'disabled');
        });

Counting DISTINCT over multiple columns

Here's a shorter version without the subselect:

SELECT COUNT(DISTINCT DocumentId, DocumentSessionId) FROM DocumentOutputItems

It works fine in MySQL, and I think that the optimizer has an easier time understanding this one.

Edit: Apparently I misread MSSQL and MySQL - sorry about that, but maybe it helps anyway.

Error In PHP5 ..Unable to load dynamic library

My problem was solved by the following command

sudo apt-get install php5-mcrypt

I have

  • PHP 5.3.10-1ubuntu3.4 with Suhosin-Patch (cli)
  • Ubuntu Desktop 12.04
  • Mysql 5.5

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

It's not a big deal, it's pretty easy to switch between them. MSTest being integrated isn't a big deal either, just grab testdriven.net.

Like the previous person said pick a mocking framework, my favourite at the moment is Moq.

ios app maximum memory budget

Working with the many answers above, I have implemented Apples new method os_proc_available_memory() for iOS 13+ coupled with NSByteCountFormatter which offers a number of useful formatting options for nicer output of the memory:

#include <os/proc.h>

....

- (NSString *)memoryStringForBytes:(unsigned long long)memoryBytes {
    NSByteCountFormatter *byteFormatter = [[NSByteCountFormatter alloc] init];
    byteFormatter.allowedUnits = NSByteCountFormatterUseGB;
    byteFormatter.countStyle = NSByteCountFormatterCountStyleMemory;
    NSString *memoryString = [byteFormatter stringFromByteCount:memoryBytes];
    return memoryString;
}

- (void)memoryLoggingOutput {
    if (@available(iOS 13.0, *)) {
        NSLog(@"Physical memory available: %@", [self memoryStringForBytes:[NSProcessInfo processInfo].physicalMemory]);
        NSLog(@"Memory A (brackets): %@", [self memoryStringForBytes:(long)os_proc_available_memory()]);
        NSLog(@"Memory B (no brackets): %@", [self memoryStringForBytes:(long)os_proc_available_memory]);
    }
}

Important note: Do not forget the () at the end. I have included both NSLog options in in the memoryLoggingOutput method because it does not warn you that they are missing and failure to include the brackets returns an unexpected yet constant result.

The string returned from the method memoryStringForBytes outputs values like so:

NSLog(@"%@", [self memoryStringForBytes:(long)os_proc_available_memory()]); // 1.93 GB
// 2 seconds later
NSLog(@"%@", [self memoryStringForBytes:(long)os_proc_available_memory()]); // 1.84 GB

How do I comment on the Windows command line?

Powershell

For powershell, use #:

PS C:\> echo foo # This is a comment
foo

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

How to change current Theme at runtime in Android

We have to set theme before calling 'super.onCreate()' and 'setContentView()' method.

Check out this link for applying new theme to whole application at runtime.

How to suppress Update Links warning?

I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:

while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
   controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd

So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.

How do I remove a single breakpoint with GDB?

You can delete all breakpoints using

del <start_breakpoint_num> - <end_breakpoint_num>

To view the start_breakpoint_num and end_breakpoint_num use:

info break

How do I perform query filtering in django templates

The other option is that if you have a filter that you always want applied, to add a custom manager on the model in question which always applies the filter to the results returned.

A good example of this is a Event model, where for 90% of the queries you do on the model you are going to want something like Event.objects.filter(date__gte=now), i.e. you're normally interested in Events that are upcoming. This would look like:

class EventManager(models.Manager):
    def get_query_set(self):
        now = datetime.now()
        return super(EventManager,self).get_query_set().filter(date__gte=now)

And in the model:

class Event(models.Model):
    ...
    objects = EventManager()

But again, this applies the same filter against all default queries done on the Event model and so isn't as flexible some of the techniques described above.

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

How to make input type= file Should accept only pdf and xls

Unfortunately, there is no guaranteed way to do it at time of selection.

Some browsers support the accept attribute for input tags. This is a good start, but cannot be relied upon completely.

<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />

You can use a cfinput and run a validation to check the file extension at submission, but not the mime-type. This is better, but still not fool-proof. Files on OSX often have no file extensions or users could maliciously mislabel the file types.

ColdFusion's cffile can check the mime-type using the contentType property of the result (cffile.contentType), but that can only be done after the upload. This is your best bet, but is still not 100% safe as mime-types could still be wrong.

Getting execute permission to xp_cmdshell

For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. In addition if you forgot one of the steps I have listed the error that will be thrown.

  1. Enable the xp_cmdshell procedure

    Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.*

  2. Create a login for the non-sysadmin user that has public access to the master database

    Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*

  3. Grant EXEC permission on the xp_cmdshell stored procedure

    Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*

  4. Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

    Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1 The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.*

It would seem from your error that either step 2 or 3 was missed. I am not familiar with clusters to know if there is anything particular to that setup.

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

I moved Android folder path to another path and taked this error.

I resolved to this problem in below.

I was changed to Gradle path in system variables. But not path in user variables. You must change to path in system variables

Screenshot this

Alternative Screenshot this

Spring boot - Not a managed type

I had some problem while migrating from Spring boot 1.3.x to 1.5, I got it working after updating entity package at EntityManagerFactory bean

  @Bean(name="entityManagerFactoryDef")
  @Primary
  public LocalContainerEntityManagerFactoryBean defaultEntityManager() {
      Map map = new HashMap();
      map.put("hibernate.default_schema", env.getProperty("spring.datasource.username"));
      map.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
      LocalContainerEntityManagerFactoryBean em = createEntityManagerFactoryBuilder(jpaVendorProperties())
              .dataSource(primaryDataSource()).persistenceUnit("default").properties(map).build();
      em.setPackagesToScan("com.simple.entity");
      em.afterPropertiesSet();
      return em;
  }

This bean referred in Application class as below

@SpringBootApplication
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryDef")
public class SimpleApp {

}

iPhone 5 CSS media query

You should maybe down the "-webkit-min-device-pixel-ratio" to 1.5 to catch all iPhones ?

@media only screen and (max-device-width: 480px), only screen and (min-device-width: 640px) and (max-device-width: 1136px) and (-webkit-min-device-pixel-ratio: 1.5) {
/* iPhone only */
}

Using "&times" word in html changes to ×

You need to escape the ampersand:

<div class="test">&amp;times</div>

&times means a multiplication sign. (Technically it should be &times; but lenient browsers let you omit the ;.)

How do I upload a file with metadata using a REST web service?

One way to approach the problem is to make the upload a two phase process. First, you would upload the file itself using a POST, where the server returns some identifier back to the client (an identifier might be the SHA1 of the file contents). Then, a second request associates the metadata with the file data:

{
    "Name": "Test",
    "Latitude": 12.59817,
    "Longitude": 52.12873,
    "ContentID": "7a788f56fa49ae0ba5ebde780efe4d6a89b5db47"
}

Including the file data base64 encoded into the JSON request itself will increase the size of the data transferred by 33%. This may or may not be important depending on the overall size of the file.

Another approach might be to use a POST of the raw file data, but include any metadata in the HTTP request header. However, this falls a bit outside basic REST operations and may be more awkward for some HTTP client libraries.

Warning: Permanently added the RSA host key for IP address

The IP addresses have changed again.

github publishes the list of used IP addresses here so you can check the IP address in your message against github's list:

https://help.github.com/articles/about-github-s-ip-addresses/

Or more precisely:

https://api.github.com/meta

It looks like this (as I write this answer!):

verifiable_password_authentication  true
github_services_sha "4159703d573ee6f602e304ed25b5862463a2c73d"
hooks   
0   "192.30.252.0/22"
1   "185.199.108.0/22"
git 
0   "192.30.252.0/22"
1   "185.199.108.0/22"
2   "18.195.85.27/32"
3   "18.194.104.89/32"
4   "35.159.8.160/32"
pages   
0   "192.30.252.153/32"
1   "192.30.252.154/32"
importer    
0   "54.87.5.173"
1   "54.166.52.62"
2   "23.20.92.3"

If you are unsure whether your IP address is contained in the above list use an CIDR calculator like http://www.subnet-calculator.com/cidr.php to show the valid IP range.

E. g. for 140.82.112.0/20 the IP range is 140.82.112.0 - 140.82.127.255

MySQL CURRENT_TIMESTAMP on create and on update

I think you maybe want ts_create as datetime (so rename -> dt_create) and only ts_update as timestamp? This will ensure it remains unchanging once set.

My understanding is that datetime is for manually-controlled values, and timestamp's a bit "special" in that MySQL will maintain it for you. In this case, datetime is therefore a good choice for ts_create.

selecting unique values from a column

Use this query to get values

SELECT * FROM `buy` group by date order by date DESC

How to parse this string in Java?

String.split(String regex) is convenient but if you don't need the regular expression handling then go with the substring(..) example, java.util.StringTokenizer or use Apache commons lang 1. The performance difference when not using regular expressions can be a gain of 1 to 2 orders of magnitude in speed.

How to use a variable in the replacement side of the Perl substitution operator?

On the replacement side, you must use $1, not \1.

And you can only do what you want by making replace an evalable expression that gives the result you want and telling s/// to eval it with the /ee modifier like so:

$find="start (.*) end";
$replace='"foo $1 bar"';

$var = "start middle end";
$var =~ s/$find/$replace/ee;

print "var: $var\n";

To see why the "" and double /e are needed, see the effect of the double eval here:

$ perl
$foo = "middle";
$replace='"foo $foo bar"';
print eval('$replace'), "\n";
print eval(eval('$replace')), "\n";
__END__
"foo $foo bar"
foo middle bar

(Though as ikegami notes, a single /e or the first /e of a double e isn't really an eval(); rather, it tells the compiler that the substitution is code to compile, not a string. Nonetheless, eval(eval(...)) still demonstrates why you need to do what you need to do to get /ee to work as desired.)

How to count rows with SELECT COUNT(*) with SQLAlchemy?

If you are using the SQL Expression Style approach there is another way to construct the count statement if you already have your table object.

Preparations to get the table object. There are also different ways.

import sqlalchemy

database_engine = sqlalchemy.create_engine("connection string")

# Populate existing database via reflection into sqlalchemy objects
database_metadata = sqlalchemy.MetaData()
database_metadata.reflect(bind=database_engine)

table_object = database_metadata.tables.get("table_name") # This is just for illustration how to get the table_object                    

Issuing the count query on the table_object

query = table_object.count()
# This will produce something like, where id is a primary key column in "table_name" automatically selected by sqlalchemy
# 'SELECT count(table_name.id) AS tbl_row_count FROM table_name'

count_result = database_engine.scalar(query)

HTML form input tag name element array with JavaScript

document.form.p_id.length ... not count().

You really should give your form an id

<form id="myform">

Then refer to it using:

var theForm = document.getElementById("myform");

Then refer to the elements like:

for(var i = 0; i < theForm.p_id.length; i++){

Check if date is in the past Javascript

var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}

Android Studio drawable folders

In order to create the drawable directory structure for different image densities, You need to:

  1. Right-click on the \res folder
  2. Select new > android resource directory
  3. In the New Resource Directory window, under Available qualifiers resource type section, select drawable.

  4. Add density and choose the appropriate size.

Class file has wrong version 52.0, should be 50.0

In your IntelliJ idea find tools.jar replace it with tools.jar from yout JDK8

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

I had the same warning using the raster package.

> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb

The solution is really simple and consist in increasing the storage capacity of R, here the code line:

##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000    
## I did this to increase my storage capacity to 7GB

Hopefully, this will help you to solve the problem Cheers

How to use ternary operator in razor (specifically on HTML attributes)?

I have a field named IsActive in table rows that's True when an item has been deleted. This code applies a CSS class named strikethrough only to deleted items. You can see how it uses the C# Ternary Operator:

<tr class="@(@businesstypes.IsActive ? "" : "strikethrough")">

Counting the number of elements with the values of x in a vector

If you want to count the number of appearances subsequently, you can make use of the sapply function:

index<-sapply(1:length(numbers),function(x)sum(numbers[1:x]==numbers[x]))
cbind(numbers, index)

Output:

        numbers index
 [1,]       4     1
 [2,]      23     1
 [3,]       4     2
 [4,]      23     2
 [5,]       5     1
 [6,]      43     1
 [7,]      54     1
 [8,]      56     1
 [9,]     657     1
[10,]      67     1
[11,]      67     2
[12,]     435     1
[13,]     453     1
[14,]     435     2
[15,]     324     1
[16,]      34     1
[17,]     456     1
[18,]      56     2
[19,]     567     1
[20,]      65     1
[21,]      34     2
[22,]     435     3

What's the correct way to communicate between controllers in AngularJS?

Since defineProperty has browser compatibility issue, I think we can think about using a service.

angular.module('myservice', [], function($provide) {
    $provide.factory('msgBus', ['$rootScope', function($rootScope) {
        var msgBus = {};
        msgBus.emitMsg = function(msg) {
        $rootScope.$emit(msg);
        };
        msgBus.onMsg = function(msg, scope, func) {
            var unbind = $rootScope.$on(msg, func);
            scope.$on('$destroy', unbind);
        };
        return msgBus;
    }]);
});

and use it in controller like this:

  • controller 1

    function($scope, msgBus) {
        $scope.sendmsg = function() {
            msgBus.emitMsg('somemsg')
        }
    }
    
  • controller 2

    function($scope, msgBus) {
        msgBus.onMsg('somemsg', $scope, function() {
            // your logic
        });
    }
    

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

Me too got the same error but in my case I was calling url with blank spaces.

Then, I fixed it by parsing like below.

String url = "Your URL Link";

url = url.replaceAll(" ", "%20");

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                            new com.android.volley.Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                ...
                                ...
                                ...

Cannot issue data manipulation statements with executeQuery()

Use executeUpdate() to issue data manipulation statements. executeQuery() is only meant for SELECT queries (i.e. queries that return a result set).

How do I set up Android Studio to work completely offline?

Not sure if it was removed before, I heard it was kinda buggy in 0.5.8 but in AS 0.5.9 the settings is there:

Gradle > Global Gradle settings > Offline work

How to disable a button when an input is empty?

Using constants allows to combine multiple fields for verification:

_x000D_
_x000D_
class LoginFrm extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = {_x000D_
      email: '',_x000D_
      password: '',_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  handleEmailChange = (evt) => {_x000D_
    this.setState({ email: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handlePasswordChange = (evt) => {_x000D_
    this.setState({ password: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handleSubmit = () => {_x000D_
    const { email, password } = this.state;_x000D_
    alert(`Welcome ${email} password: ${password}`);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const { email, password } = this.state;_x000D_
    const enabled =_x000D_
          email.length > 0 &&_x000D_
          password.length > 0;_x000D_
    return (_x000D_
      <form onSubmit={this.handleSubmit}>_x000D_
        <input_x000D_
          type="text"_x000D_
          placeholder="Email"_x000D_
          value={this.state.email}_x000D_
          onChange={this.handleEmailChange}_x000D_
        />_x000D_
        _x000D_
        <input_x000D_
          type="password"_x000D_
          placeholder="Password"_x000D_
          value={this.state.password}_x000D_
          onChange={this.handlePasswordChange}_x000D_
        />_x000D_
        <button disabled={!enabled}>Login</button>_x000D_
      </form>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<LoginFrm />, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<body>_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to determine previous page URL in Angular?

I'm using Angular 8 and the answer of @franklin-pious solves the problem. In my case, get the previous url inside a subscribe cause some side effects if it's attached with some data in the view.

The workaround I used was to send the previous url as an optional parameter in the route navigation.

this.router.navigate(['/my-previous-route', {previousUrl: 'my-current-route'}])

And to get this value in the component:

this.route.snapshot.paramMap.get('previousUrl')

this.router and this.route are injected inside the constructor of each component and are imported as @angular/router members.

import { Router, ActivatedRoute }   from '@angular/router';

.htaccess rewrite to redirect root URL to subdirectory

Another alternative if you want to rewrite the URL and hide the original URL:

RewriteEngine on
RewriteRule ^(.*)$ /store/$1 [L]

With this, if you for example type http://www.example.com/product.php?id=4, it will transparently open the file at http://www.example.com/store/product.php?id=4 but without showing to the user the full url.

Protect image download

As other answers said, if you can see it you can copy/download it.

To add up to the other answers, just for your information, you can add invisible or tricky watermarks to your images: http://www.cgrats.com/create-an-invisible-watermark-in-photoshop.html (just an example, there are more techniques, just google for invisible watermarks)

Anyway if you want to prove the ownership of your image a good way is to have a bigger resolution copy for yourself, and always publish a lower resolution / size one. Or publish it also on a "public" media like ... deviantart or flickr or something where people can't change the upload date. This way you can prove you had that image before anybody else

How to simulate browsing from various locations?

DNS info is cached at many places. If you have a server in Europe you may want to try to proxy through it

Text to speech(TTS)-Android

Try this, its simple : **speakout.xml : **

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db"
android:weightSum="1"
android:orientation="vertical" >
<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight=".1"
android:gravity="center"
android:padding="3dp"
android:text="Speak Out!!!"
android:textColor="#fff"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtTexttoSpeak"
android:layout_width="match_parent"
android:layout_weight=".5"
android:background="#fff"
android:textColor="#2c3e50"
android:text="Hi there!!!"
android:padding="5dp"
android:gravity="top|left"
android:layout_height="0dp"/>
<Button
android:id="@+id/btnspeakout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#e74c3c"
android:textColor="#fff"
android:text="SPEAK OUT"/>
</LinearLayout>

And Your SpeakOut.java :

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SpeakOut extends Activity implements OnInitListener {
private TextToSpeech repeatTTS;
Button btnspeakout;
EditText edtTexttoSpeak;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.speakout);
    btnspeakout = (Button) findViewById(R.id.btnspeakout);
    edtTexttoSpeak = (EditText) findViewById(R.id.edtTexttoSpeak);
    repeatTTS = new TextToSpeech(this, this);
    btnspeakout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            repeatTTS.speak(edtTexttoSpeak.getText().toString(),
            TextToSpeech.QUEUE_FLUSH, null);
        }
    });
}

@Override
    public void onInit(int arg0) {
        // TODO Auto-generated method stub
    }
}

SOURCE Parallelcodes.com's Post

How do I find the length/number of items present for an array?

Do you mean how long is the array itself, or how many customerids are in it?

Because the answer to the first question is easy: 5 (or if you don't want to hard-code it, Ben Stott's answer).

But the answer to the other question cannot be automatically determined. Presumably you have allocated an array of length 5, but will initially have 0 customer IDs in there, and will put them in one at a time, and your question is, "how many customer IDs have I put into the array?"

C can't tell you this. You will need to keep a separate variable, int numCustIds (for example). Every time you put a customer ID into the array, increment that variable. Then you can tell how many you have put in.

How to initialize a list of strings (List<string>) with many string values

List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

Should C# or C++ be chosen for learning Games Programming (consoles)?

C++ is the lingua franca of the console game industry. For better or worse, you must know it to be a professional console game programmer.

Difference between List, List<?>, List<T>, List<E>, and List<Object>

I would advise reading Java puzzlers. It explains inheritance, generics, abstractions, and wildcards in declarations quite well. http://www.javapuzzlers.com/

Capturing browser logs with Selenium WebDriver using Java

Add cast RemoteWebDriver to driver initialize and you will have the .setLogLevel method:

import java.util.logging.Level;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;

public class PrintLogTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/Users/.../chromedriver");
        WebDriver driver = new ChromeDriver();

        //here
        ((RemoteWebDriver) driver).setLogLevel(Level.INFO);

        driver.get("https://google.com/");
        driver.findElement(By.name("q")).sendKeys("automation test");
        driver.quit();
    }
}

Example output:

Jun 15, 2020 4:27:04 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executing: get [430aec21a9beb6340a4185c4ea6a693d, get {url=https://google.com/}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executed: [430aec21a9beb6340a4185c4ea6a693d, get {url=https://google.com/}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executing: findElement [430aec21a9beb6340a4185c4ea6a693d, findElement {using=name, value=q}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executed: [430aec21a9beb6340a4185c4ea6a693d, findElement {using=name, value=q}]
...
...

At least I've tried it on ChromeDriver() and FirefoxDriver() and it working fine.

Waiting for HOME ('android.process.acore') to be launched

SOLUTION:

Run the emulator from the command line:

sdk/tools> ./emulator-x86 -avd <DeviceName> -partition-size 1024 -gpu on

Then I launched the app from the command line as well (using built-in Cordova/PhoneGap tools):

myapp/cordova> ./run

BACKGROUND

I believe this is some sort of hardware compatibility issue. I came across this problem when following the PhoneGap 2.4.0 Getting Started Instructions. I followed their advice to install the Intel Hardware Accelerated Execution Manager, and I think this is the source of my trouble. Eclipse uses the emulator64-x86 program (in the sdk/tools folder) to launch the emulator. I could not find any way inside of Eclipse to change this but I found by following the "Tips & Tricks" section of the Intel HAXM web page that I could get the emulator to run successfully from the command line by using the emulator-x86 program instead. I'm not sure why the emulator64-x86 program doesn't work on my system. I confirmed at the Apple website that I do have a 64-bit processor.

My system:

  • OSX 10.6.8
  • 2x2.26 GHx Quad-core Intel Xeon
  • 6 GB RAM
  • ADT v21.1.0-569685
  • Eclipse 3.8.0

My AVD:

  • Device: Nexus One
  • Target: Android 4.2.2 - API Level 17
  • CPU: Intel Atom (x86)
  • RAM: 512
  • Internal Storage: 256
  • SD Card: 128

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

The raw_json_encode() function above did not solve me the problem (for some reason, the callback function raised an error on my PHP 5.2.5 server).

But this other solution did actually work.

https://www.experts-exchange.com/questions/28628085/json-encode-fails-with-special-characters.html

Credits should go to Marco Gasi. I just call his function instead of calling json_encode():

function jsonRemoveUnicodeSequences( $json_struct )
{ 
    return preg_replace( "/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode( $json_struct ) );
}

Node.js: printing to console without a trailing newline?

I got the following error when using strict mode:

Node error: "Octal literals are not allowed in strict mode."

The following solution works (source):

process.stdout.write("received: " + bytesReceived + "\x1B[0G");

smtpclient " failure sending mail"

apparently this problem got solved just by increasing queue size on my 3rd party smtp server. but the answer by Nip sounds like it is fairly usefull too

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Stacking DIVs on top of each other?

Position the outer div however you want, then position the inner divs using absolute. They'll all stack up.

_x000D_
_x000D_
.inner {_x000D_
  position: absolute;_x000D_
}
_x000D_
<div class="outer">_x000D_
   <div class="inner">1</div>_x000D_
   <div class="inner">2</div>_x000D_
   <div class="inner">3</div>_x000D_
   <div class="inner">4</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

sql try/catch rollback/commit - preventing erroneous commit after rollback

In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.

In your second example, I agree with other commenters. Using the success flag is unnecessary.

I consider the following approach to be, essentially, a light weight best practice approach.

If you want to see how it handles an exception, change the value on the second insert from 255 to 256.

CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT  INTO #TEMP( ID ) VALUES  ( 1 )

BEGIN TRY
    BEGIN TRANSACTION

    INSERT  INTO #TEMP( ID ) VALUES  ( 2 )
    INSERT  INTO #TEMP( ID ) VALUES  ( 255 )

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    DECLARE 
        @ErrorMessage NVARCHAR(4000),
        @ErrorSeverity INT,
        @ErrorState INT;
    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();
    RAISERROR (
        @ErrorMessage,
        @ErrorSeverity,
        @ErrorState    
        );
    ROLLBACK TRANSACTION
END CATCH

SET NOCOUNT ON

SELECT ID
FROM #TEMP

DROP TABLE #TEMP

How do I adb pull ALL files of a folder present in SD Card

Please try with just giving the path from where you want to pull the files I just got the files from sdcard like

adb pull sdcard/

do NOT give * like to broaden the search or to filter out. ex: adb pull sdcard/*.txt --> this is invalid.

just give adb pull sdcard/

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I found I was getting the same error because I had forgot to create referential constraint after creating an association between two entities.

Differences between arm64 and aarch64

AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.

So AArch64 and ARM64 refer to the same thing.

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

Instead of specifying a deployment target in pod post install, you can delete the pod deployment target, which causes the deployment target to be inherited from the podfile platform.

You may need to run pod install for the effect to take place.

platform :ios, '12.0'

  post_install do |installer|
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
      end
    end
  end

Convert a string date into datetime in Oracle

Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') and all I received was 2017-02-20 the time disappeared

My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') now the time doesn't disappear.

Avoid printStackTrace(); use a logger call instead

Let's talk in from company concept. Log gives you flexible levels (see Difference between logger.info and logger.debug). Different people want to see different levels, like QAs, developers, business people. But e.printStackTrace() will print out everything. Also, like if this method will be restful called, this same error may print several times. Then the Devops or Tech-Ops people in your company may be crazy because they will receive the same error reminders. I think a better replacement could be log.error("errors happend in XXX", e) This will also print out whole information which is easy reading than e.printStackTrace()

com.sun.jdi.InvocationException occurred invoking method

In my case it was due to the object reference getting stale. I was automating my application using selenium webdriver, so i type something into a text box and then it navigates to another page, so while i come back on the previous page , that object gets stale. So this was causing the exception, I handled it by again initialising the elements - PageFactory.initElements(driver, Test.class;

Ways to eliminate switch in code

Use a language that doesn't come with a built-in switch statement. Perl 5 comes to mind.

Seriously though, why would you want to avoid it? And if you have good reason to avoid it, why not simply avoid it then?

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

Present and dismiss modal view controller

Swift

self.dismissViewControllerAnimated(true, completion: nil)

How to change the height of a div dynamically based on another div using css?

By specifying the positions we can achieve this,

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  position:relative;
  overflow:auto;
}
.div2 {
  width:150px;
  height:auto;
  background-color: #F4A460;  
  float:left;
}
.div3 {
  width:150px;
  height:100%;
  position:absolute;
  right:0px;
  background-color: #FFFFE0;  
  float:right;
}

but it is not possible to achieve this using float.

Multi-gradient shapes

You can layer gradient shapes in the xml using a layer-list. Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)

<!-- Normal state. -->
<item>
    <layer-list>
        <item>  
            <shape>
                <gradient 
                    android:startColor="@color/grey_light"
                    android:endColor="@color/grey_dark"
                    android:type="linear"
                    android:angle="270"
                    android:centerColor="@color/grey_mediumtodark" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
        <item>  
            <shape>
                <gradient 
                    android:startColor="#00666666"
                    android:endColor="#77666666"
                    android:type="radial"
                    android:gradientRadius="200"
                    android:centerColor="#00666666"
                    android:centerX="0.5"
                    android:centerY="0" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
    </layer-list>
</item>

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

I had a similar issue where I had another class something like this:

public class Something {
  MyActivity myActivity;

  public Something(MyActivity myActivity) {
    this.myActivity=myActivity;
  }

  public void someMethod() {
   .
   .
   AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
   .
   AlertDialog alert = builder.create();
   alert.show();
  }
}

Worked fine most of the time, but sometimes it crashed with the same error. Then I realise that in MyActivity I had...

public class MyActivity extends Activity {
  public static Something something;

  public void someMethod() {
    if (something==null) {
      something=new Something(this);
    }
  }
}

Because I was holding the object as static, a second run of the code was still holding the original version of the object, and thus was still referring to the original Activity, which no long existed.

Silly stupid mistake, especially as I really didn't need to be holding the object as static in the first place...

UICollectionView Set number of columns

This answer is for swift 3.0 -->

first conform to the protocol :

 UICollectionViewDelegateFlowLayout

then add these methods :

    //this method is for the size of items      
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width/3
        let height : CGFloat = 160.0
        return CGSize(width: width, height: height)
    }
    //these methods are to configure the spacing between items

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0,0,0,0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

use Latin1_General_CS as your collation in your sql db

MySQL Check if username and password matches in Database

Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).

You can limit the whole search to one row by using Limit 0,1

SELECT COUNT(UserName)
  FROM TableName
 WHERE UserName = 'User' AND
       Password = 'Pass'
 LIMIT 0, 1