Programs & Examples On #Html5 animation

HTML5-ANIMATION is a way to animate HTML element with css or java script or both....

PHP get dropdown value and text

you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown

$("#dropdownid").val();   for value
$("#dropdownid").text(); for selected value

catch these into two variables and take it as inputs to ajax call for a php file

$.ajax 
   ({
     url:"callingphpfile.php",//url of fetching php  
     method:"POST", //type 
     data:"val1="+value+"&val2="+selectedtext,
     success:function(data) //return the data     
     {

}

and in php you can get it as

    if (isset($_POST["val1"])) {
    $val1= $_POST["val1"] ;
}

if (isset($_POST["val2"])) {
  $selectedtext= $_POST["val1"];
}

GDB: break if variable equal value

There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:

http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html

To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.

watch command is used to set a watchpoit for writing, while rwatch for reading, and awatch for reading/writing.

What are the differences between a multidimensional array and an array of arrays in C#?

In addition to the other answers, note that a multidimensional array is allocated as one big chunky object on the heap. This has some implications:

  1. Some multidimensional arrays will get allocated on the Large Object Heap (LOH) where their equivalent jagged array counterparts would otherwise not have.
  2. The GC will need to find a single contiguous free block of memory to allocate a multidimensional array, whereas a jagged array might be able to fill in gaps caused by heap fragmentation... this isn't usually an issue in .NET because of compaction, but the LOH doesn't get compacted by default (you have to ask for it, and you have to ask every time you want it).
  3. You'll want to look into <gcAllowVeryLargeObjects> for multidimensional arrays way before the issue will ever come up if you only ever use jagged arrays.

Excel compare two columns and highlight duplicates

I was trying to compare A-B columns and highlight equal text, but usinng the obove fomrulas some text did not match at all. So I used form (VBA macro to compare two columns and color highlight cell differences) codes and I modified few things to adapt it to my application and find any desired column (just by clicking it). In my case, I use large and different numbers of rows on each column. Hope this helps:

Sub ABTextCompare()

Dim Report As Worksheet
Dim i, j, colNum, vMatch As Integer
Dim lastRowA, lastRowB, lastRow, lastColumn As Integer
Dim ColumnUsage As String
Dim colA, colB, colC As String
Dim A, B, C As Variant

Set Report = Excel.ActiveSheet
vMatch = 1

'Select A and B Columns to compare
On Error Resume Next
 Set A = Application.InputBox(Prompt:="Select column to compare", Title:="Column A", Type:=8)
  If A Is Nothing Then Exit Sub
colA = Split(A(1).Address(1, 0), "$")(0)
 Set B = Application.InputBox(Prompt:="Select column being searched", Title:="Column B", Type:=8)
   If A Is Nothing Then Exit Sub
  colB = Split(B(1).Address(1, 0), "$")(0)
 'Select Column to show results
 Set C = Application.InputBox("Select column  to show results", "Results", Type:=8)
    If C Is Nothing Then Exit Sub
  colC = Split(C(1).Address(1, 0), "$")(0)

'Get Last Row
lastRowA = Report.Cells.Find("", Range(colA & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column A
lastRowB = Report.Cells.Find("", Range(colB & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column B

 Application.ScreenUpdating = False
'***************************************************
For i = 2 To lastRowA
      For j = 2 To lastRowB
          If Report.Cells(i, A.Column).Value <> "" Then
              If InStr(1, Report.Cells(j, B.Column).Value, Report.Cells(i, A.Column).Value, vbTextCompare) > 0 Then
                  vMatch = vMatch + 1
                  Report.Cells(i, A.Column).Interior.ColorIndex = 35 'Light green background
                  Range(colC & 1).Value = "Items Found"
                  Report.Cells(i, A.Column).Copy Destination:=Range(colC & vMatch)
                  Exit For
              Else
                  'Do Nothing
              End If
          End If
      Next j
  Next i
If vMatch = 1 Then
    MsgBox Prompt:="No Itmes Found", Buttons:=vbInformation
End If
'***************************************************
Application.ScreenUpdating = True

End Sub

Create nice column output in python

Transposing the columns like that is a job for zip:

>>> a = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
>>> list(zip(*a))
[('a', 'aaaaaaaaaa', 'a'), ('b', 'b', 'bbbbbbbbbb'), ('c', 'c', 'c')]

To find the required length of each column, you can use max:

>>> trans_a = zip(*a)
>>> [max(len(c) for c in b) for b in trans_a]
[10, 10, 1]

Which you can use, with suitable padding, to construct strings to pass to print:

>>> col_lenghts = [max(len(c) for c in b) for b in trans_a]
>>> padding = ' ' # You might want more
>>> padding.join(s.ljust(l) for s,l in zip(a[0], col_lenghts))
'a          b          c'

Shortcut to create properties in Visual Studio?

ReSharper offers property generation in its extensive feature set. (It's not cheap though, unless you're working on an open-source project.)

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

How do I skip an iteration of a `foreach` loop?

The easiest way to do that is like below:

//Skip First Iteration

foreach ( int number in numbers.Skip(1))

//Skip any other like 5th iteration

foreach ( int number in numbers.Skip(5))

What is the correct JSON content type?

Of course, the correct MIME media type for JSON is application/json, but it's necessary to realize what type of data is expected in your application.

For example, I use Ext GWT and the server response must go as text/html but contains JSON data.

Client side, Ext GWT form listener

uploadForm.getForm().addListener(new FormListenerAdapter()
{
    @Override
    public void onActionFailed(Form form, int httpStatus, String responseText) 
    {
        MessageBox.alert("Error");
    }

    @Override
    public void onActionComplete(Form form, int httpStatus, String responseText) 
    {
        MessageBox.alert("Success");
    }
});

In case of using application/json response type, the browser suggests me to save the file.

Server side source code snippet using Spring MVC

return new AbstractUrlBasedView() 
{
    @SuppressWarnings("unchecked")
    @Override
    protected void renderMergedOutputModel(Map model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception 
    {
        response.setContentType("text/html");
        response.getWriter().write(json);
    }
};

How to find and replace with regex in excel

As an alternative to Regex, running:

Sub Replacer()
   Dim N As Long, i As Long
   N = Cells(Rows.Count, "A").End(xlUp).Row

   For i = 1 To N
      If Left(Cells(i, "A").Value, 9) = "texts are" Then
         Cells(i, "A").Value = "texts are replaced"
      End If
   Next i
End Sub

will produce:

enter image description here

Plotting histograms from grouped data in a pandas DataFrame

With recent version of Pandas, you can do df.N.hist(by=df.Letter)

Just like with the solutions above, the axes will be different for each subplot. I have not solved that one yet.

How to write a simple Java program that finds the greatest common divisor between two numbers?

public static int GCD(int x, int y) {   
    int r;
    while (y!=0) {
        r = x%y;
        x = y;
        y = r;
    }
    return x;
}

JavaScript - Getting HTML form values

If you want to retrieve the form values (such as those that would be sent using an HTTP POST) you can use:

JavaScript

const formData = new FormData(document.querySelector('form'))
for (var pair of formData.entries()) {
  // console.log(pair[0] + ': ' + pair[1]);
}

form-serialize (https://code.google.com/archive/p/form-serialize/)

serialize(document.forms[0]);

jQuery

$("form").serializeArray()

Is there a function in python to split a word into a list?

>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']

Bash script to check running process

A solution with service and awk that takes in a comma-delimited list of service names.

First it's probably a good bet you'll need root privileges to do what you want. If you don't need to check then you can remove that part.

#!/usr/bin/env bash

# First parameter is a comma-delimited string of service names i.e. service1,service2,service3
SERVICES=$1

ALL_SERVICES_STARTED=true

if [ $EUID -ne 0 ]; then
  if [ "$(id -u)" != "0" ]; then
    echo "root privileges are required" 1>&2
    exit 1
  fi
  exit 1
fi

for service in ${SERVICES//,/ }
do
    STATUS=$(service ${service} status | awk '{print $2}')

    if [ "${STATUS}" != "started" ]; then
        echo "${service} not started"
        ALL_SERVICES_STARTED=false
    fi
done

if ${ALL_SERVICES_STARTED} ; then
    echo "All services started"
    exit 0
else
    echo "Check Failed"
    exit 1
fi

How to deploy a Java Web Application (.war) on tomcat?

The tomcat manual says:

Copy the web application archive file into directory $CATALINA_HOME/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way.

What is the quickest way to HTTP GET in Python?

If you want a lower level API:

import http.client

conn = http.client.HTTPSConnection('example.com')
conn.request('GET', '/')

resp = conn.getresponse()
content = resp.read()

conn.close()

text = content.decode('utf-8')

print(text)

Check date between two other dates spring data jpa

Maybe you could try

List<Article> findAllByPublicationDate(Date publicationDate);

The detail could be checked in this article:

https://www.baeldung.com/spring-data-jpa-query-by-date

Boolean checking in the 'if' condition

The first one. But just another point, the following would also make your code more readable:

if (!status) {
    // do false logic
} else {
    // do true logic
}

Note that there are extra spaces between if and the (, and also before the else statement.

EDIT

As noted by @Mudassir, if there is NO other shared code in the method using the logic, then the better style would be:

if (!status) {
    // do false logic
}

// do true logic

Display all items in array using jquery

You should use $.map for this:

var array = ["one", "two", "three"];

var el = $.map(array, function(val, i) {
  return "<span>" + val + "</span>";
});

$(".element").html(el.join(""));

jsFiddle demo

Add Foreign Key relationship between two Databases

If you need rock solid integrity, have both tables in one database, and use an FK constraint. If your parent table is in another database, nothing prevents anyone from restoring that parent database from an old backup, and then you have orphans.

This is why FK between databases is not supported.

Android: java.lang.SecurityException: Permission Denial: start Intent

I was running into the same issue and wanted to avoid adding the intent filter as you described. After some digging, I found an xml attribute android:exported that you should add to the activity you would like to be called.

It is by default set to false if no intent filter added to your activity, but if you do have an intent filter it gets set to true.

here is the documentation http://developer.android.com/guide/topics/manifest/activity-element.html#exported

tl;dr: addandroid:exported="true" to your activity in your AndroidManifest.xml file and avoid adding the intent-filter :)

Reading a string with spaces with sscanf

You want the %c conversion specifier, which just reads a sequence of characters without special handling for whitespace.

Note that you need to fill the buffer with zeroes first, because the %c specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):

memset(buffer, 0, 200);
sscanf("19 cool kid", "%d %199c", &age, buffer);

How to use subprocess popen Python

subprocess.Popen takes a list of arguments:

from subprocess import Popen, PIPE

process = Popen(['swfdump', '/tmp/filename.swf', '-d'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

There's even a section of the documentation devoted to helping users migrate from os.popen to subprocess.

How to convert list of key-value tuples into dictionary?

Here is a way to handle duplicate tuple "keys":

# An example
l = [('A', 1), ('B', 2), ('C', 3), ('A', 5), ('D', 0), ('D', 9)]

# A solution
d = dict()
[d [t [0]].append(t [1]) if t [0] in list(d.keys()) 
 else d.update({t [0]: [t [1]]}) for t in l]
d

OUTPUT: {'A': [1, 5], 'B': [2], 'C': [3], 'D': [0, 9]}

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Set in RecyclerView initialization

recyclerView.setLayoutManager(new GridLayoutManager(this, 4));

Copy all values from fields in one class to another through reflection

  1. Without using BeanUtils or Apache Commons

  2. public static <T1 extends Object, T2 extends Object>  void copy(T1     
    origEntity, T2 destEntity) throws IllegalAccessException, NoSuchFieldException {
        Field[] fields = origEntity.getClass().getDeclaredFields();
        for (Field field : fields){
            origFields.set(destEntity, field.get(origEntity));
         }
    }
    

Static methods - How to call a method from another method?

OK the main difference between class methods and static methods is:

  • class method has its own identity, that's why they have to be called from within an INSTANCE.
  • on the other hand static method can be shared between multiple instances so that it must be called from within THE CLASS

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

I used another repository for oracle java.

sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update

sudo apt install  oracle-java11-installer

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

convert big endian to little endian in C [without using provided func]

#include <stdint.h>


//! Byte swap unsigned short
uint16_t swap_uint16( uint16_t val ) 
{
    return (val << 8) | (val >> 8 );
}

//! Byte swap short
int16_t swap_int16( int16_t val ) 
{
    return (val << 8) | ((val >> 8) & 0xFF);
}

//! Byte swap unsigned int
uint32_t swap_uint32( uint32_t val )
{
    val = ((val << 8) & 0xFF00FF00 ) | ((val >> 8) & 0xFF00FF ); 
    return (val << 16) | (val >> 16);
}

//! Byte swap int
int32_t swap_int32( int32_t val )
{
    val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF ); 
    return (val << 16) | ((val >> 16) & 0xFFFF);
}

Update : Added 64bit byte swapping

int64_t swap_int64( int64_t val )
{
    val = ((val << 8) & 0xFF00FF00FF00FF00ULL ) | ((val >> 8) & 0x00FF00FF00FF00FFULL );
    val = ((val << 16) & 0xFFFF0000FFFF0000ULL ) | ((val >> 16) & 0x0000FFFF0000FFFFULL );
    return (val << 32) | ((val >> 32) & 0xFFFFFFFFULL);
}

uint64_t swap_uint64( uint64_t val )
{
    val = ((val << 8) & 0xFF00FF00FF00FF00ULL ) | ((val >> 8) & 0x00FF00FF00FF00FFULL );
    val = ((val << 16) & 0xFFFF0000FFFF0000ULL ) | ((val >> 16) & 0x0000FFFF0000FFFFULL );
    return (val << 32) | (val >> 32);
}

This view is not constrained

When creating a layout, it's easier to work with one control at a time, instead of adding them all at once.

From the Layouts Palette, drag a ConstraintLayout to the screen.

Move your desired controls inside the ConstraintLayout.

So the ConstraintLayout will now be the control's parents, and if you switch to the xml code, the controls will be nested under the ConstraintLayout.

Right click on your control, select Constraint from the menu, and select how you want to align it to the parent ConstraintLayout, top, start, etc.

If you need to align two controls relative to each other, select both controls at the same time with the Ctrl key, then right click to open the constrain menu.

More info: https://developer.android.com/training/constraint-layout

enter image description here

enter image description here You can specify the constraint separation distance in the Constraint Layout tab:

enter image description here

I'm trying to use python in powershell

Try setting the path this way:

 $env:path="$env:Path;C:\Python27"

How to use placeholder as default value in select2 framework

$('#ddlSelect').prepend('<option selected=""></option>').select2({placeholder: "Select Month"});

How to change RGB color to HSV?

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just calculations.

found via Google

What is a wrapper class?

a wrapper class is usually a class that has an object as a private property. the wrapper implements that private object's API and so it can be passed as an argument where the private object would.

say you have a collection, and you want to use some sort of translation when objects are added to it - you write a wrapper class that has all the collection's methods. when add() is called, the wrapper translate the arguments instead of just passing them into the private collection.

the wrapper can be used anyplace a collection can be used, and the private object can still have other objects referring to it and reading it.

How to stop a thread created by implementing runnable interface?

How to stop a thread created by implementing runnable interface?

There are many ways that you can stop a thread but all of them take specific code to do so. A typical way to stop a thread is to have a volatile boolean shutdown field that the thread checks every so often:

  // set this to true to stop the thread
  volatile boolean shutdown = false;
  ...
  public void run() {
      while (!shutdown) {
          // continue processing
      }
  }

You can also interrupt the thread which causes sleep(), wait(), and some other methods to throw InterruptedException. You also should test for the thread interrupt flag with something like:

  public void run() {
      while (!Thread.currentThread().isInterrupted()) {
          // continue processing
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {
              // good practice
              Thread.currentThread().interrupt();
              return;
          }
      }
  }

Note that that interrupting a thread with interrupt() will not necessarily cause it to throw an exception immediately. Only if you are in a method that is interruptible will the InterruptedException be thrown.

If you want to add a shutdown() method to your class which implements Runnable, you should define your own class like:

public class MyRunnable implements Runnable {
    private volatile boolean shutdown;
    public void run() {
        while (!shutdown) {
            ...
        }
    }
    public void shutdown() {
        shutdown = true;
    }
}

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script,  true );

The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:

<script language='javascript' defer='defer'>your script</script >

If the value will be "false" it will inject only the script witout the --script-- tag.

Sending HTTP Post request with SOAP action using org.apache.http

... using org.apache.http api. ...

You need to include SOAPAction as a header in the request. As you have httpPost and requestWrapper handles, there are three ways adding the header.

 1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
 2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
 3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );

Only difference is that addHeader allows multiple values with same header name and setHeader allows unique header names only. setHeader(... over writes first header with the same name.

You can go with any of these on your requirement.

Notice: Undefined offset: 0 in

You are asking for the value at key 0 of $votes. It is an array that does not contain that key.

The array $votes is not set, so when PHP is trying to access the key 0 of the array, it encounters an undefined offset for [0] and [1] and throws the error.

If you have an array:

$votes = array('1','2','3');

We can now access:

$votes[0];
$votes[1];
$votes[2];

If we try and access:

$votes[3];

We will get the error "Notice: Undefined offset: 3"

Python function attributes - uses and abuses

I've used them as static variables for a function. For example, given the following C code:

int fn(int i)
{
    static f = 1;
    f += i;
    return f;
}

I can implement the function similarly in Python:

def fn(i):
    fn.f += i
    return fn.f
fn.f = 1

This would definitely fall into the "abuses" end of the spectrum.

How do I flush the cin buffer?

I would prefer the C++ size constraints over the C versions:

// Ignore to the end of file
cin.ignore(std::numeric_limits<std::streamsize>::max())

// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

How to make a Java Generic method static?

the only thing you can do is to change your signature to

public static <E> E[] appendToArray(E[] array, E item)

Important details:

Generic expressions preceding the return value always introduce (declare) a new generic type variable.

Additionally, type variables between types (ArrayUtils) and static methods (appendToArray) never interfere with each other.

So, what does this mean: In my answer <E> would hide the E from ArrayUtils<E> if the method wouldn't be static. AND <E> has nothing to do with the E from ArrayUtils<E>.

To reflect this fact better, a more correct answer would be:

public static <I> I[] appendToArray(I[] array, I item)

JOptionPane Yes or No window

You are always checking for a true condition, hence your message will always show.

You should replace your if (true) statement with if ( n == JOptionPane.YES_OPTION)

When one of the showXxxDialog methods returns an integer, the possible values are:

YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION

From here

Getting Git to work with a proxy server - fails with "Request timed out"

If the command line way of configuring your proxy server doesn't work, you can probably just edit .gitconfig (in the root of your profile, which may hide both in C:\Documents and Settings and on some network drive) and add this:

[http]
    proxy = http://username:[email protected]:8080

YMMV though, this only covers the first step of the command line configuration. You may have to edit the system git configuration too and I have no idea where they hid that.

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

RSA Public Key format

Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser

RSA Public Key

-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----

Encrypted Private Key

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----

CRL

-----BEGIN X509 CRL-----
-----END X509 CRL-----

CRT

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

CSR

-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----

NEW CSR

-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----

PEM

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

PKCS7

-----BEGIN PKCS7-----
-----END PKCS7-----

PRIVATE KEY

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----

DSA KEY

-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----

Elliptic Curve

-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----

PGP Private Key

-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----

PGP Public Key

-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----

C++ floating point to integer type conversions

Size of some float types may exceed the size of int. This example shows a safe conversion of any float type to int using the int safeFloatToInt(const FloatType &num); function:

#include <iostream>
#include <limits>
using namespace std;

template <class FloatType>
int safeFloatToInt(const FloatType &num) {
   //check if float fits into integer
   if ( numeric_limits<int>::digits < numeric_limits<FloatType>::digits) {
      // check if float is smaller than max int
      if( (num < static_cast<FloatType>( numeric_limits<int>::max())) &&
          (num > static_cast<FloatType>( numeric_limits<int>::min())) ) {
         return static_cast<int>(num); //safe to cast
      } else {
        cerr << "Unsafe conversion of value:" << num << endl;
        //NaN is not defined for int return the largest int value
        return numeric_limits<int>::max();
      }
   } else {
      //It is safe to cast
      return static_cast<int>(num);
   }
}
int main(){
   double a=2251799813685240.0;
   float b=43.0;
   double c=23333.0;
   //unsafe cast
   cout << safeFloatToInt(a) << endl;
   cout << safeFloatToInt(b) << endl;
   cout << safeFloatToInt(c) << endl;
   return 0;
}

Result:

Unsafe conversion of value:2.2518e+15
2147483647
43
23333

No assembly found containing an OwinStartupAttribute Error

I deleted all DLLs from the branch which wasn't working, then I copied all DDls from my branch which was working to my branch wich wasn't. This solved the issue.

What are the best practices for SQLite on Android?

after struggling with this for a couple of hours, I've found that you can only use one db helper object per db execution. For example,

for(int x = 0; x < someMaxValue; x++)
{
    db = new DBAdapter(this);
    try
    {

        db.addRow
        (
                NamesStringArray[i].toString(), 
                StartTimeStringArray[i].toString(),
                EndTimeStringArray[i].toString()
        );

    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }
    db.close();
}

as apposed to:

db = new DBAdapter(this);
for(int x = 0; x < someMaxValue; x++)
{

    try
    {
        // ask the database manager to add a row given the two strings
        db.addRow
        (
                NamesStringArray[i].toString(), 
                StartTimeStringArray[i].toString(),
                EndTimeStringArray[i].toString()
        );

    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }

}
db.close();

creating a new DBAdapter each time the loop iterates was the only way I could get my strings into a database through my helper class.

Crystal Reports - Adding a parameter to a 'Command' query

Select Projecttname, ReleaseDate, TaskName From DB_Table Where Project_Name like '%{?Pm-?Proj_Name}%' and ReleaseDate >= currentdate

Note the single-quotes and wildcard characters. I just spent 30 minutes figuring out something similar.

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

Undefined reference to static class member

You need to actually define the static member somewhere (after the class definition). Try this:

class Foo { /* ... */ };

const int Foo::MEMBER;

int main() { /* ... */ }

That should get rid of the undefined reference.

Can't access 127.0.0.1

If it's a DNS problem, you could try:

  • ipconfig /flushdns
  • ipconfig /registerdns

If this doesn't fix it, you could try editing the hosts file located here:

C:\Windows\System32\drivers\etc\hosts

And ensure that this line (and no other line referencing localhost) is in there:

127.0.0.1 localhost

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

Set selected radio from radio group with a value

Or you can just write value attribute to it:

$(':radio[value=<yourvalue>]').attr('checked',true);

This works for me.

How to resize an image with OpenCV2.0 and Python2.6

Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio

# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]

    # Return original image if no need to resize
    if width is None and height is None:
        return image

    # We are resizing height if width is none
    if width is None:
        # Calculate the ratio of the height and construct the dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # We are resizing width if height is none
    else:
        # Calculate the ratio of the width and construct the dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # Return the resized image
    return cv2.resize(image, dim, interpolation=inter)

Usage

import cv2

image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()

Using this example image

enter image description here

Simply downscale to width=100 (left) or upscale to width=300 (right)

enter image description here enter image description here

Cannot install Aptana Studio 3.6 on Windows

Right click the installer and choose "Run as administrator". I suspect it needs administrator account to download and install Node JS during installation.

C# list.Orderby descending

var newList = list.OrderBy(x => x.Product.Name).Reverse()

This should do the job.

What should be the sizeof(int) on a 64-bit machine?

In C++, the size of int isn't specified explicitly. It just tells you that it must be at least the size of short int, which must be at least as large as signed char. The size of char in bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long long to be at least 64 bits.

How can I tell how many objects I've stored in an S3 bucket?

Although this is an old question, and feedback was provided in 2015, right now it's much simpler, as S3 Web Console has enabled a "Get Size" option:

enter image description here

Which provides the following:

enter image description here

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

If other solution is not working like:

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

check for what are you returning from onCreateView of fragment is it single view or viewgroup? in my case I had viewpager on root of xml of fragment and I was returning viewpager, when i added viewgroup in layout i didnt updated that i have to return viewgroup now, not viewpager(view).

Finding a branch point with Git?

surely I'm missing something, but IMO, all the problems above are caused because we are always trying to find the branch point going back in the history, and that causes all sort of problems because of the merging combinations available.

Instead, I've followed a different approach, based in the fact that both branches share a lot of history, exactly all the history before branching is 100% the same, so instead of going back, my proposal is about going forward (from 1st commit), looking for the 1st difference in both branches. The branch point will be, simply, the parent of the first difference found.

In practice:

#!/bin/bash
diff <( git rev-list "${1:-master}" --reverse --topo-order ) \
     <( git rev-list "${2:-HEAD}" --reverse --topo-order) \
--unified=1 | sed -ne 's/^ //p' | head -1

And it's solving all my usual cases. Sure there are border ones not covered but... ciao :-)

How to get the full URL of a Drupal page?

This is what I found to be useful

global $base_root;
$base_root . request_uri();

Returns query strings and it's what's used in core: page_set_cache()

Get single row result with Doctrine NativeQuery

Both getSingleResult() and getOneOrNullResult() will throw an exception if there is more than one result. To fix this problem you could add setMaxResults(1) to your query builder.

 $firstSubscriber = $entity->createQueryBuilder()->select('sub')
        ->from("\Application\Entity\Subscriber", 'sub')
        ->where('sub.subscribe=:isSubscribe')
        ->setParameter('isSubscribe', 1)  
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();

SQLException : String or binary data would be truncated

  1. Get the query that is causing the problems (you can also use SQL Profiler if you dont have the source)
  2. Remove all WHERE clauses and other unimportant parts until you are basically just left with the SELECT and FROM parts
  3. Add WHERE 0 = 1 (this will select only table structure)
  4. Add INTO [MyTempTable] just before the FROM clause

You should end up with something like

SELECT
 Col1, Col2, ..., [ColN]
INTO [MyTempTable]
FROM
  [Tables etc.]
WHERE 0 = 1

This will create a table called MyTempTable in your DB that you can compare to your target table structure i.e. you can compare the columns on both tables to see where they differ. It is a bit of a workaround but it is the quickest method I have found.

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

The mySQL client by default attempts to connect through a local file called a socket instead of connecting to the loopback address (127.0.0.1) for localhost.

The default location of this socket file, at least on OSX, is /tmp/mysql.sock.

QUICK, LESS ELEGANT SOLUTION

Create a symlink to fool the OS into finding the correct socket.

ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp

PROPER SOLUTION

Change the socket path defined in the startMysql.sh file in /Applications/MAMP/bin.

How do I tell Maven to use the latest version of a dependency?

The dependencies syntax is located at the Dependency Version Requirement Specification documentation. Here it is is for completeness:

Dependencies' version element define version requirements, used to compute effective dependency version. Version requirements have the following syntax:

  • 1.0: "Soft" requirement on 1.0 (just a recommendation, if it matches all other ranges for the dependency)
  • [1.0]: "Hard" requirement on 1.0
  • (,1.0]: x <= 1.0
  • [1.2,1.3]: 1.2 <= x <= 1.3
  • [1.0,2.0): 1.0 <= x < 2.0
  • [1.5,): x >= 1.5
  • (,1.0],[1.2,): x <= 1.0 or x >= 1.2; multiple sets are comma-separated
  • (,1.1),(1.1,): this excludes 1.1 (for example if it is known not to work in combination with this library)

In your case, you could do something like <version>[1.2.3,)</version>

Call two functions from same onclick

With jQuery :

jQuery("#btn").on("click",function(event){
    event.preventDefault();
    pay();
    cls();
});

How can I insert a line break into a <Text> component in React Native?

Here is a solution for React (not React Native) using TypeScript.

The same concept can be applied to React Native

import React from 'react';

type Props = {
  children: string;
  Wrapper?: any;
}

/**
 * Automatically break lines for text
 *
 * Avoids relying on <br /> for every line break
 *
 * @example
 * <Text>
 *   {`
 *     First line
 *
 *     Another line, which will respect line break
 *  `}
 * </Text>
 * @param props
 */
export const Text: React.FunctionComponent<Props> = (props) => {
  const { children, Wrapper = 'div' } = props;

  return (
    <Wrapper style={{ whiteSpace: 'pre-line' }}>
      {children}
    </Wrapper>
  );
};

export default Text;

Usage:

<Text>
  {`
    This page uses server side rendering (SSR)

    Each page refresh (either SSR or CSR) queries the GraphQL API and displays products below:
  `}
</Text>

Displays: enter image description here

how to programmatically fake a touch event to a UIButton?

If you want to do this kind of testing, you’ll love the UI Automation support in iOS 4. You can write JavaScript to simulate button presses, etc. fairly easily, though the documentation (especially the getting-started part) is a bit sparse.

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

How to update and delete a cookie?

http://www.quirksmode.org/js/cookies.html

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

How to install Android SDK Build Tools on the command line?

Build tools could not be downloaded automatically by default as Nate said in https://stackoverflow.com/a/19416222/1104031 post.

But I wrote small tool that make everything for you

I used "expect" tool as danb in https://stackoverflow.com/a/17863931/1104031 post. You only need android-sdk and python27, expect.

This script will install all build tools, all sdks and everything you need for automated build:

import subprocess,re,sys

w = subprocess.check_output(["android", "list", "sdk", "--all"])
lines = w.split("\n")
tools = filter(lambda x: "Build-tools" in x, lines)
filters = []
for tool in tools:
  m = re.search("^\s+([0-9]+)-", tool)
  tool_no = m.group(1)
  filters.append(tool_no)

if len(filters) == 0:
  raise Exception("Not found build tools")


filters.extend(['extra', 'platform', 'platform-tool', 'tool'])

filter = ",".join(filters)

expect= '''set timeout -1;
spawn android update sdk --no-ui --all --filter %s;
expect {
  "Do you accept the license" { exp_send "y\\r" ; exp_continue }
  eof
}''' % (filter)

print expect

ret = subprocess.call(["expect", "-c", expect])
sys.exit(ret)

Spring cannot find bean xml configuration file when it does exist

In Spring all source files are inside src/main/java. Similarly, the resources are generally kept inside src/main/resources. So keep your spring configuration file inside resources folder.

Make sure you have the ClassPath entry for your files inside src/main/resources as well.

In .classpath check for the following 2 lines. If they are missing add them.

<classpathentry path="src/main/java" kind="src"/>
<classpathentry path="src/main/resources" kind="src" />

So, if you have everything in place the below code should work.

ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-Module.xml");

Html.ActionLink as a button or an image, not a link

<li><a href="@Url.Action(  "View", "Controller" )"><i class='fa fa-user'></i><span>Users View</span></a></li>

To display an icon with the link

How does bitshifting work in Java?

byte x = 51; //00101011
byte y = (byte) (x >> 2); //00001010 aka Base(10) 10

Boolean vs boolean in Java

Yes you can use Boolean/boolean instead.

First one is Object and second one is primitive type.

  • On first one, you will get more methods which will be useful.

  • Second one is cheap considering memory expense The second will save you a lot more memory, so go for it

Now choose your way.

How to check if a text field is empty or not in swift

It's too late and its working fine in Xcode 7.3.1

if _txtfield1.text!.isEmpty || _txtfield2.text!.isEmpty {
        //is empty
    }

How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs

Deleting node_modules folder contents and running

npm install bower
npm install

solved the problem for me!

List of ANSI color escape sequences

How about:

ECMA-48 - Control Functions for Coded Character Sets, 5th edition (June 1991) - A standard defining the color control codes, that is apparently supported also by xterm.

SGR 38 and 48 were originally reserved by ECMA-48, but were fleshed out a few years later in a joint ITU, IEC, and ISO standard, which comes in several parts and which (amongst a whole lot of other things) documents the SGR 38/48 control sequences for direct colour and indexed colour:

There's a column for xterm in this table on the Wikipedia page for ANSI escape codes

How to fix a header on scroll

The simplest way is: HTML:

<header>
        <h1>Website</h1>
</header>

CSS:

header{
    position: sticky;
    top: 0;
}

Check if textbox has empty value

if ( $("#txt").val().length > 0 )
{
  // do something
}

Your method fails when there is more than 1 space character inside the textbox.

Linux shell sort file according to the second column?

To sort by second field only (thus where second fields match, those lines with matches remain in the order they are in the original without sorting on other fields) :

sort -k 2,2 -s orig_file > sorted_file

Split Spark Dataframe string column into multiple columns

Here's a solution to the general case that doesn't involve needing to know the length of the array ahead of time, using collect, or using udfs. Unfortunately this only works for spark version 2.1 and above, because it requires the posexplode function.

Suppose you had the following DataFrame:

df = spark.createDataFrame(
    [
        [1, 'A, B, C, D'], 
        [2, 'E, F, G'], 
        [3, 'H, I'], 
        [4, 'J']
    ]
    , ["num", "letters"]
)
df.show()
#+---+----------+
#|num|   letters|
#+---+----------+
#|  1|A, B, C, D|
#|  2|   E, F, G|
#|  3|      H, I|
#|  4|         J|
#+---+----------+

Split the letters column and then use posexplode to explode the resultant array along with the position in the array. Next use pyspark.sql.functions.expr to grab the element at index pos in this array.

import pyspark.sql.functions as f

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .show()
#+---+------------+---+---+
#|num|     letters|pos|val|
#+---+------------+---+---+
#|  1|[A, B, C, D]|  0|  A|
#|  1|[A, B, C, D]|  1|  B|
#|  1|[A, B, C, D]|  2|  C|
#|  1|[A, B, C, D]|  3|  D|
#|  2|   [E, F, G]|  0|  E|
#|  2|   [E, F, G]|  1|  F|
#|  2|   [E, F, G]|  2|  G|
#|  3|      [H, I]|  0|  H|
#|  3|      [H, I]|  1|  I|
#|  4|         [J]|  0|  J|
#+---+------------+---+---+

Now we create two new columns from this result. First one is the name of our new column, which will be a concatenation of letter and the index in the array. The second column will be the value at the corresponding index in the array. We get the latter by exploiting the functionality of pyspark.sql.functions.expr which allows us use column values as parameters.

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .show()
#+---+-------+---+
#|num|   name|val|
#+---+-------+---+
#|  1|letter0|  A|
#|  1|letter1|  B|
#|  1|letter2|  C|
#|  1|letter3|  D|
#|  2|letter0|  E|
#|  2|letter1|  F|
#|  2|letter2|  G|
#|  3|letter0|  H|
#|  3|letter1|  I|
#|  4|letter0|  J|
#+---+-------+---+

Now we can just groupBy the num and pivot the DataFrame. Putting that all together, we get:

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .groupBy("num").pivot("name").agg(f.first("val"))\
    .show()
#+---+-------+-------+-------+-------+
#|num|letter0|letter1|letter2|letter3|
#+---+-------+-------+-------+-------+
#|  1|      A|      B|      C|      D|
#|  3|      H|      I|   null|   null|
#|  2|      E|      F|      G|   null|
#|  4|      J|   null|   null|   null|
#+---+-------+-------+-------+-------+

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I'll list things I did that did not work for me and finally what did

First, the accepted answer of Run script only when installing did not work.

Deleting derived data did not work.

What did work:

  1. I added a new build phase in Build Phases

  2. New Copy Files Phase

  3. Drag & Drop the chosen framework into the drop target

  4. Set the 'Destination' to Frameworks

Credit due to Kevin Le's Medium post

Using Helvetica Neue in a Website

I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:

http://css-tricks.com/snippets/css/better-helvetica/

He basically recommends the following declaration for covering all the bases:

body {
    font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
    font-weight: 300;
}

Global Angular CLI version greater than local version

Update Angular CLI for a workspace (Local)

npm install --save -dev @angular/cli@latest

Note: Make sure to install the global version using the command with ‘-g’ is if it installed properly.

npm install -g @angular/cli@latest

Run Update command to get a list of all dependencies required to be upgraded

ng update

Next Run update command as below for each individual Angular core package

ng update @angular/cli @angular/core

However, I had to add ‘–force’ and ‘–allow-dirty’ flags command additionally to fix all other pending issues.

ng update @angular/cli @angular/core --allow-dirty --force

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!

write a shell script to ssh to a remote machine and execute commands

There are a number of ways to handle this.

My favorite way is to install http://pamsshagentauth.sourceforge.net/ on the remote systems and also your own public key. (Figure out a way to get these installed on the VM, somehow you got an entire Unix system installed, what's a couple more files?)

With your ssh agent forwarded, you can now log in to every system without a password.

And even better, that pam module will authenticate for sudo with your ssh key pair so you can run with root (or any other user's) rights as needed.

You don't need to worry about the host key interaction. If the input is not a terminal then ssh will just limit your ability to forward agents and authenticate with passwords.

You should also look into packages like Capistrano. Definitely look around that site; it has an introduction to remote scripting.

Individual script lines might look something like this:

ssh remote-system-name command arguments ... # so, for exmaple,
ssh target.mycorp.net sudo puppet apply

MySQL/SQL: Group by date only on a Datetime column

SELECT SUM(No), HOUR(dateofissue) 
FROM tablename 
WHERE dateofissue>='2011-07-30' 
GROUP BY HOUR(dateofissue)

It will give the hour by sum from a particular day!

Is there a way to check if a file is in use?

retry_possibility:
//somecode here

try
{
    using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
    {
        stream.Close();
    }
    //write or open your file here
}
catch (IOException)
{
    DialogResult dialogResult = MessageBox.Show("This file is opened by you or another user. Please close it and press retry.\n"+ expFilePath, "File Locked", MessageBoxButtons.RetryCancel);
    if (dialogResult == DialogResult.Retry)
    {
        goto retry_possibility;
    }
    else if (dialogResult == DialogResult.Cancel)
    {
        //do nothing
    }
}

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

If you have completed all steps given by Surjeet and still not getting network connection icon then follow below steps:

  1. Unpair Device using right click on the device from the Connected section.

    enter image description here

  2. Reconnect the device.

  3. Click on "+" button from the end of the lefthand side of the popup.

enter image description here

  1. Select the device and click on next button

enter image description here

  1. Click on Trust and passcode(if available) from the device.

enter image description here

  1. Click on Done button.

enter image description here

  1. Now, click on connect via network.

enter image description here

Now you can see the network connection icon after the device name. Enjoy!

enter image description here

Alter Table Add Column Syntax

It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.

What's the difference between an id and a class?

1) div id is not reusable and should only be applied to one element of HTML while div class can be added to multiple elements.

2) An id has greater importance if both are applied to the same element and have conflicting styles, the styles of the id will be applied.

3) Style element always refer a div class by putting a . (dot) in front of their names while div id class is referred by putting a # (hash) in front of their names.

4) Example :-

class in <style> declaration - .red-background { background-color: red; }

id in <style> declaration - #blue-background {background-color: blue;}

<div class="red-background" id="blue-background">Hello</div> Here background will be in blue color

How to increase Maximum Upload size in cPanel?

I have found the answer and solution to this problem. Before, I did not know that php.ini resides where in wordpress files. Now I have found that file in wp-admin directory where I placed the code

post_max_size 33M
upload_max_filesize 32M

then it worked. It increases the upload file size for my worpdress website. But, it is the same 2M as was before on cPanel.

How to implement a ViewPager with different Fragments / Layouts

Basic ViewPager Example

This answer is a simplification of the documentation, this tutorial, and the accepted answer. It's purpose is to get a working ViewPager up and running as quickly as possible. Further edits can be made after that.

enter image description here

XML

Add the xml layouts for the main activity and for each page (fragment). In our case we are only using one fragment layout, but if you have different layouts on the different pages then just make one for each of them.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.verticalviewpager.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textview"
        android:textSize="30sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

Code

This is the code for the main activity. It includes the PagerAdapter and FragmentOne as inner classes. If these get too large or you are reusing them in other places, then you can move them to their own separate classes.

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends AppCompatActivity {

    static final int NUMBER_OF_PAGES = 2;

    MyAdapter mAdapter;
    ViewPager mPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAdapter = new MyAdapter(getSupportFragmentManager());
        mPager = findViewById(R.id.viewpager);
        mPager.setAdapter(mAdapter);
    }

    public static class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return NUMBER_OF_PAGES;
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return FragmentOne.newInstance(0, Color.WHITE);
                case 1:
                    // return a different Fragment class here
                    // if you want want a completely different layout
                    return FragmentOne.newInstance(1, Color.CYAN);
                default:
                    return null;
            }
        }
    }

    public static class FragmentOne extends Fragment {

        private static final String MY_NUM_KEY = "num";
        private static final String MY_COLOR_KEY = "color";

        private int mNum;
        private int mColor;

        // You can modify the parameters to pass in whatever you want
        static FragmentOne newInstance(int num, int color) {
            FragmentOne f = new FragmentOne();
            Bundle args = new Bundle();
            args.putInt(MY_NUM_KEY, num);
            args.putInt(MY_COLOR_KEY, color);
            f.setArguments(args);
            return f;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt(MY_NUM_KEY) : 0;
            mColor = getArguments() != null ? getArguments().getInt(MY_COLOR_KEY) : Color.BLACK;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_one, container, false);
            v.setBackgroundColor(mColor);
            TextView textView = v.findViewById(R.id.textview);
            textView.setText("Page " + mNum);
            return v;
        }
    }
}

Finished

If you copied and pasted the three files above to your project, you should be able to run the app and see the result in the animation above.

Going on

There are quite a few things you can do with ViewPagers. See the following links to get started:

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.

To install OpenSSL development package on Debian, Ubuntu or their derivatives:

$ sudo apt-get install libssl-dev

To install OpenSSL development package on Fedora, CentOS or RHEL:

$ sudo yum install openssl-devel 

Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :

dnf install openssl-devel

Send POST data on redirect with JavaScript/jQuery?

Here is a method, which does not use jQuery. I used it to create a bookmarklet, which checks the current page on w3-html-validator.

var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';

var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);

document.body.appendChild(f);
f.submit();

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

CI/CD Diagram

Continuous Integration

  • Automated(building of check ins + unit test)

Continuous Delivery

  • Continuous Integration
  • Automated(deployment to test environment + load testing + integration test)
  • Manual(deployment to production)

Continuous Deployment

  • Continuous Delivery but automated(deployment to production)

CI/CD is a journey. Not a destination.

These stages are suggestions. You can adapt the stages based on your business need. Some stages can be repeated for multiple types of testing, security, and performance. Depending on the complexity of your project and the structure of your teams, some stages can be repeated several times at different levels. For example, the end product of one team can become a dependency in the project of the next team. This means that the first team’s end product is subsequently staged as an artifact in the next team’s project.

Footnote :

Practicing Continuous Integration and Continuous Delivery on AWS

How to use filter, map, and reduce in Python 3

You can read about the changes in What's New In Python 3.0. You should read it thoroughly when you move from 2.x to 3.x since a lot has been changed.

The whole answer here are quotes from the documentation.

Views And Iterators Instead Of Lists

Some well-known APIs no longer return lists:

  • [...]
  • map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).
  • [...]

Builtins

  • [...]
  • Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.
  • [...]

Converting BigDecimal to Integer

I found that the above did not work for me. I was pulling a cell value from a JTable but could not cast to double or int etc. My solution:

Object obj = getTable().getValueAt(row, 0);

where row 0 would always be a number. Hope this helps anyone still scrolling!

If statement for strings in python?

proceed = "y", "Y"
if answer in proceed:

Also, you don't want

answer = str(input("Is the information correct? Enter Y for yes or N for no"))

You want

answer = raw_input("Is the information correct? Enter Y for yes or N for no")

input() evaluates whatever is entered as a Python expression, raw_input() returns a string.

Edit: That is only true on Python 2. On Python 3, input is fine, although str() wrapping is still redundant.

Image scaling causes poor quality in firefox/internet explorer but not chrome

It seems that you are right. No option scales the image better:
http://www.maxrev.de/html/image-scaling.html

I've tested FF14, IE9, OP12 and GC21. Only GC has a better scaling that can be deactivated through image-rendering: -webkit-optimize-contrast. All other browsers have no/poor scaling.

Screenshot of the different output: http://www.maxrev.de/files/2012/08/screenshot_interpolation_jquery_animate.png

Update 2017

Meanwhile some more browsers support smooth scaling:

  • ME38 (Microsoft Edge) has good scaling. It can't be disabled and it works for JPEG and PNG, but not for GIF.

  • FF51 (Regarding @karthik 's comment since FF21) has good scaling that can be disabled through the following settings:

    image-rendering: optimizeQuality
    image-rendering: optimizeSpeed
    image-rendering: -moz-crisp-edges
    

    Note: Regarding MDN the optimizeQuality setting is a synonym for auto (but auto does not disable smooth scaling):

    The values optimizeQuality and optimizeSpeed present in early draft (and coming from its SVG counterpart) are defined as synonyms for the auto value.

  • OP43 behaves like GC (not suprising as it is based on Chromium since 2013) and its still this option that disables smooth scaling:

    image-rendering: -webkit-optimize-contrast
    

No support in IE9-IE11. The -ms-interpolation-mode setting worked only in IE6-IE8, but was removed in IE9.

P.S. Smooth scaling is done by default. This means no image-rendering option is needed!

Best C/C++ Network Library

Aggregated List of Libraries

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

How to search if dictionary value contains certain string with Python

def search(myDict, lookup):
    a=[]
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                 a.append(key)
    a=list(set(a))
    return a

if the research involves more keys maybe you should create a list with all the keys

find index of an int in a list

List<string> accountList = new List<string> {"123872", "987653" , "7625019", "028401"};

int i = accountList.FindIndex(x => x.StartsWith("762"));
//This will give you index of 7625019 in list that is 2. value of i will become 2.
//delegate(string ac)
//{
//    return ac.StartsWith(a.AccountNumber);
//}
//);

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

How to change the floating label color of TextInputLayout

to change color of the text label when you are focusing on it. i.e. typing in it. you have to add specify

<item name="android:textColorPrimary">@color/yourcolorhere</item>

Just a note: You have to add all these implementations to your main theme.

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

How to get line count of a large file cheaply in Python?

This code is shorter and clearer. It's probably the best way:

num_lines = open('yourfile.ext').read().count('\n')

The entity type <type> is not part of the model for the current context

For me the issue was that I had not included the Entity Class within my db set inside the context for entity framework.

public DbSet<ModelName> ModelName { get; set; }

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :

send by post JSON string

<input type="button" value= "click" onclick="fn()">
<script>
 function fn(){


    var js_obj = {plugin: 'jquery-json', version: 2.3};

    var encoded = JSON.stringify( js_obj );

var data= encoded


    $.ajax({
  type: "POST",
  url: '1.php',
  data: data,
  success: function(data){
    console.log(data);
  }

});

    }
</script>

1.php

//print_r($_POST); //empty!!! don't work ... 
var_dump( file_get_contents('php://input'));

When is the finalize() method called in Java?

As pointed out in https://wiki.sei.cmu.edu/confluence/display/java/MET12-J.+Do+not+use+finalizers,

There is no fixed time at which finalizers must be executed because time of execution depends on the Java Virtual Machine (JVM). The only guarantee is that any finalizer method that executes will do so sometime after the associated object has become unreachable (detected during the first cycle of garbage collection) and sometime before the garbage collector reclaims the associated object's storage (during the garbage collector's second cycle). Execution of an object's finalizer may be delayed for an arbitrarily long time after the object becomes unreachable. Consequently, invoking time-critical functionality such as closing file handles in an object's finalize() method is problematic.

Reading content from URL with Node.js

try using the on error event of the client to find the issue.

var http = require('http');

var options = {
    host: 'google.com',
    path: '/'
}
var request = http.request(options, function (res) {
    var data = '';
    res.on('data', function (chunk) {
        data += chunk;
    });
    res.on('end', function () {
        console.log(data);

    });
});
request.on('error', function (e) {
    console.log(e.message);
});
request.end();

How to fix "'System.AggregateException' occurred in mscorlib.dll"

You could handle the exception directly so it would not crash your program (catching the AggregateException). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:

try {
    // your code 
} catch (AggregateException e) {

}

Create pandas Dataframe by appending one row at a time

mycolumns = ['A', 'B']
df = pd.DataFrame(columns=mycolumns)
rows = [[1,2],[3,4],[5,6]]
for row in rows:
    df.loc[len(df)] = row

UITextField text change event

XenElement's answer is spot on.

The above can be done in interface builder too by right-clicking on the UITextField and dragging the "Editing Changed" send event to your subclass unit.

UITextField Change Event

How can I add a space in between two outputs?

You can use System.out.printf() like this if you want to get nicely formatted

System.out.printf("%-20s %s\n", Name, Income);

Prints like:

Jaden             100000.0
Angela            70000.0
Bob               10000.0

This format means:

%-20s  -> this is the first argument, Name, left justified and padded to 20 spaces.
%s     -> this is the second argument, Income, if income is a decimal swap with %f
\n     -> new line character

You could also add formatting to the Income argument so that the number is printed as desired

Check out this for a quick reference

curl POST format for CURLOPT_POSTFIELDS

One other major difference that is not yet mentioned here is that CURLOPT_POSTFIELDS can't handle nested arrays.

If we take the nested array ['a' => 1, 'b' => [2, 3, 4]] then this should be be parameterized as a=1&b[]=2&b[]=3&b[]=4 (the [ and ] will be/should be URL encoded). This will be converted back automatically into a nested array on the other end (assuming here the other end is also PHP).

This will work:

var_dump(http_build_query(['a' => 1, 'b' => [2, 3, 4]]));
// output: string(36) "a=1&b%5B0%5D=2&b%5B1%5D=3&b%5B2%5D=4"

This won't work:

curl_setopt($ch, CURLOPT_POSTFIELDS, ['a' => 1, 'b' => [2, 3, 4]]);

This will give you a notice. Code execution will continue and your endpoint will receive parameter b as string "Array":

PHP Notice: Array to string conversion in ... on line ...

Null pointer Exception on .setOnClickListener

I too got similar error when i misplaced the code

text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

I got it working on placing the code in right order as shown below

setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
 text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

How do I create a user account for basic authentication?

I was able to achieve Basic Authentication on Windows Server 2012 doing the following:

Select your site within IIS and choose Authentication enter image description here

Ensure Basic Authentication is the only enabled option enter image description here

THEN! Add a username and password via the Server Manager. Select Tools -> Computer Management enter image description here

Under System Tools -> Local Users and Groups -> Users right-click anywhere in the middle pane, choose New User.. then fill in the credentials you want to use. enter image description here

Now when you navigate to the site in the browser you should get prompted with an authentication dialog:

enter image description here

Removing all non-numeric characters from string in Python

Not sure if this is the most efficient way, but:

>>> ''.join(c for c in "abc123def456" if c.isdigit())
'123456'

The ''.join part means to combine all the resulting characters together without any characters in between. Then the rest of it is a list comprehension, where (as you can probably guess) we only take the parts of the string that match the condition isdigit.

How to filter a RecyclerView with a SearchView

In Adapter:

public void setFilter(List<Channel> newList){
        mChannels = new ArrayList<>();
        mChannels.addAll(newList);
        notifyDataSetChanged();
    }

In Activity:

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                newText = newText.toLowerCase();
                ArrayList<Channel> newList = new ArrayList<>();
                for (Channel channel: channels){
                    String channelName = channel.getmChannelName().toLowerCase();
                    if (channelName.contains(newText)){
                        newList.add(channel);
                    }
                }
                mAdapter.setFilter(newList);
                return true;
            }
        });

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

The equivalent is:

python3 -m http.server

How to convert this var string to URL in Swift

in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)

Cast a Double Variable to Decimal

use default convertation class: Convert.ToDecimal(Double)

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

Looping through all the properties of object php

If this is just for debugging output, you can use the following to see all the types and values as well.

var_dump($obj);

If you want more control over the output you can use this:

foreach ($obj as $key => $value) {
    echo "$key => $value\n";
}

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Rather than disabling a new feature, I opted to follow the instructions of the error. In my global.asax.cs I added:

protected void Application_Start(object sender, EventArgs e)
{
    string JQueryVer = "1.7.1";
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
    {
        Path = "~/Scripts/jquery-" + JQueryVer + ".min.js",
        DebugPath = "~/Scripts/jquery-" + JQueryVer + ".js",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".min.js",
        CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".js",
        CdnSupportsSecureConnection = true,
        LoadSuccessExpression = "window.jQuery"
    });
}

This comes from an msdn blog post which highlights some of the advantages of script resource mappings. Of particular interest to me was centralized control over the delivery of the script files based on "debug=true", EnableCDN, etc.

what is right way to do API call in react js?

As best place and practice for external API calls is React Lifecycle method componentDidMount(), where after the execution of the API call you should update the local state to be triggered new render() method call, then the changes in the updated local state will be applied on the component view.

As other option for initial external data source call in React is pointed the constructor() method of the class. The constructor is the first method executed on initialization of the component object instance. You could see this approach in the documentation examples for Higher-Order Components.

The method componentWillMount() and UNSAFE_componentWillMount() should not be used for external API calls, because they are intended to be deprecated. Here you could see common reasons, why this method will be deprecated.

Anyway you must never use render() method or method directly called from render() as a point for external API call. If you do this your application will be blocked.

Shorter syntax for casting from a List<X> to a List<Y>?

You can use List<Y>.ConvertAll<T>([Converter from Y to T]);

sendKeys() in Selenium web driver

For python selenium,

Importing the library,

from selenium.webdriver.common.keys import Keys

Use this code to press any key you want,

Anyelement.send_keys(Keys.RETURN)

You can find all the key names by searching this selenium.webdriver.common.keys.

Java: How to get input from System.console()

Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:

import java.util.Scanner;
String data;

Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();

scanInput.close();            
System.out.println(data);

A long bigger than Long.MAX_VALUE

That method can't return true. That's the point of Long.MAX_VALUE. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE and have literally zero reasonable uses. Just use Android's isUserAGoat, or you may roll your own function that always returns false.

Note that a long in memory takes a fixed number of bytes. From Oracle:

long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.

As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.

If you actually need this for something for real then use BigInteger class.

How to get the last value of an ArrayList

The size() method returns the number of elements in the ArrayList. The index values of the elements are 0 through (size()-1), so you would use myArrayList.get(myArrayList.size()-1) to retrieve the last element.

How can I pretty-print JSON using Go?

I was frustrated by the lack of a fast, high quality way to marshal JSON to a colorized string in Go so I wrote my own Marshaller called ColorJSON.

With it, you can easily produce output like this using very little code:

ColorJSON sample output

package main

import (
    "fmt"
    "encoding/json"

    "github.com/TylerBrock/colorjson"
)

func main() {
    str := `{
      "str": "foo",
      "num": 100,
      "bool": false,
      "null": null,
      "array": ["foo", "bar", "baz"],
      "obj": { "a": 1, "b": 2 }
    }`

    var obj map[string]interface{}
    json.Unmarshal([]byte(str), &obj)

    // Make a custom formatter with indent set
    f := colorjson.NewFormatter()
    f.Indent = 4

    // Marshall the Colorized JSON
    s, _ := f.Marshal(obj)
    fmt.Println(string(s))
}

I'm writing the documentation for it now but I was excited to share my solution.

How to Create a circular progressbar in Android which rotates on it?

I realized a Open Source library on GitHub CircularProgressBar that does exactly what you want the simplest way possible:

Gif demo CircularProgressBar

USAGE

To make a circular ProgressBar add CircularProgressBar in your layout XML and add CircularProgressBar library in your projector or you can also grab it via Gradle:

compile 'com.mikhaellopez:circularprogressbar:1.0.0'

XML

<com.mikhaellopez.circularprogressbar.CircularProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:background_progressbar_color="#FFCDD2"
    app:background_progressbar_width="5dp"
    app:progressbar_color="#F44336"
    app:progressbar_width="10dp" />

You must use the following properties in your XML to change your CircularProgressBar.

Properties:

  • app:progress (integer) >> default 0
  • app:progressbar_color (color) >> default BLACK
  • app:background_progressbar_color (color) >> default GRAY
  • app:progressbar_width (dimension) >> default 7dp
  • app:background_progressbar_width (dimension) >> default 3dp

JAVA

CircularProgressBar circularProgressBar = (CircularProgressBar)findViewById(R.id.yourCircularProgressbar);
circularProgressBar.setColor(ContextCompat.getColor(this, R.color.progressBarColor));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(this, R.color.backgroundProgressBarColor));
circularProgressBar.setProgressBarWidth(getResources().getDimension(R.dimen.progressBarWidth));
circularProgressBar.setBackgroundProgressBarWidth(getResources().getDimension(R.dimen.backgroundProgressBarWidth));
int animationDuration = 2500; // 2500ms = 2,5s
circularProgressBar.setProgressWithAnimation(65, animationDuration); // Default duration = 1500ms

Fork or Download this library here >> https://github.com/lopspower/CircularProgressBar

How do I move files in node.js?

This example taken from: Node.js in Action

A move() function that renames, if possible, or falls back to copying

var fs = require('fs');

module.exports = function move(oldPath, newPath, callback) {

    fs.rename(oldPath, newPath, function (err) {
        if (err) {
            if (err.code === 'EXDEV') {
                copy();
            } else {
                callback(err);
            }
            return;
        }
        callback();
    });

    function copy() {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);

        readStream.on('error', callback);
        writeStream.on('error', callback);

        readStream.on('close', function () {
            fs.unlink(oldPath, callback);
        });

        readStream.pipe(writeStream);
    }
}

How to detect READ_COMMITTED_SNAPSHOT is enabled?

SELECT is_read_committed_snapshot_on FROM sys.databases 
WHERE name= 'YourDatabase'

Return value:

  • 1: READ_COMMITTED_SNAPSHOT option is ON. Read operations under the READ COMMITTED isolation level are based on snapshot scans and do not acquire locks.
  • 0 (default): READ_COMMITTED_SNAPSHOT option is OFF. Read operations under the READ COMMITTED isolation level use Shared (S) locks.

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

Select unique or distinct values from a list in UNIX shell script

Pipe them through sort and uniq. This removes all duplicates.

uniq -d gives only the duplicates, uniq -u gives only the unique ones (strips duplicates).

How to find the users list in oracle 11g db?

select * from all_users

This will work for sure

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

How to add a button to UINavigationBar?

Adding custom button to navigation bar ( with image for buttonItem and specifying action method (void)openView{} and).

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 32, 32);
[button setImage:[UIImage imageNamed:@"settings_b.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(openView) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *barButton=[[UIBarButtonItem alloc] init];
[barButton setCustomView:button];
self.navigationItem.rightBarButtonItem=barButton;

[button release];
[barButton release];

Filtering a list based on a list of booleans

You're looking for itertools.compress:

>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]

Timing comparisons(py3.x):

>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]  #winner
100000 loops, best of 3: 1.98 us per loop

>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil))              #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop

>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil))              #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] 
100 loops, best of 3: 7.65 ms per loop

Don't use filter as a variable name, it is a built-in function.

Reading an Excel file in python using pandas

import pandas as pd

data = pd.read_excel (r'**YourPath**.xlsx')

print (data)

Can I install the "app store" in an IOS simulator?

You can install other builds but not Appstore build.

From Xcode 8.2,drag and drop the build to simulator for the installation.

https://stackoverflow.com/a/41671233/1522584

Calculate correlation for more than two variables?

If you would like to combine the matrix with some visualisations I can recommend (I am using the built in iris dataset):

library(psych)
pairs.panels(iris[1:4])  # select columns 1-4

enter image description here

The Performance Analytics basically does the same but includes significance indicators by default.

library(PerformanceAnalytics)
chart.Correlation(iris[1:4])

Correlation Chart

Or this nice and simple visualisation:

library(corrplot)
x <- cor(iris[1:4])
corrplot(x, type="upper", order="hclust")

corrplot

Clear dropdown using jQuery Select2

For select2 version 4 easily use this:

$('#remote').empty();

After populating select element with ajax call, you may need this line of code in the success section to update the content:

  success: function(data, textStatus, jqXHR){
  $('#remote').change();
                } 

How to position three divs in html horizontally?

Most easiest way
I can see the question is answered , I'm giving this answer for the ones who is having this question in future


Its not good practise to code inline css , and also ID for all inner div's , always try to use class for styling .Using inline css is a very bad practise if you are trying to be a professional web designer.

here in your question I have given a wrapper class for the parent div and all the inside div's are child div's in css you can call inner div's using nth-child selector.

I want to point few things here

1 - Do not use inline css ( it is very bad practise )

2 - Try to use classes instead of id's because if you give an id you can use it only once, but if you use a class you can use it many times and also you can style of them using that class so you write less code.


codepen link for my answer

https://codepen.io/feizel/pen/JELGyB


_x000D_
_x000D_
            .wrapper{width:100%;}_x000D_
            .box{float:left; height:100px;}_x000D_
            .box:nth-child(1){_x000D_
               width:25%;_x000D_
               background-color:red; _x000D_
        _x000D_
            }_x000D_
            .box:nth-child(2){_x000D_
               width:50%;_x000D_
              background-color:green; _x000D_
            }_x000D_
            .box:nth-child(3){_x000D_
               width:25%;_x000D_
              background-color:yellow; _x000D_
            }
_x000D_
 _x000D_
    <div class="wrapper">_x000D_
        <div class="box">_x000D_
        Left Side Menu_x000D_
        </div>_x000D_
        <div class="box">_x000D_
        Random Content_x000D_
        </div>_x000D_
        <div class="box">_x000D_
        Right Side Menu_x000D_
        </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Remove attribute "checked" of checkbox

try something like this FIDDLE

    try
      {
        navigator.device.capture.captureImage(function(mediaFiles) {
        console.log("works");
         });
      }

    catch(err)
      {
        alert('hi');
        $("#captureImage").prop('checked', false);

      }

What is the difference between String and string in C#?

System.String is the .NET string class - in C# string is an alias for System.String - so in use they are the same.

As for guidelines I wouldn't get too bogged down and just use whichever you feel like - there are more important things in life and the code is going to be the same anyway.

If you find yourselves building systems where it is necessary to specify the size of the integers you are using and so tend to use Int16, Int32, UInt16, UInt32 etc. then it might look more natural to use String - and when moving around between different .net languages it might make things more understandable - otherwise I would use string and int.

How to list all users in a Linux group?

In UNIX (as opposed to GNU/Linux), there's the listusers command. See the Solaris man page for listusers.

Note that this command is part of the open-source Heirloom Project. I assume that it's missing from GNU/Linux because RMS doesn't believe in groups and permissions. :-)

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Two possibilities here. Java Version incompatible or import

Query to get all rows from previous month

Here's another alternative. Assuming you have an indexed DATE or DATETIME type field, this should use the index as the formatted dates will be type converted before the index is used. You should then see a range query rather than an index query when viewed with EXPLAIN.

SELECT
    * 
FROM
    table
WHERE 
    date_created >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' ) 
AND
    date_created < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' )

Rails: Adding an index after adding column

Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true

How can I find out what version of git I'm running?

$ git --version
git version 1.7.3.4

git help and man git both hint at the available arguments you can pass to the command-line tool

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

Saving and loading objects and using pickle

You're forgetting to read it as binary too.

In your write part you have:

open(b"Fruits.obj","wb") # Note the wb part (Write Binary)

In the read part you have:

file = open("Fruits.obj",'r') # Note the r part, there should be a b too

So replace it with:

file = open("Fruits.obj",'rb')

And it will work :)


As for your second error, it is most likely cause by not closing/syncing the file properly.

Try this bit of code to write:

>>> import pickle
>>> filehandler = open(b"Fruits.obj","wb")
>>> pickle.dump(banana,filehandler)
>>> filehandler.close()

And this (unchanged) to read:

>>> import pickle
>>> file = open("Fruits.obj",'rb')
>>> object_file = pickle.load(file)

A neater version would be using the with statement.

For writing:

>>> import pickle
>>> with open('Fruits.obj', 'wb') as fp:
>>>     pickle.dump(banana, fp)

For reading:

>>> import pickle
>>> with open('Fruits.obj', 'rb') as fp:
>>>     banana = pickle.load(fp)

What are the JavaScript KeyCodes?

http://keycodes.atjayjo.com/

This app is just awesome. It is essentially a virtual keyboard that immediately shows you the keycode pressed on a standard US keyboard.

Are there any log file about Windows Services Status?

The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.

What is the correct syntax of ng-include?

You have to single quote your src string inside of the double quotes:

<div ng-include src="'views/sidepanel.html'"></div>

Source

Cannot install packages inside docker Ubuntu image

From the docs in May 2017 2018 2019 2020

Always combine RUN apt-get update with apt-get install in the same RUN statement, for example

RUN apt-get update && apt-get install -y package-bar

(...)

Using apt-get update alone in a RUN statement causes caching issues and subsequent apt-get install instructions fail.

(...)

Using RUN apt-get update && apt-get install -y ensures your Dockerfile installs the latest package versions with no further coding or manual intervention. This technique is known as “cache busting”.

Understanding __getitem__ method

__getitem__ can be used to implement "lazy" dict subclasses. The aim is to avoid instantiating a dictionary at once that either already has an inordinately large number of key-value pairs in existing containers, or has an expensive hashing process between existing containers of key-value pairs, or if the dictionary represents a single group of resources that are distributed over the internet.

As a simple example, suppose you have two lists, keys and values, whereby {k:v for k,v in zip(keys, values)} is the dictionary that you need, which must be made lazy for speed or efficiency purposes:

class LazyDict(dict):
    
    def __init__(self, keys, values):
        self.keys = keys
        self.values = values
        super().__init__()
        
    def __getitem__(self, key):
        if key not in self:
            try:
                i = self.keys.index(key)
                self.__setitem__(self.keys.pop(i), self.values.pop(i))
            except ValueError, IndexError:
                raise KeyError("No such key-value pair!!")
        return super().__getitem__(key)

Usage:

>>> a = [1,2,3,4]
>>> b = [1,2,2,3]
>>> c = LazyDict(a,b)
>>> c[1]
1
>>> c[4]
3
>>> c[2]
2
>>> c[3]
2
>>> d = LazyDict(a,b)
>>> d.items()
dict_items([])

How can I delete all of my Git stashes at once?

if you want to remove the latest stash or at any particular index -

git stash drop type_your_index

> git stash list

  stash@{0}: abc
  stash@{1}: xyz
  stash@{1}: pqr

> git stash drop 0

  Dropped refs/stash@{0}

> git stash list

  stash@{0}: xyz
  stash@{1}: pqr

if you want to remove all the stash at once -

> git stash clear
>

> git stash list
>

Warning : Once done you can not revert back your stash

How do I properly compare strings in C?

Whenever you are trying to compare the strings, compare them with respect to each character. For this you can use built in string function called strcmp(input1,input2); and you should use the header file called #include<string.h>

Try this code:

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

int main() 
{ 
    char s[]="STACKOVERFLOW";
    char s1[200];
    printf("Enter the string to be checked\n");//enter the input string
    scanf("%s",s1);
    if(strcmp(s,s1)==0)//compare both the strings  
    {
        printf("Both the Strings match\n"); 
    } 
    else
    {
        printf("Entered String does not match\n");  
    } 
    system("pause");  
} 

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

Exit VS and delete the (project)\.vs\applicationhost.config file. Restart VS. It should start working.

Get checkbox values using checkbox name using jquery

You are selecting inputs with name attribute of "bla", but your inputs have "bla[]" name attribute.

$("input[name='bla[]']").each(function (index, obj) {
        // loop all checked items
    });

http://jsfiddle.net/26axX/

What is the difference between id and class in CSS, and when should I use them?

ID's have the functionality to work as links to particular sections within a webpage. a keyword after # tag will take you to a particular section of the webpage. e.g "http://exampleurl.com#chapter5" in the address bar will take you there when you have a "section5" id wrapped around the chapter 5 section of the page.

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

how to get the current working directory's absolute path from irb

File.expand_path File.dirname(__FILE__) will return the directory relative to the file this command is called from.

But Dir.pwd returns the working directory (results identical to executing pwd in your terminal)

how to use javascript Object.defineProperty

yes no more function extending for setup setter & getter this is my example Object.defineProperty(obj,name,func)

var obj = {};
['data', 'name'].forEach(function(name) {
    Object.defineProperty(obj, name, {
        get : function() {
            return 'setter & getter';
        }
    });
});


console.log(obj.data);
console.log(obj.name);

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

To understand this, you must take a step back. In OO, the customer owns the orders (orders are a list in the customer object). There can't be an order without a customer. So the customer seems to be the owner of the orders.

But in the SQL world, one item will actually contain a pointer to the other. Since there is 1 customer for N orders, each order contains a foreign key to the customer it belongs to. This is the "connection" and this means the order "owns" (or literally contains) the connection (information). This is exactly the opposite from the OO/model world.

This may help to understand:

public class Customer {
     // This field doesn't exist in the database
     // It is simulated with a SQL query
     // "OO speak": Customer owns the orders
     private List<Order> orders;
}

public class Order {
     // This field actually exists in the DB
     // In a purely OO model, we could omit it
     // "DB speak": Order contains a foreign key to customer
     private Customer customer;
}

The inverse side is the OO "owner" of the object, in this case the customer. The customer has no columns in the table to store the orders, so you must tell it where in the order table it can save this data (which happens via mappedBy).

Another common example are trees with nodes which can be both parents and children. In this case, the two fields are used in one class:

public class Node {
    // Again, this is managed by Hibernate.
    // There is no matching column in the database.
    @OneToMany(cascade = CascadeType.ALL) // mappedBy is only necessary when there are two fields with the type "Node"
    private List<Node> children;

    // This field exists in the database.
    // For the OO model, it's not really necessary and in fact
    // some XML implementations omit it to save memory.
    // Of course, that limits your options to navigate the tree.
    @ManyToOne
    private Node parent;
}

This explains for the "foreign key" many-to-one design works. There is a second approach which uses another table to maintain the relations. That means, for our first example, you have three tables: The one with customers, the one with orders and a two-column table with pairs of primary keys (customerPK, orderPK).

This approach is more flexible than the one above (it can easily handle one-to-one, many-to-one, one-to-many and even many-to-many). The price is that

  • it's a bit slower (having to maintain another table and joins uses three tables instead of just two),
  • the join syntax is more complex (which can be tedious if you have to manually write many queries, for example when you try to debug something)
  • it's more error prone because you can suddenly get too many or too few results when something goes wrong in the code which manages the connection table.

That's why I rarely recommend this approach.

Use jquery click to handle anchor onClick()

<div class = "solTitle"> <a href = "#"  id = "solution0" onClick = "openSolution();">Solution0 </a></div> <br>

<div class= "solTitle"> <a href = "#"  id = "solution1" onClick = "openSolution();">Solution1 </a></div> <br>



$(document).ready(function(){
    $('.solTitle a').click(function(e) {
        e.preventDefault();
        alert('here in');
         var divId = 'summary' +$(this).attr('id');

        document.getElementById(divId).className = ''; /* or $('#'+divid).removeAttr('class'); */

    });
 });

I changed few things:

  1. remove the onclick attr and bind click event inside the document.ready
  2. changed solTitle to be an ID to a CLASS: id cant be repeated

Get column from a two dimensional array

var data = [
    ["a1", "a2", "a3"],
    ["b1", "b2", "b3"],
    ["c1", "c2", "c3"]
];

var col0 = data.map(d => d[0]); // [ 'a1', 'b1', 'c1' ]

var col1 = data.map(d => d[1]); // [ 'a2', 'b2', 'c2' ]

How do I download a package from apt-get without installing it?

Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).

apt-get install -d -o=dir::cache=/tmp whateveryouwant

How to check if "Radiobutton" is checked?

You can also maintain a flag value based on listener,

 radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                //handle the boolean flag here. 
                  if(arg1==true)
                         //Do something

                else 
                    //do something else

            }
        });

Or simply isChecked() can also be used to check the state of your RadioButton.

Here is a link to a sample,

http://www.mkyong.com/android/android-radio-buttons-example/

And then based on the flag you can execute your function.

Using Service to run background and create notification

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

  1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <Button
            android:id="@+id/sendNotifications"
            android:onClick="onSendNotificationsButtonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start Sending Notifications Every 2 Hours!" />
    </RelativeLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onSendNotificationsButtonClick(View view) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }   
    }
    

    and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

  2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

    Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

    Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

    NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

    NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

    NotificationEventReceiver.java

    public class NotificationEventReceiver extends WakefulBroadcastReceiver {
    
        private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
        private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
        private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    
        public static void setupAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent alarmIntent = getStartPendingIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    getTriggerAt(new Date()),
                    NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                    alarmIntent);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Intent serviceIntent = null;
            if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
            } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
            }
    
            if (serviceIntent != null) {
                startWakefulService(context, serviceIntent);
            }
        }
    
        private static long getTriggerAt(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
            return calendar.getTimeInMillis();
        }
    
        private static PendingIntent getStartPendingIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static PendingIntent getDeleteIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_DELETE_NOTIFICATION);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }
    
  3. Now let's create an IntentService to actually create notifications.

    There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

    If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

    NotificationIntentService.java

    public class NotificationIntentService extends IntentService {
    
        private static final int NOTIFICATION_ID = 1;
        private static final String ACTION_START = "ACTION_START";
        private static final String ACTION_DELETE = "ACTION_DELETE";
    
        public NotificationIntentService() {
            super(NotificationIntentService.class.getSimpleName());
        }
    
        public static Intent createIntentStartNotificationService(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_START);
            return intent;
        }
    
        public static Intent createIntentDeleteNotification(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_DELETE);
            return intent;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
            try {
                String action = intent.getAction();
                if (ACTION_START.equals(action)) {
                    processStartNotification();
                }
                if (ACTION_DELETE.equals(action)) {
                    processDeleteNotification(intent);
                }
            } finally {
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
            }
        }
    
        private void processDeleteNotification(Intent intent) {
            // Log something?
        }
    
        private void processStartNotification() {
            // Do something. For example, fetch fresh data from backend to create a rich notification?
    
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Scheduled Notification")
                    .setAutoCancel(true)
                    .setColor(getResources().getColor(R.color.colorAccent))
                    .setContentText("This notification has been triggered by Notification Service")
                    .setSmallIcon(R.drawable.notification_icon);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    NOTIFICATION_ID,
                    new Intent(this, NotificationActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
    
            final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_ID, builder.build());
        }
    }
    
  4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

    NotificationServiceStarterReceiver.java

    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationEventReceiver.setupAlarm(context);
        }
    }
    
  5. We need to also register all our services, broadcast receivers in AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="klogi.com.notificationbyschedule">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <service
                android:name=".notifications.NotificationIntentService"
                android:enabled="true"
                android:exported="false" />
    
            <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
            <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                    <action android:name="android.intent.action.TIME_SET" />
                </intent-filter>
            </receiver>
    
            <activity
                android:name=".NotificationActivity"
                android:label="@string/title_activity_notification"
                android:theme="@style/AppTheme.NoActionBar"/>
        </application>
    
    </manifest>
    

That's it!

The source code for this project you can find here. I hope, you will find this post helpful.

Passing bash variable to jq

Posting it here as it might help others. In string it might be necessary to pass the quotes to jq. To do the following with jq:

.items[] | select(.name=="string")

in bash you could do

EMAILID=$1
projectID=$(cat file.json | jq -r '.resource[] | select(.username=='\"$EMAILID\"') | .id')

essentially escaping the quotes and passing it on to jq

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

Detecting attribute change of value of an attribute I made

There is this extensions that adds an event listener to attribute changes.

Usage:

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
  src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>

Bind attrchange handler function to selected elements

$(selector).attrchange({
    trackValues: true, /* Default to false, if set to true the event object is 
                updated with old and new value.*/
    callback: function (event) { 
        //event               - event object
        //event.attributeName - Name of the attribute modified
        //event.oldValue      - Previous value of the modified attribute
        //event.newValue      - New value of the modified attribute
        //Triggered when the selected elements attribute is added/updated/removed
    }        
});

iOS 7 - Status bar overlaps the view

My status bar and navigation bar overlap after return from landscape view of YTPlayer. Here is my solution after trying @comonitos' version but not work on my iOS 8

- (void)fixNavigationBarPosition {
    if (self.navigationController) {
        CGRect frame = self.navigationController.navigationBar.frame;
        if (frame.origin.y != 20.f) {
            frame.origin.y = 20.f;
            self.navigationController.navigationBar.frame = frame;
        }
    }
}

Just call this function whenever you want to fix the position of navigation bar. I called on YTPlayerViewDelegate's playerView:didChangeToState:

- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {
    switch (state) {
        case kYTPlayerStatePaused:
        case kYTPlayerStateEnded:
            [self fixNavigationBarPosition];
            break;
        default:
    }
}

github changes not staged for commit

I kept receiving the same message no matter what i did.

To fix this, i removed .gitignore and i am not getting the Github changes not staged for commit message anymore. Before it would allow me to commit once when i ran git add . and then after it would bring up the same message.

Im not sure why the .gitignore file was causing a problem but i added on my local machine and most likely didn't sync it up properly.

Javascript Array.sort implementation?

I think that would depend on what browser implementation you are refering to.

Every browser type has it's own javascript engine implementation, so it depends. You could check the sourcecode repos for Mozilla and Webkit/Khtml for different implementations.

IE is closed source however, so you may have to ask somebody at microsoft.

How to convert string date to Timestamp in java?

You can convert String to Timestamp:

String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

Android screen size HDPI, LDPI, MDPI

UPDATE: 30.07.2014

If you use Android Studio, make sure you have at least 144x144 resource and than use "FILE-NEW-IMAGE ASSET". Android Studio will make proper image files to all folders for you : )


As documentation says, adjust bitmaps as follows:

Almost every application should have alternative drawable resources for different screen densities, because almost every application has a launcher icon and that icon should look good on all screen densities. Likewise, if you include other bitmap drawables in your application (such as for menu icons or other graphics in your application), you should provide alternative versions or each one, for different densities.

Note: You only need to provide density-specific drawables for bitmap files (.png, .jpg, or .gif) and Nine-Path files (.9.png). If you use XML files to define shapes, colors, or other drawable resources, you should put one copy in the default drawable directory (drawable/).

To create alternative bitmap drawables for different densities, you should follow the 3:4:6:8 scaling ratio between the four generalized densities. For example, if you have a bitmap drawable that's 48x48 pixels for medium-density screen (the size for a launcher icon), all the different sizes should be:

36x36 for low-density (LDPI)

48x48 for medium-density (MDPI)

72x72 for high-density (HDPI)

96x96 for extra high-density (XHDPI)

144x144 for extra extra high-density (XXHDPI)

192x192 for extra extra extra high-density (XXXHDPI)

Best Way to read rss feed in .net Using C#

Use this :

private string GetAlbumRSS(SyndicationItem album)
    {

        string url = "";
        foreach (SyndicationElementExtension ext in album.ElementExtensions)
            if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
        return (url);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string albumRSS;
        string url = "http://www.SomeSite.com/rss?";
        XmlReader r = XmlReader.Create(url);
        SyndicationFeed albums = SyndicationFeed.Load(r);
        r.Close();
        foreach (SyndicationItem album in albums.Items)
        {

            cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
            albumRSS = GetAlbumRSS(album);

        }



    }

Get the Id of current table row with Jquery

You can use .closest() to get up to the current <tr> parent, like this:

$('input[type=button]' ).click(function() {
   var bid = this.id; // button ID 
   var trid = $(this).closest('tr').attr('id'); // table row ID 
 });

Laravel update model with unique validation rule for attribute

I had the same problem. What I've done: add in my view hidden field with id of a model and in validator check the unique, only if I've get some id from view.

$this->validate(
        $request,
        [
            'index'       => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
            'name'        => 'required',
            'surname'     => 'required',
        ]
);

REST API Best practices: Where to put parameters?

"Pack" and POST your data against the "context" that universe-resource-locator provides, which means #1 for the sake of the locator.

Mind the limitations with #2. I prefer POSTs to #1.

note: limitations are discussed for

POST in Is there a max size for POST parameter content?

GET in Is there a limit to the length of a GET request? and Max size of URL parameters in _GET

p.s. these limits are based on the client capabilities (browser) and server(configuration).