Programs & Examples On #Chdir

chdir (or cd) is a command to change the working directory (change directory). It is part of many operating systems and programming languages. On many OS `chdir()` also is a system call.

React Native Error: ENOSPC: System limit for number of file watchers reached

Late answer, and there are many good answers already.

In case you want a simple script to check if the maximum file watches is big enough, and if not, increase the limit, here it is:

#!/usr/bin/env bash

let current_watches=`sysctl -n fs.inotify.max_user_watches`

if (( current_watches < 80000 ))
then
  echo "Current max_user_watches ${current_watches} is less than 80000."
else
  echo "Current max_user_watches ${current_watches} is already equal to or greater than 80000."
  exit 0
fi

if sudo sysctl -w fs.inotify.max_user_watches=80000 && sudo sysctl -p && echo fs.inotify.max_user_watches=80000 | sudo tee /etc/sysctl.d/10-user-watches.conf
then
  echo "max_user_watches changed to 80000."
else
  echo "Could not change max_user_watches."
  exit 1
fi

The script increases the limit to 80000, but feel free to set a limit that you want.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

How to test that a registered variable is not empty?

when: myvar | default('', true) | trim != ''

I use | trim != '' to check if a variable has an empty value or not. I also always add the | default(..., true) check to catch when myvar is undefined too.

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

ansible : how to pass multiple commands

Here is worker like this. \o/

- name: "Exec items"
  shell: "{{ item }}"
  with_items:
    - echo "hello"
    - echo "hello2"

VBA macro that search for file in multiple subfolders

I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.

Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant

For Each vFile In colFiles
     'file operation here or store file name/path in a string array for use later in the script
     filepath(n) = vFile
     filename = fso.GetFileName(vFile) 'If you want the filename without full path
     n=n+1
Next vFile


'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
    colFiles.Add strFolder & strTemp
    strTemp = Dir
Loop
If bIncludeSubfolders Then

    strTemp = Dir(strFolder, vbDirectory)
    Do While strTemp <> vbNullString
        If (strTemp <> ".") And (strTemp <> "..") Then
            If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
                colFolders.Add strTemp
            End If
        End If
        strTemp = Dir
    Loop
    'Call RecursiveDir for each subfolder in colFolders
    For Each vFolderName In colFolders
        Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
    Next vFolderName
End If
End Function

Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
    If Right(strFolder, 1) = "\" Then
        TrailingSlash = strFolder
    Else
        TrailingSlash = strFolder & "\"
    End If
End If
End Function

This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).

Change working directory in my current shell context when running Node script

There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');
process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.

How to open a workbook specifying its path

You can also open a required file through a prompt, This helps when you want to select file from different path and different file.

Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant

NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")

If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub

Why do I get a SyntaxError for a Unicode escape in my file path?

C:\\Users\\expoperialed\\Desktop\\Python This syntax worked for me.

Python: OSError: [Errno 2] No such file or directory: ''

I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

Python: SyntaxError: non-keyword after keyword arg

It's just what it says:

inputFile = open((x), encoding = "utf8", "r")

You have specified encoding as a keyword argument, but "r" as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:

inputFile = open((x), "r", encoding = "utf8")

Python: How to use RegEx in an if statement?

First you compile the regex, then you have to use it with match, find, or some other method to actually run it against some input.

import os
import re
import shutil

def test():
    os.chdir("C:/Users/David/Desktop/Test/MyFiles")
    files = os.listdir(".")
    os.mkdir("C:/Users/David/Desktop/Test/MyFiles2")
    pattern = re.compile(regex_txt, re.IGNORECASE)
    for x in (files):
        with open((x), 'r') as input_file:
            for line in input_file:
                if pattern.search(line):
                    shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")
                    break

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

How to count objects in PowerShell?

As short as @jumbo's answer is :-) you can do it even more tersely. This just returns the Count property of the array returned by the antecedent sub-expression:

@(Get-Alias).Count

A couple points to note:

  1. You can put an arbitrarily complex expression in place of Get-Alias, for example:

    @(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
    
  2. The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count property to exist by forcing the output to be an array.)

2012.01.30 Update

The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count property even for singletons, so the at-sign becomes unimportant for this scenario.

How do I use JDK 7 on Mac OSX?

Get cask

brew tap caskroom/cask

Install java7:

brew tap caskroom/versions
brew cask install java7

(I had difficulty finding the download link of java7 on oracle website, as they're just "recommending" java8 )

EDIT January 2018 (As pointed by Ankur):

Use zulu7 cask. Zulu is a certified build of OpenJDK produced by Azul Systems that should be around for a long time (they even offer JDK6 builds still).

brew cask install caskroom/versions/zulu7

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

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

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

Downloading a picture via urllib and python

Aside from suggesting you read the docs for retrieve() carefully (http://docs.python.org/library/urllib.html#urllib.URLopener.retrieve), I would suggest actually calling read() on the content of the response, and then saving it into a file of your choosing rather than leaving it in the temporary file that retrieve creates.

List Directories and get the name of the Directory

Listing the entries in the current directory (for directories in os.listdir(os.getcwd()):) and then interpreting those entries as subdirectories of an entirely different directory (dir = os.path.join('/home/user/workspace', directories)) is one thing that looks fishy.

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

this solution is robust even in executables

import inspect, os.path

filename = inspect.getframeinfo(inspect.currentframe()).filename
path     = os.path.dirname(os.path.abspath(filename))

Run a string as a command within a Bash script

You can use eval to execute a string:

eval $illcommando

How to do a newline in output

You can do this all in the File.open block:

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'

File.open playlist_name, 'w' do |f|
  music.each do |z|
    f.puts z
  end
end

python: Change the scripts working directory to the script's own directory

Change your crontab command to

* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)

The (...) starts a sub-shell that your crond executes as a single command. The || exit 1 causes your cronjob to fail in case that the directory is unavailable.

Though the other solutions may be more elegant in the long run for your specific scripts, my example could still be useful in cases where you can't modify the program or command that you want to execute.

How to have the cp command create any necessary folders for copying a file to a destination

I didn't know you could do that with cp.

You can do it with mkdir ..

mkdir -p /var/path/to/your/dir

EDIT See lhunath's answer for incorporating cp.

How can I find the location of origin/master in git, and how do I change it?

I was wondering the same thing about my repo. In my case I had an old remote that I wasn't pushing to anymore so I needed to remove it.

Get list of remotes:

git remote

Remove the one that you don't need

git remote rm {insert remote to remove}

How to resolve symbolic links in a shell script

function realpath {
    local r=$1; local t=$(readlink $r)
    while [ $t ]; do
        r=$(cd $(dirname $r) && cd $(dirname $t) && pwd -P)/$(basename $t)
        t=$(readlink $r)
    done
    echo $r
}

#example usage
SCRIPT_PARENT_DIR=$(dirname $(realpath "$0"))/..

C++ calling base class constructors

The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.

Rectangle(int h,int w):
   Shape(h,w)
  {...}

Will call the other base class constructor.

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

Transfer data from one HTML file to another

<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>

<body>

<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>

</body>

client side scripting

function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}

jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.

jquery load function http://api.jquery.com/load/

Check if TextBox is empty and return MessageBox?

if (MaterialTextBox.Text.length==0)
{
message

}

Remove trailing zeros

Trying to do more friendly solution of DecimalToString (https://stackoverflow.com/a/34486763/3852139):

private static decimal Trim(this decimal value)
{
    var s = value.ToString(CultureInfo.InvariantCulture);
    return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
        ? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
        : value;
}

private static decimal? Trim(this decimal? value)
{
    return value.HasValue ? (decimal?) value.Value.Trim() : null;
}

private static void Main(string[] args)
{
    Console.WriteLine("=>{0}", 1.0000m.Trim());
    Console.WriteLine("=>{0}", 1.000000023000m.Trim());
    Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
    Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}

Output:

=>1
=>1.000000023
=>1.000000023
=>

AngularJS: How to make angular load script inside ng-include?

This won't work anymore from 1.2.0-rc1. See this issue for more about it, in which I posted a comment describing a quick workaround. I'll share it here as well :

// Quick fix : replace the script tag you want to load by a <div load-script></div>.
// Then write a loadScript directive that creates your script tag and appends it to your div.
// Took me one minute.

// This means that in your view, instead of :
<script src="/path/to/my/file.js"></script>

// You'll have :
<div ng-load-script></div>

// And then write a directive like :
angular.module('myModule', []).directive('loadScript', [function() {
    return function(scope, element, attrs) {
        angular.element('<script src="/path/to/my/file.js"></script>').appendTo(element);
    }
}]);

Not the best solution ever, but hey, neither is putting script tags in subsequent views. In my case I have to do this is order to use Facebook/Twitter/etc. widgets.

jQuery Validation using the class instead of the name value

You can add the rules based on that selector using .rules("add", options), just remove any rules you want class based out of your validate options, and after calling $(".formToValidate").validate({... });, do this:

$(".checkBox").rules("add", { 
  required:true,  
  minlength:3
});

Equivalent of Oracle's RowID in SQL Server

If you want to permanently number the rows in the table, Please don't use the RID solution for SQL Server. It will perform worse than Access on an old 386. For SQL Server simply create an IDENTITY column, and use that column as a clustered primary key. This will place a permanent, fast Integer B-Tree on the table, and more importantly every non-clustered index will use it to locate rows. If you try to develop in SQL Server as if it's Oracle you'll create a poorly performing database. You need to optimize for the engine, not pretend it's a different engine.

also, please don't use the NewID() to populate the Primary Key with GUIDs, you'll kill insert performance. If you must use GUIDs use NewSequentialID() as the column default. But INT will still be faster.

If on the other hand, you simply want to number the rows that result from a query, use the RowNumber Over() function as one of the query columns.

Get the week start date and week end date from week number

Here is another version. If your Scenario requires Saturday to be 1st day of Week and Friday to be last day of Week, the below code will handle that:

  DECLARE @myDate DATE = GETDATE()
  SELECT    @myDate,
    DATENAME(WEEKDAY,@myDate),
    DATEADD(DD,-(CHOOSE(DATEPART(dw, @myDate), 1,2,3,4,5,6,0)),@myDate) AS WeekStartDate,
    DATEADD(DD,7-CHOOSE(DATEPART(dw, @myDate), 2,3,4,5,6,7,1),@myDate) AS WeekEndDate

Screenshot of Query

How do I run Python code from Sublime Text 2?

Cool U guys, I just found this:

http://ptomato.wordpress.com/2012/02/09/geek-tip-running-python-guis-in-sublime-text-2/

It explains (like one of the answers above) how to edit this exec.py in the default directory.

I had the problem that my PYTHON UI APPLICATION would not start. I commented out the last line from the following snipped:

    # Hide the console window on Windows
    startupinfo = None
    if os.name == "nt":
        startupinfo = subprocess.STARTUPINFO()
        #startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

and, taaadaaaa, I could start my app by pressing Ctrl+B. Funny line anyways, uh? And a big thank you to whoever wrote that article ;-)

Why are my CSS3 media queries not working on mobile devices?

I use a few methods depending. In the same stylesheet i use: @media (max-width: 450px), or for separate make sure you have the link in the header correctly. I had a look at your fixmeup and you have a confusing array of links to css. It acts as you say also on HTC desire S.

How to copy a selection to the OS X clipboard

I am currently on OS X 10.9 and my efforts to compile vim with +xterm_clipboard brought me nothing. So my current solution is to use MacVim in terminal mode with option set clipboard=unnamed in my ~/.vimrc file. Works perfect for me.

Firebase FCM force onTokenRefresh() to be called

Guys it has very simple solution

https://developers.google.com/instance-id/guides/android-implementation#generate_a_token

Note: If your app used tokens that were deleted by deleteInstanceID, your app will need to generate replacement tokens.

In stead of deleting instance Id, delete only token:

String authorizedEntity = PROJECT_ID;
String scope = "GCM";
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

Checking for empty result (php, pdo, mysql)

Even though this is an old thread, I thought I would weigh in as I had to deal with this lately.

You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

//I would usually put this all in a try/catch block, but kept it the same for continuity
if(!$sth->execute(array(':today'=>$today))) 
{
    $db = null ;
    exit();
}

$result = $sth->fetch(PDO::FETCH_OBJ)

if(!isset($result->id_email))
{
    echo "empty";
}
else
{
    echo "not empty, value is $result->id_email";
}

$db = null;

Of course this is only for a single result, as you might have when looping over a dataset.

Official reasons for "Software caused connection abort: socket write error"

ssl client side will throw such exception in below situation(I had tested), :

server is asked to authenticate client certificate, but the client provide a certificate which Extended Key Usage donot support client auth.

Create a new txt file using VB.NET

You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:

Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
   System.IO.File.Create(filepath).Dispose()
End If

HTTP Basic Authentication - what's the expected web browser experience?

To help everyone avoid confusion, I will reformulate the question in two parts.

First : "how can make an authenticated HTTP request with a browser, using BASIC auth?".

In the browser you can do a http basic auth first by waiting the prompt to come, or by editing the URL if you follow this format: http://myusername:[email protected]

NB: the curl command mentionned in the question is perfectly fine, if you have a command-line and curl installed. ;)

References:

Also according to the CURL manual page https://curl.haxx.se/docs/manual.html

HTTP

  Curl also supports user and password in HTTP URLs, thus you can pick a file
  like:

      curl http://name:[email protected]/full/path/to/file

  or specify user and password separately like in

      curl -u name:passwd http://machine.domain/full/path/to/file

  HTTP offers many different methods of authentication and curl supports
  several: Basic, Digest, NTLM and Negotiate (SPNEGO). Without telling which
  method to use, curl defaults to Basic. You can also ask curl to pick the
  most secure ones out of the ones that the server accepts for the given URL,
  by using --anyauth.

  NOTE! According to the URL specification, HTTP URLs can not contain a user
  and password, so that style will not work when using curl via a proxy, even
  though curl allows it at other times. When using a proxy, you _must_ use
  the -u style for user and password.

The second and real question is "However, on somesite.com, I'm not getting an authorization prompt at all, just a page that says I'm not authorized. Did somesite not implement the Basic Auth workflow correctly, or is there something else I need to do?"

The curl documentation says the -u option supports many method of authentication, Basic being the default.

How to make a smaller RatingBar?

There is no need to add a listener to the ?android:attr/ratingBarStyleSmall. Just add android:isIndicator=false and it will capture click events, e.g.

<RatingBar
  android:id="@+id/myRatingBar"
  style="?android:attr/ratingBarStyleSmall"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:numStars="5"
  android:isIndicator="false" />

jQuery and TinyMCE: textarea value doesn't submit

You can also simply use the jQuery plugin and package for TinyMCE it sorts out these kinds of issues.

javascript multiple OR conditions in IF statement

Each of the three conditions is evaluated independently[1]:

id != 1 // false
id != 2 // true
id != 3 // true

Then it evaluates false || true || true, which is true (a || b is true if either a or b is true). I think you want

id != 1 && id != 2 && id != 3

which is only true if the ID is not 1 AND it's not 2 AND it's not 3.

[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.

How do I import the javax.servlet API in my Eclipse project?

Quick Fix- This worked in Eclipse - Right Click on project -> Properties -> Java Build Path (Tab) -> Add External JARs -> locate the servlet api jar implementation (if Tomcat - its named servlet-api.jar) -> click OK. That's it !!

How to retrieve form values from HTTPPOST, dictionary or?

You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:

[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
    var value1 = model.SimpleProp1;
    var value2 = model.SimpleProp2;
    var value3 = model.ComplexProp1.SimpleProp1;
    ...

    ... return something ...
}

Another (obviously uglier) way is:

[HttpPost]
public ActionResult SubmitAction()
{
    var value1 = Request["SimpleProp1"];
    var value2 = Request["SimpleProp2"];
    var value3 = Request["ComplexProp1.SimpleProp1"];
    ...

    ... return something ...
}

Jackson JSON: get node name from json-tree

fields() and fieldNames() both were not working for me. And I had to spend quite sometime to find a way to iterate over the keys. There are two ways by which it can be done.

One is by converting it into a map (takes up more space):

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, Map.class);
for (String key : result.keySet())
{
    if(key.equals(foo))
    {
        //code here
    }
}

Another, by using a String iterator:

Iterator<String> it = jsonNode.getFieldNames();
while (it.hasNext())
{
    String key = it.next();
    if (key.equals(foo))
    {
         //code here
    }
}

How to install a specific version of a ruby gem?

Use the -v flag:

$ gem install fog -v 1.8

How do I declare an array with a custom class?

To default-initialize an array of Ts, T must be default constructible. Normally the compiler gives you a default constructor for free. However, since you declared a constructor yourself, the compiler does not generate a default constructor.

Your options:

  • add a default constructor to name, if that makes sense (I don't think so, but I don't know the problem domain);
  • initialize all the elements of the array upon declaration (you can do this because name is an aggregate);

      name someName[4] = { { "Arthur", "Dent" },
                           { "Ford", "Prefect" },
                           { "Tricia", "McMillan" },
                           { "Zaphod", "Beeblebrox" }
                         };
    
  • use a std::vector instead, and only add element when you have them constructed.

php check if array contains all array values from another array

The previous answers are all doing more work than they need to. Just use array_diff. This is the simplest way to do it:

$containsAllValues = !array_diff($search_this, $all);

That's all you have to do.

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

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

How do I float a div to the center?

If for some reason you have position absolute on the div, do this:

<div class="something"></div>

.something {
    position:absolute;
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto;
}

How to clean up R memory (without the need to restart my PC)?

An example under Linux (Fedora 16) shows that memory is freed when R is closed:

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       2854        974          0        344       1440                                                                                                                                                                    
-/+ buffers/cache:       1069       2759                                                                                                                                                                                                     
Swap:         4095         85       4010     

2854 megabytes is used. Next I open an R session and create a large matrix of random numbers:

m = matrix(runif(10e7), 10000, 1000)

when the matrix is created, 3714 MB is used:

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       3714        115          0        344       1442                                                                                                                                                                    
-/+ buffers/cache:       1927       1902                                                                                                                                                                                                     
Swap:         4095         85       4010     

After closing the R session, I nicely get back the memory I used (2856 MB free):

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       2856        972          0        344       1442                                                                                                                                                                    
-/+ buffers/cache:       1069       2759                                                                                                                                                                                                     
Swap:         4095         85       4010   

Ofcourse you use Windows, but you could repeat this excercise in Windows and report how the available memory develops before and after you create this large dataset in R.

Sort a Map<Key, Value> by values

    static <K extends Comparable<? super K>, V extends Comparable<? super V>>
    Map sortByValueInDescendingOrder(final Map<K, V> map) {
        Map re = new TreeMap(new Comparator<K>() {
            @Override
            public int compare(K o1, K o2) {
                if (map.get(o1) == null || map.get(o2) == null) {
                    return -o1.compareTo(o2);
                }
                int result = -map.get(o1).compareTo(map.get(o2));
                if (result != 0) {
                    return result;
                }
                return -o1.compareTo(o2);
            }
        });
        re.putAll(map);
        return re;
    }
    @Test(timeout = 3000l, expected = Test.None.class)
    public void testSortByValueInDescendingOrder() {
        char[] arr = "googler".toCharArray();
        Map<Character, Integer> charToTimes = new HashMap();
        for (int i = 0; i < arr.length; i++) {
            Integer times = charToTimes.get(arr[i]);
            charToTimes.put(arr[i], times == null ? 1 : times + 1);
        }
        Map sortedByTimes = sortByValueInDescendingOrder(charToTimes);
        Assert.assertEquals(charToTimes.toString(), "{g=2, e=1, r=1, o=2, l=1}");
        Assert.assertEquals(sortedByTimes.toString(), "{o=2, g=2, r=1, l=1, e=1}");
        Assert.assertEquals(sortedByTimes.containsKey('a'), false);
        Assert.assertEquals(sortedByTimes.get('a'), null);
        Assert.assertEquals(sortedByTimes.get('g'), 2);
        Assert.assertEquals(sortedByTimes.equals(charToTimes), true);
    }

Is it possible to use the SELECT INTO clause with UNION [ALL]?

The challenge I see with the solution:

FROM( 
SELECT top(100) *
    FROM Customers 
UNION
    SELECT top(100) *  
    FROM CustomerEurope 
UNION 
    SELECT top(100) *  
    FROM CustomerAsia 
UNION
    SELECT top(100) *  
    FROM CustomerAmericas
)

is that this creates a windowed data set that will reside in the RAM and on larger data sets this solution will create severe performance issues as it must first create the partition and then it will use the partition to write to the temp table.

A better solution would be the following:

SELECT top(100)* into #tmpFerdeen
FROM Customers

Insert into #tmpFerdeen
SELECT top(100)* 
FROM CustomerEurope

Insert into #tmpFerdeen
SELECT top(100)* 
FROM CustomerAsia

Insert into #tmpFerdeen
SELECT top(100)* 
FROM CustomerAmericas

to select insert into the temp table and then add additional rows. However the draw back here is if there are any duplicate rows in the data.

The Best Solution would be the following:

Insert into #tmpFerdeen
SELECT top(100)* 
FROM Customers
UNION
SELECT top(100)* 
FROM CustomerEurope
UNION
SELECT top(100)* 
FROM CustomerAsia
UNION
SELECT top(100)* 
FROM CustomerAmericas

This method should work for all purposes that require distinct rows. If, however, you want the duplicate rows simply swap out the UNION for UNION ALL

Best of luck!

how to set font size based on container size?

I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;

  • I have a container that changed size depending on the viewport using media queries
  • Text inside is dynamically generated
  • I want to scale up as well as down

Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)

_x000D_
_x000D_
var TextFit = function(){_x000D_
 var container = $('.container');_x000D_
  container.each(function(){_x000D_
    var container_width = $(this).width(),_x000D_
      width_offset = parseInt($(this).data('width-offset')),_x000D_
        font_container = $(this).find('.font-container');_x000D_
 _x000D_
     if ( width_offset > 0 ) {_x000D_
         container_width -= width_offset;_x000D_
     }_x000D_
                _x000D_
    font_container.each(function(){_x000D_
      var font_container_width = $(this).width(),_x000D_
          font_size = parseFloat( $(this).css('font-size') );_x000D_
_x000D_
      var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
 _x000D_
      var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
      _x000D_
      if (diff_percentage !== 0){_x000D_
          if ( container_width > font_container_width ) {_x000D_
            new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          } else if ( container_width < font_container_width ) {_x000D_
            new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          }_x000D_
      }_x000D_
      $(this).css('font-size', new_font_size + 'px');_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
  TextFit();_x000D_
  $(window).resize(function(){_x000D_
   TextFit();_x000D_
  });_x000D_
});
_x000D_
.container {_x000D_
  width:341px;_x000D_
  height:341px;_x000D_
  background-color:#000;_x000D_
  padding:20px;_x000D_
 }_x000D_
 .font-container {_x000D_
  font-size:131px;_x000D_
  text-align:center;_x000D_
  color:#fff;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container" data-width-offset="10">_x000D_
 <span class="font-container">£5000</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/Merch80/b8hoctfb/7/

click command in selenium webdriver does not work

A major thing to watch out for is whether a button is Enabled or not. You can still click them and nothing will fall over and the element is there but it is not ready to be clicked on so just doesnt do anything.

I've been using webdriver and its taken me most of the day to figure this out!

The following method seems to work reliably (in my environment for one button!)

    private void TryClick(By selector)
    {
        var wait = WaitUpTo(TimeSpan.FromSeconds(10));
        var element = wait.Until(ExpectedConditions.ElementIsVisible((selector)));

        //really important bit!
        WaitUpTo(TimeSpan.FromSeconds(5))
            .Until(d => element.Enabled);

        element.Click();
    }

you use it something like

TryClick(By.XPath("//button[contains(.//*,'Some Text')]"));

Difference between `constexpr` and `const`

According to book of "The C++ Programming Language 4th Editon" by Bjarne Stroustrup
const: meaning roughly ‘‘I promise not to change this value’’ (§7.5). This is used primarily to specify interfaces, so that data can be passed to functions without fear of it being modified.
The compiler enforces the promise made by const.
constexpr: meaning roughly ‘‘to be evaluated at compile time’’ (§10.4). This is used primarily to specify constants, to allow
For example:

const int dmv = 17; // dmv is a named constant
int var = 17; // var is not a constant
constexpr double max1 = 1.4*square(dmv); // OK if square(17) is a constant expression
constexpr double max2 = 1.4*square(var); // error : var is not a constant expression
const double max3 = 1.4*square(var); //OK, may be evaluated at run time
double sum(const vector<double>&); // sum will not modify its argument (§2.2.5)
vector<double> v {1.2, 3.4, 4.5}; // v is not a constant
const double s1 = sum(v); // OK: evaluated at run time
constexpr double s2 = sum(v); // error : sum(v) not constant expression

For a function to be usable in a constant expression, that is, in an expression that will be evaluated by the compiler, it must be defined constexpr.
For example:

constexpr double square(double x) { return x*x; }


To be constexpr, a function must be rather simple: just a return-statement computing a value. A constexpr function can be used for non-constant arguments, but when that is done the result is not a constant expression. We allow a constexpr function to be called with non-constant-expression arguments in contexts that do not require constant expressions, so that we don’t hav e to define essentially the same function twice: once for constant expressions and once for variables.
In a few places, constant expressions are required by language rules (e.g., array bounds (§2.2.5, §7.3), case labels (§2.2.4, §9.4.2), some template arguments (§25.2), and constants declared using constexpr). In other cases, compile-time evaluation is important for performance. Independently of performance issues, the notion of immutability (of an object with an unchangeable state) is an important design concern (§10.4).

Writing a VLOOKUP function in vba

How about just using:

result = [VLOOKUP(DATA!AN2, DATA!AA9:AF20, 5, FALSE)]

Note the [ and ].

Structure padding and packing

Structure packing is only done when you tell your compiler explicitly to pack the structure. Padding is what you're seeing. Your 32-bit system is padding each field to word alignment. If you had told your compiler to pack the structures, they'd be 6 and 5 bytes, respectively. Don't do that though. It's not portable and makes compilers generate much slower (and sometimes even buggy) code.

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

What is apache's maximum url length?

The default limit for the length of the request line is 8192 bytes = 8* 1024. It you want to change the limit, you have to add or update in your tomcat server.xml the attribut maxHttpHeaderSize.

as:

<Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />

In this example I set the limite to 65536 bytes= 64*1024.

Hope this will help.

Switch case with conditions

Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.

What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.

Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.

Like follow:

switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList

_x000D_
_x000D_
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
    alert('10');
    break;
case (cnt >= 21 && cnt <= 30 && cnt):
    alert('21');
    break;
case (cnt >= 31 && cnt <= 40 && cnt):
    alert('31');
    break;
default:
    alert('>41');
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>
_x000D_
_x000D_
_x000D_

ImageButton in Android

I think you already solved this problem, and as other answers suggested

android:background="@drawable/eye"

is available. But I prefer

android:src="@drawable/eye"
android:background="00000000" // transparent

and it works well too.(of course former code will set image as a background and the other will set image as a image) But according to your selected answer, I guess you meant 9-patch.

Convert between UIImage and Base64 string

Swift 5

Encoding

func convertImageToBase64String (img: UIImage) -> String {
    return img.jpegData(compressionQuality: 1)?.base64EncodedString() ?? ""
}

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image!
}

Note: Tested in xcode 10.2

Swift 4

Encoding

func convertImageToBase64String (img: UIImage) -> String {
    let imageData:NSData = UIImageJPEGRepresentation(img, 0.50)! as NSData //UIImagePNGRepresentation(img)
    let imgString = imageData.base64EncodedString(options: .init(rawValue: 0))
    return imgString
}

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image
}

Note: Tested in xcode 9.4.1

How to grey out a button?

The most easy solution is to set color filter to the background image of a button as I saw here

You can do as follow:

if ('need to set button disable')
    button.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
else
    button.getBackground().setColorFilter(null);

Hope I helped someone...

Base64 Decoding in iOS 7+

Swift 3+

let plainString = "foo"

Encoding

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

Decoding

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift < 3

let plainString = "foo"

Encoding

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

Decoding

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo

Objective-C

NSString *plainString = @"foo";

Encoding

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

Decoding

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

Conveniently map between enum and int / String

Int -->String :

public enum Country {

    US("US",0),
    UK("UK",2),
    DE("DE",1);


    private static Map<Integer, String> domainToCountryMapping; 
    private String country;
    private int domain;

    private Country(String country,int domain){
        this.country=country.toUpperCase();
        this.domain=domain;
    }

    public String getCountry(){
        return country;
    }


    public static String getCountry(String domain) {
        if (domainToCountryMapping == null) {
            initMapping();
        }

        if(domainToCountryMapping.get(domain)!=null){
            return domainToCountryMapping.get(domain);
        }else{
            return "US";
        }

    }

     private static void initMapping() {
         domainToCountryMapping = new HashMap<Integer, String>();
            for (Country s : values()) {
                domainToCountryMapping.put(s.domain, s.country);
            }
        }

Programmatically read from STDIN or input file in Perl

Do

$userinput =  <STDIN>; #read stdin and put it in $userinput
chomp ($userinput);    #cut the return / line feed character

if you want to read just one line

How to wait for 2 seconds?

Try this example:

exec DBMS_LOCK.sleep(5);

This is the whole script:

SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Start Date / Time" FROM DUAL;

exec DBMS_LOCK.sleep(5);

SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "End Date / Time" FROM DUAL;

How to make code wait while calling asynchronous calls like Ajax

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

Sending Arguments To Background Worker?

You can use the DoWorkEventArgs.Argument property.

A full example (even using an int argument) can be found on Microsoft's site:

Using a global variable with a thread

You just need to declare a as a global in thread2, so that you aren't modifying an a that is local to that function.

def thread2(threadname):
    global a
    while True:
        a += 1
        time.sleep(1)

In thread1, you don't need to do anything special, as long as you don't try to modify the value of a (which would create a local variable that shadows the global one; use global a if you need to)>

def thread1(threadname):
    #global a       # Optional if you treat a as read-only
    while a < 10:
        print a

How can I pass command-line arguments to a Perl program?

Depends on what you want to do. If you want to use the two arguments as input files, you can just pass them in and then use <> to read their contents.

If they have a different meaning, you can use GetOpt::Std and GetOpt::Long to process them easily. GetOpt::Std supports only single-character switches and GetOpt::Long is much more flexible. From GetOpt::Long:

use Getopt::Long;
my $data   = "file.dat";
my $length = 24;
my $verbose;
$result = GetOptions ("length=i" => \$length,    # numeric
                    "file=s"   => \$data,      # string
                    "verbose"  => \$verbose);  # flag

Alternatively, @ARGV is a special variable that contains all the command line arguments. $ARGV[0] is the first (ie. "string1" in your case) and $ARGV[1] is the second argument. You don't need a special module to access @ARGV.

Which programming language for cloud computing?

This is always fascinating. I am not a cloud developer, but based on my research there is nothing significantly different than what many of us have been doing off and on for decades. The server is platform specific. If you want to write platform agnostic code for your server that is fine, but unnecessary based on whoever your cloud server provider is. I think the biggest difference I've seen so far is the concept of providing a large set of services for the front end client to process. the front end, I'm assuming is predominantly web or web app development. As most browsers can handle LAMP vs Microsoft stack well enough, then you are still back to whatever your flavor of the month is. The only difference I truly am seeing from what I did 20 years ago in a highly distributed network environment are higher level protocol (HTTP vs. TCP/UDP). Maybe I am wrong and would welcome the education, but then again I've been doing this a long time and still have not seen anything I would consider revolutionary or significantly different, though languages like Java, C#, Python, Ruby, etc are significantly simpler to program in which is a mixed bag as the bar is lowered for those are are not familiar with writing optimized code. PAAS and SAAS to me seem to be some of the keys in the new technology, but been doing some of this to off and on for 20 years :)

Setting maxlength of textbox with JavaScript or jQuery

<head>
    <script type="text/javascript">
        function SetMaxLength () {
            var input = document.getElementById ("myInput");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id="myInput" type="text" size="20" />
</body>

AngularJS - How to use $routeParams in generating the templateUrl?

templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.

See the example.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.

I can’t find the Android keytool

No need to use the command line.

If you FILE-> "Export Android Application" in the ADK then it will allow you to create a key and then produce your .apk file.

What is the equivalent of Java static methods in Kotlin?

Docs recommends to solve most of the needs for static functions with package-level functions. They are simply declared outside a class in a source code file. The package of a file can be specified at the beginning of a file with the package keyword.

Declaration

package foo

fun bar() = {}

Usage

import foo.bar

Alternatively

import foo.*

You can now call the function with:

bar()

or if you do not use the import keyword:

foo.bar()

If you do not specify the package the function will be accessible from the root.

If you only have experience with java, this might seem a little strange. The reason is that kotlin is not a strictly object-oriented language. You could say it supports methods outside of classes.

Edit: They have edited the documentation to no longer include the sentence about recommending package level functions. This is the original that was referred to above.

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

How to linebreak an svg text within javascript?

I think this does what you want:

function ShowTooltip(evt, mouseovertext){
    // Make tooltip text        
    var tooltip_text = tt.childNodes.item(1);
    var words = mouseovertext.split("\\\n");
    var max_length = 0;

    for (var i=0; i<3; i++){
        tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
        length = tooltip_text.childNodes.item(i).getComputedTextLength();
        if (length > max_length) {max_length = length;}
    }

    var x = evt.clientX + 14 + max_length/2;
    var y = evt.clientY + 29;
    tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")

    // Make tooltip background
    bg.setAttributeNS(null,"width", max_length+15);
    bg.setAttributeNS(null,"height", words.length*15+6);
    bg.setAttributeNS(null,"x",evt.clientX+8);
    bg.setAttributeNS(null,"y",evt.clientY+14);

    // Show everything
    tt.setAttributeNS(null,"visibility","visible");
    bg.setAttributeNS(null,"visibility","visible");
}

It splits the text on \\\n and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:

<g id="tooltip" visibility="hidden">
    <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
</g>

This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.

How to enable file upload on React's Material UI simple input?

You need to wrap your input with component, and add containerElement property with value 'label' ...

<RaisedButton
   containerElement='label' // <-- Just add me!
   label='My Label'>
   <input type="file" />
</RaisedButton>

You can read more about it in this GitHub issue.

EDIT: Update 2019.

Check at the bottom answer from @galki

TLDR;

<input
  accept="image/*"
  className={classes.input}
  style={{ display: 'none' }}
  id="raised-button-file"
  multiple
  type="file"
/>
<label htmlFor="raised-button-file">
  <Button variant="raised" component="span" className={classes.button}>
    Upload
  </Button>
</label> 

Test if a property is available on a dynamic variable

Maybe use reflection?

dynamic myVar = GetDataThatLooksVerySimilarButNotTheSame();
Type typeOfDynamic = myVar.GetType();
bool exist = typeOfDynamic.GetProperties().Where(p => p.Name.Equals("PropertyName")).Any(); 

Styling a input type=number

I modified @LcSalazar's answer a bit... it's still not perfect because the background of the default buttons can still be seen in both Firefox, Chrome & Opera (not tested in Safari); but clicking on the arrows still works

Notes:

  • Adding pointer-events: none; allows you to click through the overlapping button, but then you can not style the button while hovered.
  • The arrows are visible in Edge, but don't work because Edge doesn't use arrows. It only adds an "x" to clear the input.

_x000D_
_x000D_
.number-wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.number-wrapper:after,_x000D_
.number-wrapper:before {_x000D_
  position: absolute;_x000D_
  right: 5px;_x000D_
  width: 1.6em;_x000D_
  height: .9em;_x000D_
  font-size: 10px;_x000D_
  pointer-events: none;_x000D_
  background: #fff;_x000D_
}_x000D_
_x000D_
.number-wrapper:after {_x000D_
  color: blue;_x000D_
  content: "\25B2";_x000D_
  margin-top: 1px;_x000D_
}_x000D_
_x000D_
.number-wrapper:before {_x000D_
  color: red;_x000D_
  content: "\25BC";_x000D_
  margin-bottom: 5px;_x000D_
  bottom: -.5em;_x000D_
}
_x000D_
<span class='number-wrapper'>_x000D_
    <input type="number" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

Fatal error: Call to undefined function mb_detect_encoding()

Under Windows / WAMP there doesn't seem to be any php_mbstring.dll dependencies on the GD2 extension, the MySQL extensions, nor on external dlls/libs:

deplister.exe ext\php_mbstring.dll

php5ts.dll,OK
MSVCR110.dll,OK
KERNEL32.dll,OK

deplister.exe ext\php_gd2.dll

php5ts.dll,OK
USER32.dll,OK
GDI32.dll,OK
KERNEL32.dll,OK
MSVCR110.dll,OK

Whatever php_mbstring already needs, it's built-in (statically compiled right into the DLL).

Call to undefined function mb_detect_encoding()

This error is also very specific and deterministic...

The function mb_detect_encoding() didn't fail because php_gd, php_mysql, php_mysqli, or another extension was not loaded; it simply was NOT found.

I'm guessing that all the answers that are reported as valid (for Windows / WAMP), that say to load other extensions, to change php.ini extension_dir paths (if this one was wrong to begin with, NO extensions would load), etc, work more due to a) un-commenting the extension = php_mbstring.dll line, or b) restarting Apache or the computer (for changes to take effect).

On Windows, most of the time the problem is that php_mbstring.dll is either:

  • Blocked by Windows. Unblock it by right-clicking it, check Properties.

  • Or PHP can't load php_mbstring.dll due to another version getting loaded (e.g., from some improper PHP DLLs install into C:\Windows\system32), some version mismatch, missing run-time DLLs, etc. Check Apache's and PHP's error log files first for clues.

More in-depth answer here: Call to undefined function mb_detect_encoding

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

In my case the problem was that GNOME keyring was holding an invalid passphrase for the ssh key to be used. After spending indecent amount of time troubleshooting this issue I ran seahorse and found the entry to hold empty string. I can only guess that it was caused by mistyping the passphrase at first use some time earlier, and then probably cancelling the requester or so in order to fall back to command line. Updating the entry with correct passphrase immediately solved the problem. Deleting that entry (from "login" keyring) and reentering passphrase at that first prompt (and checking the appropriate checkbox) solves this too. Now agent gets the correct passphrase from the unlocked at login keyring named "login" and neither asks for passphrase nor "refuses operation" anymore. Of course YMMV.

Docker compose, running containers in net:host

Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode when using the v2 YAML format.

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

The Java Naming and Directory InterfaceTM (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the JavaTM programming language. It is defined to be independent of any specific directory service implementation. Thus a variety of directories(new, emerging, and already deployed) can be accessed in a common way.

What is its basic use?

Most of it is covered in the above answer but I would like to provide architecture here so that above will make more sense.

enter image description here

To use the JNDI, you must have the JNDI classes and one or more service providers. The Java 2 SDK, v1.3 includes three service providers for the following naming/directory services:

  1. Lightweight Directory Access Protocol (LDAP)
  2. Common Object Request Broker Architecture (CORBA) Common Object Services (COS) name service
  3. Java Remote Method Invocation (RMI) Registry

So basically you create objects and register them on the directory services which you can later do lookup and execute operation on.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

Recover from git reset --hard?

(answer suitable for a subset of users)

If you're on (any recent) macOS, and even if you're away from your Time Machine disk, the OS will have saved hourly backups, called local snapshots.

Enter Time Machine and navigate to the file you lost. The OS will then ask you:

The location to which you're restoring "file.ext" already contains an
item with the same name. Do you want to replace it with the one you're
restoring?

You should be able to recover the file(s) you lost.

MySQL root access from all hosts

I'm using AWS LightSail and for my instance to work, I had to change:

bind-address = 127.0.0.1

to

bind-address = <Private IP Assigned by Amazon>

Then I was able to connect remotely.

Check If array is null or not in php

Corrected;

/*
 return true if the array is not empty
 return false if it is empty
*/
function is_array_empty($arr){
  if(is_array($arr)){     
      foreach($arr as $key => $value){
          if(!empty($value) || $value != NULL || $value != ""){
              return true;
              break;//stop the process we have seen that at least 1 of the array has value so its not empty
          }
      }
      return false;
  }
}

Visual Studio Code - Convert spaces to tabs

There are 3 options in .vscode/settings.json:

// The number of spaces a tab is equal to.
"editor.tabSize": 4,

// Insert spaces when pressing Tab.
"editor.insertSpaces": true,

// When opening a file, `editor.tabSize` and `editor.insertSpaces` will be detected based on the file contents.
"editor.detectIndentation": true

editor.detectIndentation detects it from your file, you have to disable it. If it didn't help, check that you have no settings with higher priority. For example when you save it to User settings it could be overwritten by Workspace settings which are in your project folder.

Update:

You may just open File » Preferences » Settings or use shortcut:

CTRL+, (Windows, Linux)

?+, (Mac)

Update:

Now you have alternative to editing those options manually.
Click on selector Spaces:4 at the bottom-right of the editor:
 Ln44, Col .  [Spaces:4] . UTF-8 with BOM . CTRLF . HTML . :)

When you want to convert existing ws to tab, install extension from Marketplace
EDIT:
To convert existing indentation from spaces to tabs hit Ctrl+Shift+P and type:

>Convert indentation to Tabs

This will change the indentation for your document based on the defined settings to Tabs.

Passing $_POST values with cURL

<?php
    function executeCurl($arrOptions) {

        $mixCH = curl_init();

        foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
            curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
        }

        $mixResponse = curl_exec($mixCH);
        curl_close($mixCH);
        return $mixResponse;
    }

    // If any HTTP authentication is needed.
    $username = 'http-auth-username';
    $password = 'http-auth-password';

    $requestType = 'POST'; // This can be PUT or POST

    // This is a sample array. You can use $arrPostData = $_POST
    $arrPostData = array(
        'key1'  => 'value-1-for-k1y-1',
        'key2'  => 'value-2-for-key-2',
        'key3'  => array(
                'key31'   => 'value-for-key-3-1',
                'key32'   => array(
                    'key321' => 'value-for-key321'
                )
        ),
        'key4'  => array(
            'key'   => 'value'
        )
    );

    // You can set your post data
    $postData = http_build_query($arrPostData); // Raw PHP array

    $postData = json_encode($arrPostData); // Only USE this when request JSON data.

    $mixResponse = executeCurl(array(
        CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPGET => true,
        CURLOPT_VERBOSE => true,
        CURLOPT_AUTOREFERER => true,
        CURLOPT_CUSTOMREQUEST => $requestType,
        CURLOPT_POSTFIELDS  => $postData,
        CURLOPT_HTTPHEADER  => array(
            "X-HTTP-Method-Override: " . $requestType,
            'Content-Type: application/json', // Only USE this when requesting JSON data
        ),

        // If HTTP authentication is required, use the below lines.
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_USERPWD  => $username. ':' . $password
    ));

    // $mixResponse contains your server response.

How do I find out if a column exists in a VB.Net DataRow

You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".

Changing selection in a select with the Chosen plugin

My answer is late, but i want to add some information that is missed in all above answers.

1) If you want to select single value in chosen select.

$('#select-id').val("22").trigger('chosen:updated');

2) If you are using multiple chosen select, then may you need to set multiple values at single time.

$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');

Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion

Integer division: How do you produce a double?

double num = 5;

That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:

Widening primitive conversions do not lose information about the overall magnitude of a numeric value.

[...]

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

5 can be expressed exactly as a double.

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

#pragma mark in Swift?

I think Extensions is a better way instead of #pragma mark.

The Code before using Extensions:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    ...

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        ...
    }
}

The code after using Extensions:

class ViewController: UIViewController {
    ...
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       ...
    }
}

ORA-12154 could not resolve the connect identifier specified

Please let me repeat what Stephen said since I missed it the first time myself. The TNS_ADMIN environment variable and ORACLE_HOME is set to C:\instantclient_11_2 and th tnsnames.ora file is in there. Found the answer on this link.

Make just one slide different size in Powerpoint

if you want to shrink one slide for instance, add shapes to hide the unwanted background margins. you can set the shape color filling as the background (gray or black). It's "ugly" but it works

Create folder in Android

If you are trying to make more than just one folder on the root of the sdcard, ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"

then instead of folder.mkdir() you would use folder.mkdirs()

I've made this mistake in the past & I took forever to figure it out.

Best way to get hostname with php

For PHP >= 5.3.0 use this:

$hostname = gethostname();

For PHP < 5.3.0 but >= 4.2.0 use this:

$hostname = php_uname('n');

For PHP < 4.2.0 use this:

$hostname = getenv('HOSTNAME'); 
if(!$hostname) $hostname = trim(`hostname`); 
if(!$hostname) $hostname = exec('echo $HOSTNAME');
if(!$hostname) $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); 

Why is document.body null in my javascript?

Or add this part

<script type="text/javascript">

    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);

    alert("Why does the span change after this alert? Not before?");

</script>

after the HTML, like:

    <html>
    <head>...</head>
    <body>...</body>
   <script type="text/javascript">
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");

    </script>

    </html>

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

Getting the index of a particular item in array

The previous answers will only work if you know the exact value you are searching for - the question states that only a partial value is known.

Array.FindIndex(authors, author => author.Contains("xyz"));

This will return the index of the first item containing "xyz".

Using Linq select list inside list

If you want to filter the models by applicationname and the remaining models by surname:

List<Model> newList = list.Where(m => m.application == "applicationname")
    .Select(m => new Model { 
        application = m.application, 
        users = m.users.Where(u => u.surname == "surname").ToList() 
    }).ToList();

As you can see, it needs to create new models and user-lists, hence it is not the most efficient way.

If you instead don't want to filter the list of users but filter the models by users with at least one user with a given username, use Any:

List<Model> newList = list
    .Where(m => m.application == "applicationname"
            &&  m.users.Any(u => u.surname == "surname"))
    .ToList();

ViewPager and fragments — what's the right way to store fragment's state?

What is that BasePagerAdapter? You should use one of the standard pager adapters -- either FragmentPagerAdapter or FragmentStatePagerAdapter, depending on whether you want Fragments that are no longer needed by the ViewPager to either be kept around (the former) or have their state saved (the latter) and re-created if needed again.

Sample code for using ViewPager can be found here

It is true that the management of fragments in a view pager across activity instances is a little complicated, because the FragmentManager in the framework takes care of saving the state and restoring any active fragments that the pager has made. All this really means is that the adapter when initializing needs to make sure it re-connects with whatever restored fragments there are. You can look at the code for FragmentPagerAdapter or FragmentStatePagerAdapter to see how this is done.

scroll up and down a div on button click using jquery

scrollBottom is not a method in jQuery.

UPDATED DEMO - http://jsfiddle.net/xEFq5/10/

Try this:

   $("#upClick").on("click" ,function(){
     scrolled=scrolled-300;
        $(".cover").animate({
          scrollTop:  scrolled
     });
   });

How to make an ImageView with rounded corners?

If you don't want to border affects the image, use this class. Unfortunately, I didn't find any approach to draw a transparent area on the canvas came to onDraw(). So, here is created a new bitmap and it's drawn on a real canvas.

The view is useful if you want to make a disappearing border. If you set borderWidth to 0, the border will disappear and the image remains with rounder corners exactly like the border was. I.e. it looks like the border is drawn exactly by the image edges.

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView


class RoundedImageViewWithBorder @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0) : AppCompatImageView(context, attrs, defStyleAttr) {

    var borderColor: Int = 0
        set(value) {
            invalidate()
            field = value
        }
    var borderWidth: Int = 0
        set(value) {
            invalidate()
            field = value
        }
    var cornerRadius: Float = 0f
        set(value) {
            invalidate()
            field = value
        }

    private var bitmapForDraw: Bitmap? = null
    private var canvasForDraw: Canvas? = null
    private val transparentPaint = Paint().apply {
        isAntiAlias = true
        color = Color.TRANSPARENT
        style = Paint.Style.STROKE
        xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
    }

    private val borderPaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
    }

    private val transparentAreaRect = RectF()
    private val borderRect = RectF()

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundedImageViewWithBorder)

        try {
            borderWidth = typedArray.getDimensionPixelSize(R.styleable.RoundedImageViewWithBorder_border_width, 0)
            borderColor = typedArray.getColor(R.styleable.RoundedImageViewWithBorder_border_color, 0)
            cornerRadius = typedArray.getDimensionPixelSize(R.styleable.RoundedImageViewWithBorder_corner_radius, 0).toFloat()

        } finally {
            typedArray.recycle()
        }
    }

    @SuppressLint("CanvasSize", "DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        if (canvas.height <=0 || canvas.width <=0) {
            return
        }

        if (canvasForDraw?.height != canvas.height || canvasForDraw?.width != canvas.width) {
            val newBitmap = Bitmap.createBitmap(canvas.width, canvas.height, Bitmap.Config.ARGB_8888)
            bitmapForDraw = newBitmap
            canvasForDraw = Canvas(newBitmap)
        }
        
        bitmapForDraw?.eraseColor(Color.TRANSPARENT)

        // Draw existing content
        super.onDraw(canvasForDraw)

        if (borderWidth > 0) {
            canvasForDraw?.let { drawWithBorder(it) }
        } else {
            canvasForDraw?.let { drawWithoutBorder(it) }
        }

        // Draw everything on real canvas
        bitmapForDraw?.let { canvas.drawBitmap(it, 0f, 0f, null) }
    }

    private fun drawWithBorder(canvas: Canvas) {
        // Draw transparent area
        transparentPaint.strokeWidth = borderWidth.toFloat() * 4
        transparentAreaRect.apply {
            left = -borderWidth.toFloat() * 1.5f
            top = -borderWidth.toFloat() * 1.5f
            right = canvas.width.toFloat() + borderWidth.toFloat() * 1.5f
            bottom = canvas.height.toFloat() + borderWidth.toFloat() * 1.5f
        }
        canvasForDraw?.drawRoundRect(transparentAreaRect, borderWidth.toFloat() * 2 + cornerRadius, borderWidth.toFloat() * 2 + cornerRadius, transparentPaint)

        // Draw border
        borderPaint.color = borderColor
        borderPaint.strokeWidth = borderWidth.toFloat()
        borderRect.apply {
            left = borderWidth.toFloat() / 2
            top = borderWidth.toFloat() / 2
            right = canvas.width.toFloat() - borderWidth.toFloat() / 2
            bottom = canvas.height.toFloat() - borderWidth.toFloat() / 2
        }
        canvas.drawRoundRect(borderRect, cornerRadius - borderWidth.toFloat() / 2, cornerRadius - borderWidth.toFloat() / 2, borderPaint)
    }

    private fun drawWithoutBorder(canvas: Canvas) {
        // Draw transparent area
        transparentPaint.strokeWidth = cornerRadius * 4
        transparentAreaRect.apply {
            left = -cornerRadius * 2
            top = -cornerRadius * 2
            right = canvas.width.toFloat() + cornerRadius * 2
            bottom = canvas.height.toFloat() + cornerRadius * 2
        }
        canvasForDraw?.drawRoundRect(transparentAreaRect, cornerRadius * 3, cornerRadius * 3, transparentPaint)
    }

}

In values:

<declare-styleable name="RoundedImageViewWithBorder">
    <attr name="corner_radius" format="dimension|string" />
    <attr name="border_width" format="dimension|reference" />
    <attr name="border_color" format="color|reference" />
</declare-styleable>

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

How do I detect a click outside an element?

I believe the best way of doing it is something like this.

$(document).on("click", function(event) {
  clickedtarget = $(event.target).closest('#menuscontainer');
  $("#menuscontainer").not(clickedtarget).hide();
});

This type of solution could easily be made to work for multiple menus and also menus that are dynamically added through javascript. Basically it just allows you to click anywhere in your document, and checks which element you clicked in, and selects it's closest "#menuscontainer". Then it hides all menuscontainers but excludes the one you clicked in.

Not sure about exactly how your menus are built, but feel free to copy my code in the JSFiddle. It's a very simple but thoroughly functional menu/modal system. All you need to do is build the html-menus and the code will do the work for you.

https://jsfiddle.net/zs6anrn7/

Java ArrayList - how can I tell if two lists are equal, order not mattering?

My solution for this. It is not so cool, but works well.

public static boolean isEqualCollection(List<?> a, List<?> b) {

    if (a == null || b == null) {
        throw new NullPointerException("The list a and b must be not null.");
    }

    if (a.size() != b.size()) {
        return false;
    }

    List<?> bCopy = new ArrayList<Object>(b);

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

        for (int j = 0; j < bCopy.size(); j++) {
            if (a.get(i).equals(bCopy.get(j))) {
                bCopy.remove(j);
                break;
            }
        }
    }

    return bCopy.isEmpty();
}

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

Moment.js will handle date formatting for you. Here is how to include it via a JavaScript tag, and then an example of how to use Moment.js to format a date.

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
moment("2013-03-10T02:00:00Z").format("YYYY-MM-DD") // "2013-03-10"

How can I loop through a List<T> and grab each item?

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}

How to create a dump with Oracle PL/SQL Developer?

Export (or datapump if you have 10g/11g) is the way to do it. Why not ask how to fix your problems with that rather than trying to find another way to do it?

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

Making Enter key on an HTML form submit instead of activating button

You can use jQuery:

$(function() {
    $("form input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('button[type=submit] .default').click();
            return false;
        } else {
            return true;
        }
    });
});

Oracle: How to filter by date and time in a where clause

Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.

Update:

You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.

How to delete or add column in SQLITE?

You can also now use DB browser for SQLite to manipulate columns

Set the value of a variable with the result of a command in a Windows batch file

The only way I've seen it done is if you do this:

for /f "delims=" %a in ('ver') do @set foobar=%a

ver is the version command for Windows and on my system it produces:

Microsoft Windows [Version 6.0.6001]

Source

How to write a file or data to an S3 object using boto3

A cleaner and concise version which I use to upload files on the fly to a given S3 bucket and sub-folder-

import boto3

BUCKET_NAME = 'sample_bucket_name'
PREFIX = 'sub-folder/'

s3 = boto3.resource('s3')

# Creating an empty file called "_DONE" and putting it in the S3 bucket
s3.Object(BUCKET_NAME, PREFIX + '_DONE').put(Body="")

Note: You should ALWAYS put your AWS credentials (aws_access_key_id and aws_secret_access_key) in a separate file, for example- ~/.aws/credentials

sum two columns in R

You can do this :

    df <- data.frame("a" = c(1,2,3,4), "b" = c(4,3,2,1), "x_ind" = c(1,0,1,1), "y_ind" = c(0,0,1,1), "z_ind" = c(0,1,1,1) )
df %>% mutate( bi  = ifelse((df$x_ind + df$y_ind +df$z_ind)== 3, 1,0 ))

Polymorphism vs Overriding vs Overloading

The term overloading refers to having multiple versions of something with the same name, usually methods with different parameter lists

public int DoSomething(int objectId) { ... }
public int DoSomething(string objectName) { ... }

So these functions might do the same thing but you have the option to call it with an ID, or a name. Has nothing to do with inheritance, abstract classes, etc.

Overriding usually refers to polymorphism, as you described in your question

Python: URLError: <urlopen error [Errno 10060]

This is because of the proxy settings. I also had the same problem, under which I could not use any of the modules which were fetching data from the internet. There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done. try to run the programme again, it must work it worked for me at least

How to get param from url in angular 4?

The accepted answer uses the observable to retrieve the parameter which can be useful in the parameter will change throughtout the component lifecycle.

If the parameter will not change, one can consider using the params object on the snapshot of the router url.

snapshot.params returns all the parameters in the URL in an object.

constructor(private route: ActivateRoute){}

ngOnInit() {
   const allParams = this.route.snapshot.params // allParams is an object
   const param1 = allParams.param1 // retrieve the parameter "param1"
}

Find if a String is present in an array

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

Add new line in text file with Windows batch file

DISCLAIMER: The below solution does not preserve trailing tabs.


If you know the exact number of lines in the text file, try the following method:

@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /P L=
  IF %%i==%insertbefore% ECHO(
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%

The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.

After finishing, the original file is deleted and the temporary one gets assigned the original name.


UPDATE

If the number of lines is unknown beforehand, you can use the following method to obtain it:

FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C

(This line simply replaces the SET totallines=200 line in the above script.)

The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.

Eclipse Problems View not showing Errors anymore

If you have reached here that means all the other solutions did not work for you. One reason could be your source folder is not a java project.

Solution would be to run below command on the source folder

mvn eclipse:eclipse

This worked for me.

If this also doesn't work then try removing .classpath and .project file and run the above command again

phpexcel to download

$excel = new PHPExcel();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');

// Do your stuff here

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');

// This line will force the file to download
$writer->save('php://output');

How to specify the bottom border of a <tr>?

tr td 
{
    border-bottom: 2px solid silver;
}

or if you want the border inside the TR tag, you can do this:

tr td {
    box-shadow: inset 0px -2px 0px silver;
}

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to use bootstrap-theme.css with bootstrap 3?

Upon downloading Bootstrap 3.x, you'll get bootstrap.css and bootstrap-theme.css (not to mention the minified versions of these files that are also present).

bootstrap.css

bootstrap.css is completely styled and ready to use, if such is your desire. It is perhaps a bit plain but it is ready and it is there.

You do not need to use bootstrap-theme.css if you don't want to and things will be just fine.

bootstrap-theme.css

bootstrap-theme.css is just what the name of the file is trying to suggest: it is a theme for bootstrap that is creatively considered 'THE bootstrap theme'. The name of the file confuses things just a bit since the base bootstrap.css already has styling applied and I, for one, would consider those styles to be the default. But that conclusion is apparently incorrect in light of things said in the Bootstrap documentation's examples section in regard to this bootstrap-theme.css file:

"Load the optional Bootstrap theme for a visually enhanced experience."

The above quote is found here http://getbootstrap.com/getting-started/#examples on a thumbnail that links to this example page http://getbootstrap.com/examples/theme/. The idea is that bootstrap-theme.css is THE bootstrap theme AND it's optional.

Themes at BootSwatch.com

About the themes at BootSwatch.com: These themes are not implemented like bootstrap-theme.css. The BootSwatch themes are modified versions of the original bootstrap.css. So, you should definitely NOT use a theme from BootSwatch AND the bootstrap-theme.css file at the same time.

Custom Theme

About Your Own Custom Theme: You might choose to modify bootstrap-theme.css when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.

Java: convert seconds to minutes, hours and days

An example using built in TimeUnit.

long uptime = System.currentTimeMillis();

long days = TimeUnit.MILLISECONDS
    .toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);

long hours = TimeUnit.MILLISECONDS
    .toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);

long minutes = TimeUnit.MILLISECONDS
    .toMinutes(uptime);
uptime -= TimeUnit.MINUTES.toMillis(minutes);

long seconds = TimeUnit.MILLISECONDS
    .toSeconds(uptime);

Get escaped URL parameter

Slight modification to the answer by @pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.

Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.

Fix:

var urlParamVal = function (name) {
    var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
    return result ? decodeURIComponent(result[2]) : "";
};

Change limit for "Mysql Row size too large"

The other answers address the question asked. I will address the underlying cause: poor schema design.

Do not splay an array across columns. Here you have 3*10 columns that should be turned into 10 rows of 3 columns in a new table (plus id, etc)

Your Main table would have only

id  int(11) No       
name    text    No       
date    date    No       
time    time    No       
schedule    int(11) No       
category    int(11) No       
status  int(11) No       
admin_id    int(11) No 

Your extra table (Top) would have

id  int(11) No          -- for joining to Main
seq TINYINT UNSIGNED    -- containing 1..10
img   varchar(255)    No       
title varchar(255)    No       
desc  text    No    
PRIMARY KEY(id, seq)    -- so you can easily find the 10 top_titles

There would be 10 (or fewer? or more?) rows in Top for each id.

This eliminates your original problem, and cleans up the schema. (This is not "normalization", as debated in some of the Comments.)

Do not switch to MyISAM; it is going away.
Don't worry about ROW_FORMAT.

You will need to change your code to do the JOIN and to handle multiple rows instead of multiple columns.

Get Context in a Service

Since Service is a Context, the variable context must be this:

DataBaseManager dbm = Utils.getDataManager(this);   

BeanFactory vs ApplicationContext

For the most part, ApplicationContext is preferred unless you need to save resources, like on a mobile application.

I'm not sure about depending on XML format, but I'm pretty sure the most common implementations of ApplicationContext are the XML ones such as ClassPathXmlApplicationContext, XmlWebApplicationContext, and FileSystemXmlApplicationContext. Those are the only three I've ever used.

If your developing a web app, it's safe to say you'll need to use XmlWebApplicationContext.

If you want your beans to be aware of Spring, you can have them implement BeanFactoryAware and/or ApplicationContextAware for that, so you can use either BeanFactory or ApplicationContext and choose which interface to implement.

A simple scenario using wait() and notify() in java

Even though you asked for wait() and notify() specifically, I feel that this quote is still important enough:

Josh Bloch, Effective Java 2nd Edition, Item 69: Prefer concurrency utilities to wait and notify (emphasis his):

Given the difficulty of using wait and notify correctly, you should use the higher-level concurrency utilities instead [...] using wait and notify directly is like programming in "concurrency assembly language", as compared to the higher-level language provided by java.util.concurrent. There is seldom, if ever, reason to use wait and notify in new code.

Leap year calculation

Will it not be much better if we make one step further. Assuming every 3200 year as no leap year, the length of the year will come

364.999696 + 1/3200 = 364.999696 + .0003125 = 365.0000085

and after this the adjustment will be required after around 120000 years.

How do I create a constant in Python?

You can use Tuple for constant variable :

• A tuple is a collection which is ordered and unchangeable

my_tuple = (1, "Hello", 3.4)
print(my_tuple[0])

Accessing Google Account Id /username via Android

String name = android.os.Build.USER;

if (!TextUtils.isEmpty(name)) {
    nameEdit.setText(name);
}

How to format a JavaScript date

If you are using jQuery UI in your code, there is an inbuilt function called formatDate(). I am using it this way to format today's date:

var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);

You can see many other examples of formatting date in the jQuery UI documentation.

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

If the radiobutton-checked event occurs before the content of the window is loaded fully, i.e. the ellipse is loaded fully, such an exception will be thrown. So check if the UI of the window is loaded (probably by Window_ContentRendered event, etc.).

keypress, ctrl+c (or some combo like that)

Simple way to do it in jQuery :

/* The elements we'll bind the shortcut keys to. */
var elements = "body, input, select, checkbox, textarea";

/* Bind the key short-cut 'Ctrl+S' to the save function. */
$(elements).bind ("keydown", "ctrl+space", function (e) {
    // Prevent the default operation.
    e.preventDefault ();
    // Stop processing if we're already doing something.
    console.log ("That's right , you pressed correct shortcut!");
});

Get the client's IP address in socket.io

In 1.3.5 :

var clientIP = socket.handshake.headers.host;

How to load a controller from another controller in codeigniter?

There are many ways by which you can access one controller into another.

class Test1 extends CI_controller
{
    function testfunction(){
        return 1;
    }
}

Then create another class, and include first Class in it, and extend it with your class.

include 'Test1.php';

class Test extends Test1
{
    function myfunction(){
        $this->test();
        echo 1;
    }
}

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

Pass in an array of Deferreds to $.when()

If you're transpiling and have access to ES6, you can use spread syntax which specifically applies each iterable item of an object as a discrete argument, just the way $.when() needs it.

$.when(...deferreds).done(() => {
    // do stuff
});

MDN Link - Spread Syntax

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

I think the answers are below

List<string> aa = (from char c in source
                    select c.ToString() ).ToList();

List<string> aa2 = (from char c1 in source
                    from char c2 in source
                    select string.Concat(c1, ".", c2)).ToList();

How to append to the end of an empty list?

use my_list.append(...) and do not use and other list to append as list are mutable.

Setting background color for a JFrame

You can use this code block for JFrame background color.

    JFrame frame = new JFrame("Frame BG color");
    frame.setLayout(null);
    
    frame.setSize(1000, 650);
    frame.getContentPane().setBackground(new Color(5, 65, 90));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);

Java 6 Unsupported major.minor version 51.0

I face the same problem and solved by adding the JAVA_HOME variable with updated version of java in my Ubuntu Machine(16.04). if you are using "Apache Maven 3.3.9" You need to upgrade your JAVA_HOME with java7 or more

Step to Do this

1-sudo vim /etc/environment

2-JAVA_HOME=JAVA Installation Directory (MyCase-/opt/dev/jdk1.7.0_45/)

3-Run echo $JAVA_HOME will give the JAVA_HOME set value

4-Now mvn -version will give the desired output

Apache Maven 3.3.9

Maven home: /usr/share/maven

Java version: 1.7.0_45, vendor: Oracle Corporation

Java home: /opt/dev/jdk1.7.0_45/jre

Default locale: en_US, platform encoding: UTF-8

OS name: "linux", version: "4.4.0-36-generic", arch: "amd64", family: "unix"

Using GitLab token to clone without authentication

The gitlab has a lot of tokens:

  • Private token
  • Personal Access Token
  • CI/CD running token

I tested only the Personal Access Token using GitLab Community Edition 10.1.2, the example:

git clone https://gitlab-ci-token:${Personal Access Tokens}@gitlab.com/username/myrepo.git


git clone https://oauth2:${Personal Access Tokens}@gitlab.com/username/myrepo.git

or using username and password:

git clone https://${username}:${password}@gitlab.com/username/myrepo.git

or by input your password:

git clone https://${username}@gitlab.com/username/myrepo.git

But the private token seems can not work.

Failed to install *.apk on device 'emulator-5554': EOF

Solution:

  1. Start emulator (separately) and wait until it is fully loaded.
  2. Open keylock.
  3. Navigate to Eclipse and run your app.

Cause of the problem: Android emulator hasn't loaded all its libraries which handle the installing of a new application and due to that you run into java.io.IOException: EOF

That was causing me the problem.

The remote server returned an error: (407) Proxy Authentication Required

Probably the machine or web.config in prod has the settings in the configuration; you probably won't need the proxy tag.

<system.net>
    <defaultProxy useDefaultCredentials="true" >
        <proxy usesystemdefault="False"
               proxyaddress="http://<ProxyLocation>:<port>"
               bypassonlocal="True"
               autoDetect="False" />
    </defaultProxy>
</system.net>

The name 'ConfigurationManager' does not exist in the current context

Adding the System.Configuration as reference to all the projects will solve this.

  1. Go to Project -> Add Reference

  2. In the box that appears, click the All assemblies list tab in the left hand list.

  3. In the central list, scroll to System.Configuration and make sure the box is checked.

  4. Click ok to apply, and you'll now be able to access the ConfigurationManager class.

How can I call controller/view helper methods from the console in Ruby on Rails?

If the method is the POST method then:

app.post 'controller/action?parameter1=value1&parameter2=value2'

(Here parameters will be as per your applicability.)

Else if it is the GET method then:

app.get 'controller/action'

How to convert from Hex to ASCII in JavaScript?

I found a useful function present in web3 library.

var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)

Force page scroll position to top at page refresh in HTML

This is one of the best way to do so:

_x000D_
_x000D_
<script>
$(window).on('beforeunload', function() {
  $('body').hide();
  $(window).scrollTop(0);
});
</script>
_x000D_
_x000D_
_x000D_

How to select all instances of a variable and edit variable name in Sublime

As user1767754 said, the key here is to not make any selection initially.

Just place the cursor inside the variable name, don't double click to select it. For single character variables, place the cursor at the front or end of the variable to not make any selection initially.

Now keep hitting Cmd+D for next variable selection or Ctrl+Cmd+G for selecting all variables at once. It will magically select only the variables.

How to check if keras tensorflow backend is GPU or CPU version?

Also you can check using Keras backend function:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

I test this on Keras (2.1.1)

Importing CSV with line breaks in Excel 2007

I have finally found the problem!

It turns out that we were writing the file using Unicode encoding, rather than ASCII or UTF-8. Changing the encoding on the FileStream seems to solve the problem.

Thanks everyone for all your suggestions!

What's the PowerShell syntax for multiple values in a switch statement?

Supports entering y|ye|yes and case insensitive.

switch -regex ($someString.ToLower()) {
        "^y(es?)?$" {
            "You entered Yes." 
        }
        default { "You entered No." }
}

C++ equivalent of StringBuffer/StringBuilder?

NOTE this answer has received some attention recently. I am not advocating this as a solution (it is a solution I have seen in the past, before the STL). It is an interesting approach and should only be applied over std::string or std::stringstream if after profiling your code you discover this makes an improvement.

I normally use either std::string or std::stringstream. I have never had any problems with these. I would normally reserve some room first if I know the rough size of the string in advance.

I have seen other people make their own optimized string builder in the distant past.

class StringBuilder {
private:
    std::string main;
    std::string scratch;

    const std::string::size_type ScratchSize = 1024;  // or some other arbitrary number

public:
    StringBuilder & append(const std::string & str) {
        scratch.append(str);
        if (scratch.size() > ScratchSize) {
            main.append(scratch);
            scratch.resize(0);
        }
        return *this;
    }

    const std::string & str() {
        if (scratch.size() > 0) {
            main.append(scratch);
            scratch.resize(0);
        }
        return main;
    }
};

It uses two strings one for the majority of the string and the other as a scratch area for concatenating short strings. It optimise's appends by batching the short append operations in one small string then appending this to the main string, thus reducing the number of reallocations required on the main string as it gets larger.

I have not required this trick with std::string or std::stringstream. I think it was used with a third party string library before std::string, it was that long ago. If you adopt a strategy like this profile your application first.

Find something in column A then show the value of B for that row in Excel 2010

Assuming

source data range is A1:B100.
query cell is D1 (here you will input Police or Fire).
result cell is E1

Formula in E1 = VLOOKUP(D1, A1:B100, 2, FALSE)

How to display databases in Oracle 11g using SQL*Plus

You can think of a MySQL "database" as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS view to see the list of schemas:

SELECT * FROM DBA_USERS;

How to redirect a url in NGINX

This is the top hit on Google for "nginx redirect". If you got here just wanting to redirect a single location:

location = /content/unique-page-name {
  return 301 /new-name/unique-page-name;
}

text-overflow: ellipsis not working

Without Fixed Width

For those of us that do not want to use fixed-width, it also works using display: inline-grid. So along with required properties, you just add display

span {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-grid;
}

How do I include inline JavaScript in Haml?

:javascript
    $(document).ready( function() {
      $('body').addClass( 'test' );
    } );

Docs: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter

I cannot access tomcat admin console?

For me, it just was that service console restart didn't work after tomcat ran into an error. Only stop/start brought it back.

Convert object of any type to JObject with Json.NET

If you have an object and wish to become JObject you can use:

JObject o = (JObject)JToken.FromObject(miObjetoEspecial);

like this :

Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};

JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}

Checking network connection

If we can connect to some Internet server, then we indeed have connectivity. However, for the fastest and most reliable approach, all solutions should comply with the following requirements, at the very least:

  • Avoid DNS resolution (we will need an IP that is well-known and guaranteed to be available for most of the time)
  • Avoid application layer connections (connecting to an HTTP/FTP/IMAP service)
  • Avoid calls to external utilities from Python or other language of choice (we need to come up with a language-agnostic solution that doesn't rely on third-party solutions)

To comply with these, one approach could be to, check if one of the Google's public DNS servers is reachable. The IPv4 addresses for these servers are 8.8.8.8 and 8.8.4.4. We can try connecting to any of them.

A quick Nmap of the host 8.8.8.8 gave below result:

$ sudo nmap 8.8.8.8

Starting Nmap 6.40 ( http://nmap.org ) at 2015-10-14 10:17 IST
Nmap scan report for google-public-dns-a.google.com (8.8.8.8)
Host is up (0.0048s latency).
Not shown: 999 filtered ports
PORT   STATE SERVICE
53/tcp open  domain

Nmap done: 1 IP address (1 host up) scanned in 23.81 seconds

As we can see, 53/tcp is open and non-filtered. If you are a non-root user, remember to use sudo or the -Pn argument for Nmap to send crafted probe packets and determine if a host is up.

Before we try with Python, let's test connectivity using an external tool, Netcat:

$ nc 8.8.8.8 53 -zv
Connection to 8.8.8.8 53 port [tcp/domain] succeeded!

Netcat confirms that we can reach 8.8.8.8 over 53/tcp. Now we can set up a socket connection to 8.8.8.8:53/tcp in Python to check connection:

import socket

def internet(host="8.8.8.8", port=53, timeout=3):
    """
    Host: 8.8.8.8 (google-public-dns-a.google.com)
    OpenPort: 53/tcp
    Service: domain (DNS/TCP)
    """
    try:
        socket.setdefaulttimeout(timeout)
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
        return True
    except socket.error as ex:
        print(ex)
        return False

internet()

Another approach could be to send a manually crafted DNS probe to one of these servers and wait for a response. But, I assume, it might prove slower in comparison due to packet drops, DNS resolution failure, etc. Please comment if you think otherwise.

UPDATE #1: Thanks to @theamk's comment, timeout is now an argument and initialized to 3s by default.

UPDATE #2: I did quick tests to identify the fastest and most generic implementation of all valid answers to this question. Here's the summary:

$ ls *.py | sort -n | xargs -I % sh -c 'echo %; ./timeit.sh %; echo'
defos.py
True
00:00:00:00.487

iamaziz.py
True
00:00:00:00.335

ivelin.py
True
00:00:00:00.105

jaredb.py
True
00:00:00:00.533

kevinc.py
True
00:00:00:00.295

unutbu.py
True
00:00:00:00.546

7h3rAm.py
True
00:00:00:00.032

And once more:

$ ls *.py | sort -n | xargs -I % sh -c 'echo %; ./timeit.sh %; echo'
defos.py
True
00:00:00:00.450

iamaziz.py
True
00:00:00:00.358

ivelin.py
True
00:00:00:00.099

jaredb.py
True
00:00:00:00.585

kevinc.py
True
00:00:00:00.492

unutbu.py
True
00:00:00:00.485

7h3rAm.py
True
00:00:00:00.035

True in the above output signifies that all these implementations from respective authors correctly identify connectivity to the Internet. Time is shown with milliseconds resolution.

UPDATE #3: Tested again after the exception handling change:

defos.py
True
00:00:00:00.410

iamaziz.py
True
00:00:00:00.240

ivelin.py
True
00:00:00:00.109

jaredb.py
True
00:00:00:00.520

kevinc.py
True
00:00:00:00.317

unutbu.py
True
00:00:00:00.436

7h3rAm.py
True
00:00:00:00.030

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

For Java 8 the following method works:

  1. Form an URI from file URI string
  2. Create a file from the URI (not directly from URI string, absolute URI string are not paths)

Refer, below code snippet

    String fileURiString="file:///D:/etc/MySQL.txt";
    URI fileURI=new URI(fileURiString);
    File file=new File(fileURI);//File file=new File(fileURiString) - will generate exception

    FileInputStream fis=new FileInputStream(file);
    fis.close();

How do I call Objective-C code from Swift?

Apple has provided official guide in this doc: how-to-call-objective-c-code-from-swift

Here is the relevant part:

To import a set of Objective-C files into Swift code within the same app target, you rely on an Objective-C bridging header file to expose those files to Swift. Xcode offers to create this header when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.

If you accept, Xcode creates the bridging header file along with the file you were creating, and names it by using your product module name followed by "-Bridging-Header.h". Alternatively, you can create a bridging header yourself by choosing File > New > File > [operating system] > Source > Header File

Edit the bridging header to expose your Objective-C code to your Swift code:

  1. In your Objective-C bridging header, import every Objective-C header you want to expose to Swift.
  2. In Build Settings, in Swift Compiler - Code Generation, make sure the Objective-C Bridging Header build setting has a path to the bridging header file. The path should be relative to your project, similar to the way your Info.plist path is specified in Build Settings. In most cases, you won't need to modify this setting.

Any public Objective-C headers listed in the bridging header are visible to Swift.

How to disable Hyper-V in command line?

Open command prompt as admin and write :

bcdedit /set hypervisorlaunchtype off

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

How do shift operators work in Java?

Signed left shift Logically Simple if 1<<11 it will tends to 2048 and 2<<11 will give 4096

In java programming int a = 2 << 11;

// it will result in 4096

2<<11 = 2*(2^11) = 4096

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

Tower of Hanoi: Recursive Algorithm

Suppose we want to move a disc from A to C through B then:

  1. move a smaller disc to B.
  2. move another disc to C.
  3. move B to C.
  4. move from A to B.
  5. move all from C to A.

If you repeat all the above steps, the disc will transfer.

Convert pyQt UI to python

Quickest way to convert .ui to .py is from terminal:

pyuic4 -x input.ui -o output.py

Make sure you have pyqt4-dev-tools installed.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

Yes, it does. From the AdMob page:

The Mobile Ads SDK for iOS utilizes Apple's advertising identifier (IDFA). The SDK uses IDFA under the guidelines laid out in the iOS developer program license agreement. You must ensure you are in compliance with the iOS developer program license agreement policies governing the use of this identifier.

Convert List<DerivedClass> to List<BaseClass>

I personally like to create libs with extensions to the classes

public static List<TTo> Cast<TFrom, TTo>(List<TFrom> fromlist)
  where TFrom : class 
  where TTo : class
{
  return fromlist.ConvertAll(x => x as TTo);
}

How unique is UUID?

For UUID4 I make it that there are approximately as many IDs as there are grains of sand in a cube-shaped box with sides 360,000km long. That's a box with sides ~2 1/2 times longer than Jupiter's diameter.

Working so someone can tell me if I've messed up units:

  • volume of grain of sand 0.00947mm^3 (Guardian)
  • UUID4 has 122 random bits -> 5.3e36 possible values (wikipedia)
  • volume of that many grains of sand = 5.0191e34 mm^3 or 5.0191e+25m^3
  • side length of cubic box with that volume = 3.69E8m or 369,000km
  • diameter of Jupiter: 139,820km (google)

jQuery UI Tabs - How to Get Currently Selected Tab Index

In case anybody has tried to access tabs from within an iframe, you may notice it's not possible. The div of the tab never gets marked as selected, just as hidden or not hidden. The link itself is the only piece marked as selected.

<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-focus"><a href="#tabs-4">Tab 5</a></li>

The following will get you the href value of the link which should be the same as the id for your tab container:

jQuery('.ui-tabs-selected a',window.parent.document).attr('href')

This should also work in place of: $tabs.tabs('option', 'selected');

It's better in the sense that instead of just getting the index of the tab, it gives you the actual id of the tab.

How to specify the current directory as path in VBA?

If the path you want is the one to the workbook running the macro, and that workbook has been saved, then

ThisWorkbook.Path

is what you would use.

Using std::max_element on a vector<double>

As others have said, std::max_element() and std::min_element() return iterators, which need to be dereferenced to obtain the value.

The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.

For example (using C++11 for brevity):

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};

    auto biggest = std::max_element(std::begin(v), std::end(v));
    std::cout << "Max element is " << *biggest
        << " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v));
    std::cout << "min element is " << *smallest
        << " at position " << std::distance(std::begin(v), smallest) << std::endl;
}

This yields:

Max element is 5 at position 4
min element is 1 at position 0

Note:

Using std::minmax_element() as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9 since...

If several elements are equivalent to the largest element, the iterator to the last such element is returned.

How many socket connections possible?

This depends not only on the operating system in question, but also on configuration, potentially real-time configuration.

For Linux:

cat /proc/sys/fs/file-max

will show the current maximum number of file descriptors total allowed to be opened simultaneously. Check out http://www.cs.uwaterloo.ca/~brecht/servers/openfiles.html

Hive External Table Skip First Row

skip.header.line.count will skip the header line.

However, if you have some external tool accessing accessing the table, it will still see that actual data without skipping those lines

How to convert a string with Unicode encoding to a string of letters

StringEscapeUtils from org.apache.commons.lang3 library is deprecated as of 3.6.

So you can use their new commons-text library instead:

compile 'org.apache.commons:commons-text:1.9'

OR

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-text</artifactId>
   <version>1.9</version>
</dependency>

Example code:

org.apache.commons.text.StringEscapeUtils.unescapeJava(escapedString);

How to fix a locale setting warning from Perl

I have this issue whenever I run a Perl script, such as enum4linux, on the latest Kali Linux version.

kali@kali:~$ lsb_release -a
No LSB modules are available.
Distributor ID:    Kali
Description:    Kali GNU/Linux Rolling
Release:    2020.3
Codename:    kali-rolling
kali@kali:~$

E.g.,

kali@kali:~$ enum4linux
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
    LANGUAGE = (unset),
    LC_ALL = (unset),
    LC_ADDRESS = "ms_MY.UTF-8",
    LC_NAME = "ms_MY.UTF-8",
    LC_MONETARY = "ms_MY.UTF-8",
    LC_PAPER = "ms_MY.UTF-8",
    LC_IDENTIFICATION = "ms_MY.UTF-8",
    LC_TELEPHONE = "ms_MY.UTF-8",
    LC_MEASUREMENT = "ms_MY.UTF-8",
    LC_TIME = "ms_MY.UTF-8",
    LC_NUMERIC = "ms_MY.UTF-8",
    LANG = "en_US.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to a fallback locale ("en_US.UTF-8").
enum4linux v0.8.9 (http://labs.portcullis.co.uk/application/enum4linux/)
Copyright (C) 2011 Mark Lowe ([email protected])

Look at the warning message given.

perl: warning: Falling back to a fallback locale ("en_US.UTF-8").

Also, notice that LC_ALL = (unset)

The solution is simple. All you have to do is to set it.

export LC_ALL=en_US.UTF-8

E.g.,

kali@kali:~$ export LC_ALL=en_US.UTF-8
kali@kali:~$

And problem solved

kali@kali:~$ enum4linux
enum4linux v0.8.9 (http://labs.portcullis.co.uk/application/enum4linux/)
Copyright (C) 2011 Mark Lowe ([email protected])

For a permanent solution, you might want to add it to the .bashrc file.

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

How do I get into a Docker container's shell?

For docker-compose up (Docker4Drupal)

docker-compose exec php bash

I use Docker for Drupal on a Linux laptop. After running the container I use 'docker-compose exec php bash' to connect with the container so I can run drush commandos. It works fine for me.

Java split string to array

This behavior is explicitly documented in String.split(String regex) (emphasis mine):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):

String[] array = values.split("\\|", -1);

android pick images from gallery

Just to offer an update to the answer for people with API min 19, per the docs:

On Android 4.4 (API level 19) and higher, you have the additional option of using the ACTION_OPEN_DOCUMENT intent, which displays a system-controlled picker UI controlled that allows the user to browse all files that other apps have made available. From this single UI, the user can pick a file from any of the supported apps.

On Android 5.0 (API level 21) and higher, you can also use the ACTION_OPEN_DOCUMENT_TREE intent, which allows the user to choose a directory for a client app to access.

Open files using storage access framework - Android Docs

     val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
     intent.type = "image/*"
     startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)

How to get current foreground activity context in android?

Personally I did as "Cheok Yan Cheng" said, but I used a "List" to have a "Backstack" of all my activities.

If you want to check Which is the Current Activity you just need to get the last activity class in the list.

Create an application which extends "Application" and do this:

public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks,
EndSyncReceiver.IEndSyncCallback {

private List<Class> mActivitiesBackStack;
private EndSyncReceiver mReceiver;
    private Merlin mMerlin;
    private boolean isMerlinBound;
    private boolean isReceiverRegistered;

@Override
    public void onCreate() {
        super.onCreate();
        [....]
RealmHelper.initInstance();
        initMyMerlin();
        bindMerlin();
        initEndSyncReceiver();
        mActivitiesBackStack = new ArrayList<>();
    }

/* START Override ActivityLifecycleCallbacks Methods */
    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
        mActivitiesBackStack.add(activity.getClass());
    }

    @Override
    public void onActivityStarted(Activity activity) {
        if(!isMerlinBound){
            bindMerlin();
        }
        if(!isReceiverRegistered){
            registerEndSyncReceiver();
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        if(!AppUtils.isAppOnForeground(this)){
            if(isMerlinBound) {
                unbindMerlin();
            }
            if(isReceiverRegistered){
                unregisterReceiver(mReceiver);
            }
            if(RealmHelper.getInstance() != null){
                RealmHelper.getInstance().close();
                RealmHelper.getInstance().logRealmInstanceCount("AppInBackground");
                RealmHelper.setMyInstance(null);
            }
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if(mActivitiesBackStack.contains(activity.getClass())){
            mActivitiesBackStack.remove(activity.getClass());
        }
    }
    /* END Override ActivityLifecycleCallbacks Methods */

/* START Override IEndSyncCallback Methods */
    @Override
    public void onEndSync(Intent intent) {
        Constants.SyncType syncType = null;
        if(intent.hasExtra(Constants.INTENT_DATA_SYNC_TYPE)){
            syncType = (Constants.SyncType) intent.getSerializableExtra(Constants.INTENT_DATA_SYNC_TYPE);
        }
        if(syncType != null){
            checkSyncType(syncType);
        }
    }
    /* END IEndSyncCallback Methods */

private void checkSyncType(Constants.SyncType){
    [...]
    if( mActivitiesBackStack.contains(ActivityClass.class) ){
         doOperation()     }
}

}

In my case I used "Application.ActivityLifecycleCallbacks" to:

  • Bind/Unbind Merlin Instance (used to get event when the app lose or get connection, for example when you close mobile data or when you open it). It is useful after the "OnConnectivityChanged" intent action was disabled. For more info about MERLIN see: MERLIN INFO LINK

  • Close my last Realm Instance when the application is closed; I will init it inside a BaseActivity wich is extended from all others activities and which has a private RealmHelper Instance. For more info about REALM see: REALM INFO LINK For instance I have a static "RealmHelper" instance inside my "RealmHelper" class which is instantiated inside my application "onCreate". I have a synchronization service in which I create I new "RealmHelper" because Realm is "Thread-Linked" and a Realm Instance can't work inside a different Thread. So in order to follow Realm Documentation "You Need To Close All Opened Realm Instances to avoid System Resources Leaks", to accomplish this thing I used the "Application.ActivityLifecycleCallbacks" as you can see up.

  • Finally I have a receiver wich is triggered when I finish to synchronize my application, then when the sync end it will call the "IEndSyncCallback" "onEndSync" method in which I look if I have a specific Activity Class inside my ActivitiesBackStack List because I need to update the data on the view if the sync updated them and I could need to do others operations after the app sync.

That's all, hope this is helpful. See u :)

No shadow by default on Toolbar?

actionbar_background.xml

    <item>
        <shape>
            <solid android:color="@color/black" />
            <corners android:radius="2dp" />
            <gradient
                android:startColor="@color/black"
                android:centerColor="@color/black"
                android:endColor="@color/white"
                android:angle="270" />
        </shape>
    </item>

    <item android:bottom="3dp" >
        <shape>

            <solid android:color="#ffffff" />
            <corners android:radius="1dp" />
        </shape>
    </item>
</layer-list>

add to actionbar_style background

<style name="Theme.ActionBar" parent="style/Widget.AppCompat.Light.ActionBar.Solid">
    <item name="background">@drawable/actionbar_background</item>
    <item name="android:elevation">0dp</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:layout_marginBottom">5dp</item>

name="displayOptions">useLogo|showHome|showTitle|showCustom

add to Basetheme

<style name="BaseTheme" parent="Theme.AppCompat.Light">
   <item name="android:homeAsUpIndicator">@drawable/home_back</item>
   <item name="actionBarStyle">@style/Theme.ActionBar</item>
</style>

to remove first and last element in array

Creates a 1 level deep copy.

fruits.slice(1, -1)

Let go of the original array.

Thanks to @Tim for pointing out the spelling errata.

Pass command parameter to method in ViewModel in WPF?

Just using Data Binding syntax. For example,

<Button x:Name="btn" 
         Content="Click" 
         Command="{Binding ClickCmd}" 
         CommandParameter="{Binding ElementName=btn,Path=Content}" /> 

Not only can we use Data Binding to get some data from View Models, but also pass data back to View Models. In CommandParameter, must use ElementName to declare binding source explicitly.

Array definition in XML?

The second way isn't valid XML; did you mean <numbers>[3,2,1]</numbers>?

If so, then the first one is preferred because all you need to get the array elements is some XML manipulation. On the second one you first need to get the value of the <numbers> element via XML manipulation, then somehow parse the [3,2,1] text using something else.

Or if you really want some compact format, you can consider using JSON (which "natively" supports arrays). But that depends on your application requirements.

Dynamically add data to a javascript map

Javascript now has a specific built in object called Map, you can call as follows :

   var myMap = new Map()

You can update it with .set :

   myMap.set("key0","value")

This has the advantage of methods you can use to handle look ups, like the boolean .has

  myMap.has("key1"); // evaluates to false 

You can use this before calling .get on your Map object to handle looking up non-existent keys

Python - List of unique dictionaries

Expanding on John La Rooy (Python - List of unique dictionaries) answer, making it a bit more flexible:

def dedup_dict_list(list_of_dicts: list, columns: list) -> list:
    return list({''.join(row[column] for column in columns): row
                for row in list_of_dicts}.values())

Calling Function:

sorted_list_of_dicts = dedup_dict_list(
    unsorted_list_of_dicts, ['id', 'name'])

iPad/iPhone hover problem causes the user to double click a link

Just an improvement to avoid redirection when you slide your finger on a link by mistake.

// tablet "one touch (click)" X "hover" > link redirection
$('a').on('touchmove touchend', function(e) {

    // if touchmove>touchend, set the data() for this element to true. then leave touchmove & let touchend fail(data=true) redirection
    if (e.type == 'touchmove') {
        $.data(this, "touchmove_cancel_redirection", true );
        return;
    }

    // if it's a simple touchend, data() for this element doesn't exist.
    if (e.type == 'touchend' && !$.data(this, "touchmove_cancel_redirection")) {
        var el = $(this);
        var link = el.attr('href');
        window.location = link;
    }

    // if touchmove>touchend, to be redirected on a future simple touchend for this element
    $.data(this, "touchmove_cancel_redirection", false );
});

How to include scripts located inside the node_modules folder?

I want to update this question with an easier solution. Create a symbolic link to node_modules.

The easiest way to grant public access to node_modules is to create a symbolic link pointing to your node_modules from within your public directory. The symlink will make it as if the files exist wherever the link is created.

For example, if the node server has code for serving static files

app.use(serveStatic(path.join(__dirname, 'dist')));

and __dirname refers to /path/to/app so that your static files are served from /path/to/app/dist

and node_modules is at /path/to/app/node_modules, then create a symlink like this on mac/linux:

ln -s /path/to/app/node_modules /path/to/app/dist/node_modules

or like this on windows:

mklink /path/to/app/node_modules /path/to/app/dist/node_modules

Now a get request for:

node_modules/some/path 

will receive a response with the file at

/path/to/app/dist/node_modules/some/path 

which is really the file at

/path/to/app/node_modules/some/path

If your directory at /path/to/app/dist is not a safe location, perhaps because of interference from a build process with gulp or grunt, then you could add a separate directory for the link and add a new serveStatic call such as:

ln -s /path/to/app/node_modules /path/to/app/newDirectoryName/node_modules

and in node add:

app.use(serveStatic(path.join(__dirname, 'newDirectoryName')));

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

Thanks for the advice. As there is no equivalent in SQL server. I simply created a 2nd field which converted the TimeSpan to ticks and stored that in the DB. I then prevented storing the TimeSpan

public Int64 ValidityPeriodTicks { get; set; }

[NotMapped]
public TimeSpan ValidityPeriod
{
    get { return TimeSpan.FromTicks(ValidityPeriodTicks); }
    set { ValidityPeriodTicks = value.Ticks; }
}

Convert a JSON String to a HashMap

Hope this will work, try this:

import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);

str, your JSON String

As Simple as this, if you want emailid,

String emailIds = response.get("email id").toString();

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)


To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]

or

map(lambda axi: axi.set_axis_off(), ax.ravel())

Binding an enum to a WinForms combo box, and then setting it

public Form1()
{
    InitializeComponent();
    comboBox.DataSource = EnumWithName<SearchType>.ParseEnum();
    comboBox.DisplayMember = "Name";
}

public class EnumWithName<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public static EnumWithName<T>[] ParseEnum()
    {
        List<EnumWithName<T>> list = new List<EnumWithName<T>>();

        foreach (object o in Enum.GetValues(typeof(T)))
        {
            list.Add(new EnumWithName<T>
            {
                Name = Enum.GetName(typeof(T), o).Replace('_', ' '),
                Value = (T)o
            });
        }

        return list.ToArray();
    }
}

public enum SearchType
{
    Value_1,
    Value_2
}

String is immutable. What exactly is the meaning?

An immutable object is an object whose state cannot be modified after it is created.

So a = "ABC" <-- immutable object. "a" holds reference to the object. And, a = "DEF" <-- another immutable object, "a" holds reference to it now.

Once you assign a string object, that object can not be changed in memory.

In summary, what you did is to change the reference of "a" to a new string object.

Convert character to ASCII numeric value in java

It's simple, get the character you want, and convert it to int.

String name = "admin";
int ascii = name.charAt(0);

Can you find all classes in a package using reflection?

Spring

This example is for Spring 4, but you can find the classpath scanner in earlier versions as well.

// create scanner and disable default filters (that is the 'false' argument)
final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
// add include filters which matches all the classes (or use your own)
provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));

// get matching classes defined in the package
final Set<BeanDefinition> classes = provider.findCandidateComponents("my.package.name");

// this is how you can load the class type from BeanDefinition instance
for (BeanDefinition bean: classes) {
    Class<?> clazz = Class.forName(bean.getBeanClassName());
    // ... do your magic with the class ...
}

Google Guava

Note: In version 14, the API is still marked as @Beta, so beware in production code.

final ClassLoader loader = Thread.currentThread().getContextClassLoader();

for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
  if (info.getName().startsWith("my.package.")) {
    final Class<?> clazz = info.load();
    // do something with your clazz
  }
}

How to "crop" a rectangular image into a square with CSS?

I actually came across this same problem recently and ended up with a slightly different approach (I wasn't able to use background images). It does require a tiny bit of jQuery though to determine the orientation of the images (I' sure you could use plain JS instead though).

I wrote a blog post about it if you are interested in more explaination but the code is pretty simple:

HTML:

<ul class="cropped-images">
  <li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
  <li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>

CSS:

li {
  width: 150px; // Or whatever you want.
  height: 150px; // Or whatever you want.
  overflow: hidden;
  margin: 10px;
  display: inline-block;
  vertical-align: top;
}
li img {
  max-width: 100%;
  height: auto;
  width: auto;
}
li img.landscape {
  max-width: none;
  max-height: 100%;
}

jQuery:

$( document ).ready(function() {

    $('.cropped-images img').each(function() {
      if ($(this).width() > $(this).height()) {
        $(this).addClass('landscape');        
      }
    });

});

How to find cube root using Python?

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

def is_perfect_cube(x):
    x = abs(x)
    return int(round(x ** (1. / 3))) ** 3 == x

print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
                                   # handles this correctly

This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).

Should I use string.isEmpty() or "".equals(string)?

You can use apache commons StringUtils isEmpty() or isNotEmpty().

javascript : sending custom parameters with window.open() but its not working

To concatenate strings, use the + operator.

To insert data into a URI, encode it for URIs.

Bad:

var url = "http://localhost:8080/login?cid='username'&pwd='password'"

Good:

var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;

The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.

… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).

How to get streaming url from online streaming radio station

not that hard,

if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.

this is the stream url

"StreamUrl": "http://stream.radiotime.com/listen.stream?streamIds=3244651&rti=c051HQVbfRc4FEMbKg5RRVMzRU9KUBw%2fVBZHS0dPF1VIExNzJz0CGQtRcX8OS0o0CUkYRFJDDW8LEVRxGAEOEAcQXko%2bGgwSBBZrV1pQZgQZZxkWCA4L%7e%7e%7e",

which returns a JSON like that:

{
    "Streams": [
        {
            "StreamId": 3244651,
            "Reliability": 92,
            "Bandwidth": 64,
            "HasPlaylist": false,
            "MediaType": "MP3",
            "Url": "http://mp3hdfm32.hala.jo:8132",
            "Type": "Live"
        }
    ]
}

i believe that's the url you need: http://mp3hdfm32.hala.jo:8132

this is the station WebSite

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text