Programs & Examples On #Macports

MacPorts is a package manager for Mac OS X. It is modeled after BSD Ports. macports.org

sudo: port: command not found

there might be the situation your machine is managed by Puppet or so. Then changing root .profile or .bash_rc file does not work at all. Therefore you could add the following to your .profile file. After that you can use "mydo" instead of "sudo". It works perfectly for me.

function mydo() {
    echo Executing sudo with: "$1" "${@:2}"
    sudo $(which $1) "${@:2}"
}

Visit my page: http://www.danielkoitzsch.de/blog/2016/03/16/sudo-returns-xyz-command-not-found/

What is the difference/usage of homebrew, macports or other package installation tools?

Homebrew and macports both solve the same problem - that is the installation of common libraries and utilities that are not bundled with osx.

Typically these are development related libraries and the most common use of these tools is for developers working on osx.

They both need the xcode command line tools installed (which you can download separately from https://developer.apple.com/), and for some specific packages you will need the entire xcode IDE installed.

xcode can be installed from the mac app store, its a free download but it takes a while since its around 5GB (if I remember correctly).

macports is an osx version of the port utility from BSD (as osx is derived from BSD, this was a natural choice). For anyone familiar with any of the BSD distributions, macports will feel right at home.

One major difference between homebrew and macports; and the reason I prefer homebrew is that it will not overwrite things that should be installed "natively" in osx. This means that if there is a native package available, homebrew will notify you instead of overwriting it and causing problems further down the line. It also installs libraries in the user space (thus, you don't need to use "sudo" to install things). This helps when getting rid of libraries as well since everything is in a path accessible to you.

homebrew also enjoys a more active user community and its packages (called formulas) are updated quite often.


macports does not overwrite native OSX packages - it supplies its own version - This is the main reason I prefer macports over home-brew, you need to be certain of what you are using and Apple's change at different times to the ports and have been know to be years behind updates in some projects

Can you give a reference showing that macports overwrites native OS X packages? As far as I can tell, all macports installation happens in /opt/local

Perhaps I should clarify - I did not say anywhere in my answer that macports overwrites OSX native packages. They both install items separately.

Homebrew will warn you when you should install things "natively" (using the library/tool's preferred installer) for better compatibility. This is what I meant. It will also use as many of the local libraries that are available in OS X. From the wiki:

We really don’t like dupes in Homebrew/homebrew

However, we do like dupes in the tap!

Stuff that comes with OS X or is a library that is provided by RubyGems, CPAN or PyPi should not be duped. There are good reasons for this:

  • Duplicate libraries regularly break builds
  • Subtle bugs emerge with duplicate libraries, and to a lesser extent, duplicate tools
  • We want you to try harder to make your formula work with what OS X comes with

You can optionally overwrite the macosx supplied versions of utilities with homebrew.

How do I upgrade PHP in Mac OS X?

You may want to check out Marc Liyanage's PHP package. It comes in a nice Mac OS X installer package that you can double-click. He keeps it pretty up to date.

http://php-osx.liip.ch/

Also, although upgrading to Snow Leopard won't help you do PHP updates in the future, it will probably give you a newer version of PHP. I'm running OS X 10.6.2 and it has PHP 5.3.0.

What is the most compatible way to install python modules on a Mac?

Directly install one of the fink packages (Django 1.6 as of 2013-Nov)

fink install django-py27
fink install django-py33

Or create yourself a virtualenv:

fink install virtualenv-py27
virtualenv django-env
source django-env/bin/activate
pip install django
deactivate # when you are done

Or use fink django plus any other pip installed packages in a virtualenv

fink install django-py27
fink install virtualenv-py27
virtualenv django-env --system-site-packages
source django-env/bin/activate
# django already installed
pip install django-analytical # or anything else you might want
deactivate # back to your normally scheduled programming

Xcode is not currently available from the Software Update server

I just got the same error after I upgraded to 10.14 Mojave and had to reinstall command line tools (I don't use the full Xcode IDE and wanted command line tools a la carte).

My xcode-select -p path was right, per Basav's answer, so that wasn't the issue.

I also ran sudo softwareupdate --clear-catalog per Lambda W's answer and that reset to Apple Production, but did not make a difference.

What worked was User 92's answer to visit https://developer.apple.com/download/more/.

From there I was able to download a .dmg file that had a GUI installer wizard for command line tools :)

I installed that, then I restarted terminal and everything was back to normal.

pip installs packages successfully, but executables not found from command line

When you install Python or Python3 using MacOS installer (downloaded from Python website) - it adds an exporter to your ~/.profile script. All you need to do is just source it. Restarting all the terminals should also do the trick.

WARNING - I believe it's better to just use pip3 with Python3 - for future benefits.

If you already have Python3 installed, the following steps work for me on macOS Mojave:

  1. Install ansible first using sudo - sudo -H pip3 install ansible

  2. you create a symlink to the Python's bin path

sudo ln -s /Library/Frameworks/Python.framework/Versions/Current/bin /Library/Frameworks/Python.framework/current_python_bin

and staple it to .profile

export PATH=$PATH:/Library/Frameworks/Python.framework/current_python_bin

  1. run source ~/.profile and restart all terminal shells.

  2. Type ansible --version

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Since the question was "display" :

@Html.ValueFor(model => model.RegistrationDate, "{0:dd/MM/yyyy}")

string encoding and decoding?

You can't decode a unicode, and you can't encode a str. Try doing it the other way around.

Execute SQLite script

There are many ways to do this, one way is:

sqlite3 auction.db

Followed by:

sqlite> .read create.sql

In general, the SQLite project has really fantastic documentation! I know we often reach for Google before the docs, but in SQLite's case, the docs really are technical writing at its best. It's clean, clear, and concise.

How do I put double quotes in a string in vba?

I have written a small routine which copies formula from a cell to clipboard which one can easily paste in Visual Basic Editor.

    Public Sub CopyExcelFormulaInVBAFormat()
        Dim strFormula As String
        Dim objDataObj As Object

        '\Check that single cell is selected!
       If Selection.Cells.Count > 1 Then
            MsgBox "Select single cell only!", vbCritical
            Exit Sub
        End If

        'Check if we are not on a blank cell!
       If Len(ActiveCell.Formula) = 0 Then
            MsgBox "No Formula To Copy!", vbCritical
            Exit Sub
        End If

        'Add quotes as required in VBE
       strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)

        'This is ClsID of MSFORMS Data Object
       Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
        objDataObj.SetText strFormula, 1
        objDataObj.PutInClipboard
        MsgBox "VBA Format formula copied to Clipboard!", vbInformation

        Set objDataObj = Nothing

    End Sub

It is originally posted on Chandoo.org forums' Vault Section.

mcrypt is deprecated, what is the alternative?

You should use OpenSSL over mcrypt as it's actively developed and maintained. It provides better security, maintainability and portability. Secondly it performs AES encryption/decryption much faster. It uses PKCS7 padding by default, but you can specify OPENSSL_ZERO_PADDING if you need it. To use with a 32-byte binary key, you can specify aes-256-cbc which is much obvious than MCRYPT_RIJNDAEL_128.

Here is the code example using Mcrypt:

Unauthenticated AES-256-CBC encryption library written in Mcrypt with PKCS7 padding.

/**
 * This library is unsafe because it does not MAC after encrypting
 */
class UnsafeMcryptAES
{
    const CIPHER = MCRYPT_RIJNDAEL_128;

    public static function encrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = mcrypt_get_iv_size(self::CIPHER);
        $iv = mcrypt_create_iv($ivsize, MCRYPT_DEV_URANDOM);

        // Add PKCS7 Padding
        $block = mcrypt_get_block_size(self::CIPHER);
        $pad = $block - (mb_strlen($message, '8bit') % $block, '8bit');
        $message .= str_repeat(chr($pad), $pad);

        $ciphertext = mcrypt_encrypt(
            MCRYPT_RIJNDAEL_128,
            $key,
            $message,
            MCRYPT_MODE_CBC,
            $iv
        );

        return $iv . $ciphertext;
    }

    public static function decrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = mcrypt_get_iv_size(self::CIPHER);
        $iv = mb_substr($message, 0, $ivsize, '8bit');
        $ciphertext = mb_substr($message, $ivsize, null, '8bit');

        $plaintext = mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            $key,
            $ciphertext,
            MCRYPT_MODE_CBC,
            $iv
        );

        $len = mb_strlen($plaintext, '8bit');
        $pad = ord($plaintext[$len - 1]);
        if ($pad <= 0 || $pad > $block) {
            // Padding error!
            return false;
        }
        return mb_substr($plaintext, 0, $len - $pad, '8bit');
    }
}

And here is the version written using OpenSSL:

/**
 * This library is unsafe because it does not MAC after encrypting
 */
class UnsafeOpensslAES
{
    const METHOD = 'aes-256-cbc';

    public static function encrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = openssl_cipher_iv_length(self::METHOD);
        $iv = openssl_random_pseudo_bytes($ivsize);

        $ciphertext = openssl_encrypt(
            $message,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );

        return $iv . $ciphertext;
    }

    public static function decrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = openssl_cipher_iv_length(self::METHOD);
        $iv = mb_substr($message, 0, $ivsize, '8bit');
        $ciphertext = mb_substr($message, $ivsize, null, '8bit');

        return openssl_decrypt(
            $ciphertext,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );
    }
}

Source: If You're Typing the Word MCRYPT Into Your PHP Code, You're Doing It Wrong.

Print raw string from variable? (not getting the answers)

You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.

increase the java heap size permanently?

what platform are you running?..
if its unix, maybe adding

alias java='java -Xmx1g'  

to .bashrc (or similar) work

edit: Changing XmX to Xmx

How do I find duplicate values in a table in Oracle?

How about:

SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;

To answer the example above, it would look like:

SELECT job_number, count(*)
FROM jobs
GROUP BY job_number HAVING COUNT(*) > 1;

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

How to calculate the median of an array?

I faced a similar problem yesterday. I wrote a method with Java generics in order to calculate the median value of every collection of Numbers; you can apply my method to collections of Doubles, Integers, Floats and returns a double. Please consider that my method creates another collection in order to not alter the original one. I provide also a test, have fun. ;-)

public static <T extends Number & Comparable<T>> double median(Collection<T> numbers){
    if(numbers.isEmpty()){
        throw new IllegalArgumentException("Cannot compute median on empty collection of numbers");
    }
    List<T> numbersList = new ArrayList<>(numbers);
    Collections.sort(numbersList);
    int middle = numbersList.size()/2;
    if(numbersList.size() % 2 == 0){
        return 0.5 * (numbersList.get(middle).doubleValue() + numbersList.get(middle-1).doubleValue());
    } else {
        return numbersList.get(middle).doubleValue();
    }

}

JUnit test code snippet:

/**
 * Test of median method, of class Utils.
 */
@Test
public void testMedian() {
    System.out.println("median");
    Double expResult = 3.0;
    Double result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,13.0));
    assertEquals(expResult, result);
    expResult = 3.5;
    result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,4.0,13.0));
    assertEquals(expResult, result);
}

Usage example (consider the class name is Utils):

List<Integer> intValues = ... //omitted init
Set<Float> floatValues = ... //omitted init
.....
double intListMedian = Utils.median(intValues);
double floatSetMedian = Utils.median(floatValues);

Note: my method works on collections, you can convert arrays of numbers to list of numbers as pointed here

How to use NULL or empty string in SQL

This is ugly MSSQL:

CASE WHEN LTRIM(RTRIM(ISNULL([Address1], ''))) <> '' THEN [Address2] ELSE '' END

Windows batch: sleep

For a pure cmd.exe script, you can use this piece of code that returns the current time in hundreths of seconds.

:gettime
set hh=%time:~0,2%
set mm=%time:~3,2%
set ss=%time:~6,2%
set cc=%time:~-2%
set /A %1=hh*360000+mm*6000+ss*100+cc
goto :eof

You may then use it in a wait loop like this.

:wait
call :gettime wait0
:w2
call :gettime wait1
set /A waitt = wait1-wait0
if !waitt! lss %1 goto :w2
goto :eof

And putting all pieces together:

@echo off
setlocal enableextensions enabledelayedexpansion

call :gettime t1
echo %t1%
call :wait %1
call :gettime t2
echo %t2%
set /A tt = (t2-t1)/100
echo %tt%
goto :eof

:wait
call :gettime wait0
:w2
call :gettime wait1
set /A waitt = wait1-wait0
if !waitt! lss %1 goto :w2
goto :eof

:gettime 
set hh=%time:~0,2%
set mm=%time:~3,2%
set ss=%time:~6,2%
set cc=%time:~-2%
set /A %1=hh*360000+mm*6000+ss*100+cc
goto :eof

For a more detailed description of the commands used here, check HELP SET and HELP CALL information.

multi line comment vb.net in Visual studio 2010

I just learned this trick from a friend. Put your code inside these 2 statements and it will be commented out.

#if false

#endif

Horizontal list items

Updated Answer

I've noticed a lot of people are using this answer so I decided to update it a little bit. If you want to see the original answer, check below. The new answer demonstrates how you can add some style to your list.

_x000D_
_x000D_
ul > li {_x000D_
    display: inline-block;_x000D_
    /* You can also add some margins here to make it look prettier */_x000D_
    zoom:1;_x000D_
    *display:inline;_x000D_
    /* this fix is needed for IE7- */_x000D_
}
_x000D_
<ul>_x000D_
    <li> <a href="#">some item</a>_x000D_
_x000D_
    </li>_x000D_
    <li> <a href="#">another item</a>_x000D_
_x000D_
    </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

For me the following setting worked:

Build Settings >> Excluded Architectures

added "arm64" to both Release and Debug mode for "Any iOS Simulator SDK" option.

enter image description here

How to fix Cannot find module 'typescript' in Angular 4?

If you use yarn instead of npm, you can install typescript package for that workspace by running:

yarn add typescript

or you can install it globally by running:

sudo yarn global add typescript

to be available for any project.

Get dates from a week number in T-SQL

Quassnoi's answer works, but kind of leaves you on the hook for cleaning up the dates if they are dates in the middle of the day (his start of week leaves you one day earlier than you need to be if you use a time in the middle of the day -- you can test using GETDATE()).

I've used something like this in the past:

SELECT 
   CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL), DATECOL)), 101),
   CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL) - 6, DATECOL)), 101)

A side benefit of this is that by using @@DATEFIRST you can handle nonstandard week starting days (the default is Sunday, but with SET @@DATEFIRST you can change this).

It seems crazy that simple date manipulation in SQL Server has to be this arcane, but there you go...

How to push both value and key into PHP array

A bit weird, but this worked for me

    $array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
    $array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
    $array3 = array();

    $count = count($array1);

    for($x = 0; $x < $count; $x++){
       $array3[$array1[$x].$x] = $array2[$x];
    }

    foreach($array3 as $key => $value){
        $output_key = substr($key, 0, -1);
        $output_value = $value;
        echo $output_key.": ".$output_value."<br>";
    }

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

How to unzip a file using the command line?

Firstly, write an unzip utility using vbscript to trigger the native unzip functionality in Windows. Then pipe out the script from within your batch file and then call it. Then it's as good as stand alone. I've done it in the past for numerous tasks. This way it does not require need of third party applications, just the one batch file that does everything.

I put an example on my blog on how to unzip a file using a batch file:

' j_unzip.vbs
'
' UnZip a file script
'
' By Justin Godden 2010
'
' It's a mess, I know!!!
'

' Dim ArgObj, var1, var2
Set ArgObj = WScript.Arguments

If (Wscript.Arguments.Count > 0) Then
 var1 = ArgObj(0)
Else
 var1 = ""
End if

If var1 = "" then
 strFileZIP = "example.zip"
Else
 strFileZIP = var1
End if

'The location of the zip file.
REM Set WshShell = CreateObject("Wscript.Shell")
REM CurDir = WshShell.ExpandEnvironmentStrings("%%cd%%")
Dim sCurPath
sCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
strZipFile = sCurPath & "\" & strFileZIP
'The folder the contents should be extracted to.
outFolder = sCurPath & "\"

 WScript.Echo ( "Extracting file " & strFileZIP)

Set objShell = CreateObject( "Shell.Application" )
Set objSource = objShell.NameSpace(strZipFile).Items()
Set objTarget = objShell.NameSpace(outFolder)
intOptions = 256
objTarget.CopyHere objSource, intOptions

 WScript.Echo ( "Extracted." )

' This bit is for testing purposes
REM Dim MyVar
REM MyVar = MsgBox ( strZipFile, 65, "MsgBox Example"

Use it like this:

cscript //B j_unzip.vbs zip_file_name_goes_here.zip

How to make a JFrame Modal in Swing java

just replace JFrame to JDialog in class

public class MyDialog extends JFrame // delete JFrame and write JDialog

and then write setModal(true); in constructor

After that you will be able to construct your Form in netbeans and the form becomes modal

Map a network drive to be used by a service

A better way would be to use a symbolic link using mklink.exe. You can just create a link in the file system that any app can use. See http://en.wikipedia.org/wiki/NTFS_symbolic_link.

Webdriver and proxy server for firefox

The WebDriver API has been changed. The current snippet for setting the proxy is

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.http", "localhost");
profile.setPreference("network.proxy.http_port", "3128");
WebDriver driver = new FirefoxDriver(profile);

How do I negate a condition in PowerShell?

If you are like me and dislike the double parenthesis, you can use a function

function not ($cm, $pm) {
  if (& $cm $pm) {0} else {1}
}

if (not Test-Path C:\Code) {'it does not exist!'}

Example

Any way to make plot points in scatterplot more transparent in R?

Otherwise, you have function alpha in package scales in which you can directly input your vector of colors (even if they are factors as in your example):

library(scales)
cols <- cut(z, 6, labels = c("pink", "red", "yellow", "blue", "green", "purple"))
plot(x, y, main= "Fragment recruitment plot - FR-HIT", 
     ylab = "Percent identity", xlab = "Base pair position", 
     col = alpha(cols, 0.4), pch=16) 
# For an alpha of 0.4, i. e. an opacity of 40%.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Personnaly I encountered this issue while migrating a IIS6 website into IIS7, in order to fix this issue I used this command line :
%windir%\System32\inetsrv\appcmd migrate config "MyWebSite\"
Make sure to backup your web.config

How to get the Power of some Integer in Swift language?

Trying to combine the overloading, I tried to use generics but couldn't make it work. I finally figured to use NSNumber instead of trying to overload or use generics. This simplifies to the following:

typealias Dbl = Double // Shorter form
infix operator ** {associativity left precedence 160}
func ** (lhs: NSNumber, rhs: NSNumber) -> Dbl {return pow(Dbl(lhs), Dbl(rhs))}

The following code is the same function as above but implements error checking to see if the parameters can be converted to Doubles successfully.

func ** (lhs: NSNumber, rhs: NSNumber) -> Dbl {
    // Added (probably unnecessary) check that the numbers converted to Doubles
    if (Dbl(lhs) ?? Dbl.NaN) != Dbl.NaN && (Dbl(rhs) ?? Dbl.NaN) != Dbl.NaN {
        return pow(Dbl(lhs), Dbl(rhs))
    } else {
        return Double.NaN
    }
}

jQuery.ajax handling continue responses: "success:" vs ".done"?

If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done. This is from jQuery official site:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

Function stoi not declared

The answers above are correct, but not well explained.

g++ -std=c++11 my_cpp_code.cpp

Add -std=c++11 to your compiler options since you are most likely using an older version of debian or ubuntu which is not using by default the new c++11 standard of g++/gcc. I had the same problem on Debian Wheezy.

http://en.cppreference.com/w/cpp/string/basic_string/stol

shows in really small writing to the right in green that c++11 is required.

How to create web service (server & Client) in Visual Studio 2012?

WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.

WCF Project

enter image description here

Create a new project. enter image description here Right-Click on the project in solution explorer, select "Add Service Reference" enter image description here

Create a textbox and button in the new application. Below is my click event for the button:

private void btnGo_Click(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
        //Add error handling, null checks, etc...
        int iValue = int.Parse(txtInput.Text);
        string sResult = testClient.GetData(iValue).ToString();
        MessageBox.Show(sResult);
    }

And you're done. enter image description here

How much data can a List can hold at the maximum?

The interface however defines the size() method, which returns an int.

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

So, no limit, but after you reach Integer.MAX_VALUE, the behaviour of the list changes a bit

ArrayList (which is tagged) is backed by an array, and is limited to the size of the array - i.e. Integer.MAX_VALUE

How to set time zone in codeigniter?

you can try this:

date_default_timezone_set('Asia/Kolkata');

In application/config.php OR application/autoload.php

There is look like this:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

date_default_timezone_set('Asia/Kolkata');

It's working fine for me, i think this is the best way to define DEFAULT TIMEZONE in codeignitor.

Can't connect to Postgresql on port 5432

Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf and postgres.conf files I finally found out that my firewall was overriding everything and therefore blocking connections

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

You could use

var a = document.querySelector('a[data-a="1"]');

instead of

var a = document.querySelector('a[data-a=1]');

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

Short Solution:

easy_install <package name>

For Example:

easy_install pandas

Alternate solution:

pip install <package_name> --trusted-host pypi.org --trusted-host files.pythonhosted.org

Example:

pip install pandas --trusted-host pypi.org --trusted-host files.pythonhosted.org

Visual studio code terminal, how to run a command with administrator rights?

Running as admin didn't help me. (also got errors with syscall: rename)

Turns out this error can also occur if files are locked by Windows.

This can occur if :

  • You are actually running the project
  • You have files open in both Visual Studio and VSCode.

Running as admin doesn't get around windows file locking.

I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error

Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.

How to retrieve data from sqlite database in android and display it in TextView

You may use this following code actually it is rough but plz check it out

db = openOrCreateDatabase("sms.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor cc = db.rawQuery("SELECT * FROM datatable", null);
final ArrayList<String> row1 = new ArrayList<String>();
final ArrayList<String> row2 = new ArrayList<String>();

if(cc!=null) {
    cc.moveToFirst();   
    startManagingCursor(cc);
    for (int i=0; i<cc.getCount(); i++) {

    String number  = cc.getString(0);
    String message = cc.getString(1);
    row1.add(number);
    row2.add(message);

    final EditText et3 = (EditText) findViewById(R.id.editText3);
    final EditText et4 = (EditText) findViewById(R.id.editText4);
    Button bt1 = (Button) findViewById(R.id.button1);
    bt1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            switch (v.getId()) {
                case R.id.button1:
                    et3.setText(row1.get(count));
                    et4.setText(row2.get(count));
                    count++;
                    break;
                default:
                    break;
            }

        }
    });

cc.moveToNext();
}

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

How can I select records ONLY from yesterday?

If you don't support future dated transactions then something like this might work:

AND oh.tran_date >= trunc(sysdate-1)

Displaying the Error Messages in Laravel after being Redirected from controller

Below input field I include additional view:

@include('input-errors', ['inputName' => 'inputName']) #For your case it would be 'email'

input-errors.blade.php

@foreach ($errors->get($inputName) as $message)
    <span class="input-error">{{ $message }}</span>
@endforeach

CSS - adds red color to the message.

.input-error {
    color: #ff5555;
}

How to determine an object's class?

I use the blow function in my GeneralUtils class, check it may be useful

    public String getFieldType(Object o) {
    if (o == null) {
        return "Unable to identify the class name";
    }
    return o.getClass().getName();
}

Getting realtime output using subprocess

By setting the buffer size to 1, you essentially force the process to not buffer the output.

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print line,
p.stdout.close()
p.wait()

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Setting default values for columns in JPA

You can't do this with the column annotation. I think the only way is to set the default value when a object is created. Maybe the default constructor would be the right place to do that.

How to iterate using ngFor loop Map containing key as string and values as map iteration

Angular’s keyvalue pipe can be used, but unfortunately it sorts by key. Maps already have an order and it would be great to be able to keep it!

We can define out own pipe mapkeyvalue which preserves the order of items in the map:

import { Pipe, PipeTransform } from '@angular/core';

// Holds a weak reference to its key (here a map), so if it is no longer referenced its value can be garbage collected.
const cache = new WeakMap<ReadonlyMap<any, any>, Array<{ key: any; value: any }>>();

@Pipe({ name: 'mapkeyvalue', pure: true })
export class MapKeyValuePipe implements PipeTransform {
  transform<K, V>(input: ReadonlyMap<K, V>): Iterable<{ key: K; value: V }> {
    const existing = cache.get(input);
    if (existing !== undefined) {
      return existing;
    }

    const iterable = Array.from(input, ([key, value]) => ({ key, value }));
    cache.set(input, iterable);
    return iterable;
  }
}

It can be used like so:

<mat-select>
  <mat-option *ngFor="let choice of choicesMap | mapkeyvalue" [value]="choice.key">
    {{ choice.value }}
  </mat-option>
</mat-select>

Loop code for each file in a directory

Try GLOB()

$dir = "/etc/php5/*";  

// Open a known directory, and proceed to read its contents  
foreach(glob($dir) as $file)  
{  
    echo "filename: $file : filetype: " . filetype($file) . "<br />";  
}  

Conversion of a datetime2 data type to a datetime data type results out-of-range value

Sometimes it works fine on development machines and not in servers. In my case I had to put :

<globalization uiCulture="es" culture="es-CO" />

In the web.config file.

The timezone in the machine (Server) was right (to the CO locale) but the web app did not. This setting done and it worked fine again.

Off course, all dates had value.

:D

How to decompile to java files intellij idea

You could use one of these (you can both use them online or download them, there is some info about each of them) : http://www.javadecompilers.com/

The one IntelliJ IDEA uses is fernflower, but it can't handle recent things - like String/Enum switches, generics (didn't test this one personally, only read about it), ... I just tried cfr from the above website and the result was the same as with the built-in decompiler (except for the Enum switch I had in my class).

How to strip HTML tags from a string in SQL Server?

There is a UDF that will do that described here:

User Defined Function to Strip HTML

CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT
    SET @Start = CHARINDEX('<',@HTMLText)
    SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
    SET @Length = (@End - @Start) + 1
    WHILE @Start > 0 AND @End > 0 AND @Length > 0
    BEGIN
        SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
        SET @Start = CHARINDEX('<',@HTMLText)
        SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
        SET @Length = (@End - @Start) + 1
    END
    RETURN LTRIM(RTRIM(@HTMLText))
END
GO

Edit: note this is for SQL Server 2005, but if you change the keyword MAX to something like 4000, it will work in SQL Server 2000 as well.

How do you send a Firebase Notification to all devices via CURL?

The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic. Copy this in your main activity

FirebaseMessaging.getInstance().subscribeToTopic("all");

Now send the request as

{
   "to":"/topics/all",
   "data":
   {
      "title":"Your title",
      "message":"Your message"
      "image-url":"your_image_url"
   }
}

This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.

You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM


To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA and either TopicB or TopicC:

{
   "data":
   {
      "title": "Your title",
      "message": "Your message"
      "image-url": "your_image_url"
   },
   "condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}

Read more about conditions and topics here on FCM documentation

How to get the groups of a user in Active Directory? (c#, asp.net)

In case Translate works locally but not remotly e.i group.Translate(typeof(NTAccount)

If you want to have the application code executes using the LOGGED IN USER identity, then enable impersonation. Impersonation can be enabled thru IIS or by adding the following element in the web.config.

<system.web>
<identity impersonate="true"/>

If impersonation is enabled, the application executes using the permissions found in your user account. So if the logged in user has access, to a specific network resource, only then will he be able to access that resource thru the application.

Thank PRAGIM tech for this information from his diligent video

Windows authentication in asp.net Part 87:

https://www.youtube.com/watch?v=zftmaZ3ySMc

But impersonation creates a lot of overhead on the server

The best solution to allow users of certain network groups is to deny anonymous in the web config <authorization><deny users="?"/><authentication mode="Windows"/>

and in your code behind, preferably in the global.asax, use the HttpContext.Current.User.IsInRole :

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User.IsInRole("TheDomain\TheGroup") Then
//code to do when user is in group
End If

NOTE: The Group must be written with a backslash \ i.e. "TheDomain\TheGroup"

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

Also, the Angular docs now have a cookbook example that uses a Subject.


Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

nav.service.ts

import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
    this.navchange.emit(number);
  }
  getNavChangeEmitter() {
    return this.navchange;
  }
}

components.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emitNavChangeEvent(item);
  }
}

Plunker

Multiple file upload in php

I run foreach loop with error element, look like

 foreach($_FILES['userfile']['error'] as $k=>$v)
 {
    $uploadfile = 'uploads/'. basename($_FILES['userfile']['name'][$k]);
    if (move_uploaded_file($_FILES['userfile']['tmp_name'][$k], $uploadfile)) 
    {
        echo "File : ", $_FILES['userfile']['name'][$k] ," is valid, and was                      successfully uploaded.\n";
    }

    else 
    {
        echo "Possible file : ", $_FILES['userfile']['name'][$k], " upload attack!\n";
    }   

 }

Best Way to Refresh Adapter/ListView on Android

If you are using LoaderManager try with this statement:

getLoaderManager().restartLoader(0, null, this);

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

How do I programmatically click a link with javascript?

Many of the above methods have been deprecated. It is now recommended to use the constructor found here

function clickAnchorTag() {
    var event = document.createEvent('MouseEvent');
    event = new CustomEvent('click');
    var a = document.getElementById('nameOfID');
    a.dispatchEvent(event);
}

This will cause the anchor tag to be clicked, but it wont show if pop-up blockers are active so the user will need to allow pop-ups.

Default keystore file does not exist?

Use This for MAC users

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

HTTP authentication logout via PHP

Method that works nicely in Safari. Also works in Firefox and Opera, but with a warning.

Location: http://[email protected]/

This tells browser to open URL with new username, overriding previous one.

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

You are trying to use it as a CSS file, probably by using

<link rel=stylesheet href=ABCD.html>

or

<style>
@import url("ABCD.html");
</style>

How to index characters in a Golang string?

Can be done via slicing too

package main

import "fmt"

func main() {
    fmt.Print("HELLO"[1:2])
}

NOTE: This solution only works for ASCII characters.

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

Shuffle an array with python, randomize array item order with python

I don't know I used random.shuffle() but it return 'None' to me, so I wrote this, might helpful to someone

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

SQL select * from column where year = 2010

T-SQL and others;

select * from t where year(Columnx) = 2010

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

This exception will come in case your server is based on JDK 7 and your client is on JDK 6 and using SSL certificates. In JDK 7 sslv2hello message handshaking is disabled by default while in JDK 6 sslv2hello message handshaking is enabled. For this reason when your client trying to connect server then a sslv2hello message will be sent towards server and due to sslv2hello message disable you will get this exception. To solve this either you have to move your client to JDK 7 or you have to use 6u91 version of JDK. But to get this version of JDK you have to get the MOS (My Oracle Support) Enterprise support. This patch is not public.

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I also had the same issue. I also tried to look for solutions, but after I didn't find any of the solutions working, I tried to restart my mobile (Android device), and it resolved the issue.

Please give it a try! Restart your mobile device and Eclipse to be on safe side and check if it works.

How to 'foreach' a column in a DataTable using C#?

In LINQ you could do something like:

foreach (var data in from DataRow row in dataTable.Rows
                     from DataColumn col in dataTable.Columns
                          where
                              row[col] != null
                          select row[col])
{
    // do something with data
}

Asynchronous Process inside a javascript for loop

The for loop runs immediately to completion while all your asynchronous operations are started. When they complete some time in the future and call their callbacks, the value of your loop index variable i will be at its last value for all the callbacks.

This is because the for loop does not wait for an asynchronous operation to complete before continuing on to the next iteration of the loop and because the async callbacks are called some time in the future. Thus, the loop completes its iterations and THEN the callbacks get called when those async operations finish. As such, the loop index is "done" and sitting at its final value for all the callbacks.

To work around this, you have to uniquely save the loop index separately for each callback. In Javascript, the way to do that is to capture it in a function closure. That can either be done be creating an inline function closure specifically for this purpose (first example shown below) or you can create an external function that you pass the index to and let it maintain the index uniquely for you (second example shown below).

As of 2016, if you have a fully up-to-spec ES6 implementation of Javascript, you can also use let to define the for loop variable and it will be uniquely defined for each iteration of the for loop (third implementation below). But, note this is a late implementation feature in ES6 implementations so you have to make sure your execution environment supports that option.

Use .forEach() to iterate since it creates its own function closure

someArray.forEach(function(item, i) {
    asynchronousProcess(function(item) {
        console.log(i);
    });
});

Create Your Own Function Closure Using an IIFE

var j = 10;
for (var i = 0; i < j; i++) {
    (function(cntr) {
        // here the value of i was passed into as the argument cntr
        // and will be captured in this function closure so each
        // iteration of the loop can have it's own value
        asynchronousProcess(function() {
            console.log(cntr);
        });
    })(i);
}

Create or Modify External Function and Pass it the Variable

If you can modify the asynchronousProcess() function, then you could just pass the value in there and have the asynchronousProcess() function the cntr back to the callback like this:

var j = 10;
for (var i = 0; i < j; i++) {
    asynchronousProcess(i, function(cntr) {
        console.log(cntr);
    });
}

Use ES6 let

If you have a Javascript execution environment that fully supports ES6, you can use let in your for loop like this:

const j = 10;
for (let i = 0; i < j; i++) {
    asynchronousProcess(function() {
        console.log(i);
    });
}

let declared in a for loop declaration like this will create a unique value of i for each invocation of the loop (which is what you want).

Serializing with promises and async/await

If your async function returns a promise, and you want to serialize your async operations to run one after another instead of in parallel and you're running in a modern environment that supports async and await, then you have more options.

async function someFunction() {
    const j = 10;
    for (let i = 0; i < j; i++) {
        // wait for the promise to resolve before advancing the for loop
        await asynchronousProcess();
        console.log(i);
    }
}

This will make sure that only one call to asynchronousProcess() is in flight at a time and the for loop won't even advance until each one is done. This is different than the previous schemes that all ran your asynchronous operations in parallel so it depends entirely upon which design you want. Note: await works with a promise so your function has to return a promise that is resolved/rejected when the asynchronous operation is complete. Also, note that in order to use await, the containing function must be declared async.

Run asynchronous operations in parallel and use Promise.all() to collect results in order

 function someFunction() {
     let promises = [];
     for (let i = 0; i < 10; i++) {
          promises.push(asynchonousProcessThatReturnsPromise());
     }
     return Promise.all(promises);
 }

 someFunction().then(results => {
     // array of results in order here
     console.log(results);
 }).catch(err => {
     console.log(err);
 });

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

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

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

$ sudo apt-get install libssl-dev

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

$ sudo yum install openssl-devel 

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

dnf install openssl-devel

PHP CURL & HTTPS

One important note, the solution mentioned above will not work on local host, you have to upload your code to server and then it will work. I was getting no error, than bad request, the problem was I was using localhost (test.dev,myproject.git). Both solution above work, the solution that uses SSL cert is recommended.

  1. Go to https://curl.haxx.se/docs/caextract.html, download the latest cacert.pem. Store is somewhere (not in public folder - but will work regardless)

  2. Use this code

".$result; //echo "
Path:".$_SERVER['DOCUMENT_ROOT'] . "/ssl/cacert.pem"; // this is for troubleshooting only ?>
  1. Upload the code to live server and test.

Simple dynamic breadcrumb

This is the code that i personally use in my sites. Works outside of the box.

<?php
function breadcrumbs($home = 'Home') {
  global $page_title; //global varable that takes it's value from the page that breadcrubs will appear on. Can be deleted if you wish, but if you delete it, delete also the title tage inside the <li> tag inside the foreach loop.
    $breadcrumb  = '<div class="breadcrumb-container"><div class="container"><ol class="breadcrumb">';
    $root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
    $breadcrumb .= '<li><i class="fa fa-home"></i><a href="' . $root_domain . '" title="Home Page"><span>' . $home . '</span></a></li>';
    foreach ($breadcrumbs as $crumb) {
        $link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
        $root_domain .=  $crumb . '/';
        $breadcrumb .= '<li><a href="'. $root_domain .'" title="'.$page_title.'"><span>' . $link . '</span></a></li>';
    }
    $breadcrumb .= '</ol>';
    $breadcrumb .= '</div>';
    $breadcrumb .= '</div>';
    return $breadcrumb;
}
echo breadcrumbs();
?>

The css:

.breadcrumb-container {
    width: 100%;
    background-color: #f8f8f8;
    border-bottom-color: 1px solid #f4f4f4;
    list-style: none;
    margin-top: 72px;
    min-height: 25px;
    box-shadow: 0 3px 0 rgba(60, 57, 57, .2)
}

.breadcrumb-container li {
    display: inline
}
.breadcrumb {
    font-size: 12px;
    padding-top: 3px
}
.breadcrumb>li:last-child:after {
    content: none
}

.breadcrumb>li:last-child {
    font-weight: 700;
    font-style: italic
}
.breadcrumb>li>i {
    margin-right: 3px
}

.breadcrumb>li:after {
    font-family: FontAwesome;
    content: "\f101";
    font-size: 11px;
    margin-left: 3px;
    margin-right: 3px
}
.breadcrumb>li+li:before {
    font-size: 11px;
    padding-left: 3px
}

Feel free to play around with the css padding and margins until you get it right for your own site.

Asp.net Validation of viewstate MAC failed

my problem was this piece of javascript code

$('input').each(function(ele, indx){
    this.value = this.value.toUpperCase();
});

Turns it was messing with viewstate hidden field so I changed it to below code and it worked

$('input:visible').each(function(ele, indx){
    this.value = this.value.toUpperCase();
});

How to override trait function and call it from the overridden function?

Your last one was almost there:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    use A {
        calc as protected traitcalc;
    }

    function calc($v) {
        $v++;
        return $this->traitcalc($v);
    }
}

The trait is not a class. You can't access its members directly. It's basically just automated copy and paste...

How to calculate a logistic sigmoid function in Python?

Here's how you would implement the logistic sigmoid in a numerically stable way (as described here):

def sigmoid(x):
    "Numerically-stable sigmoid function."
    if x >= 0:
        z = exp(-x)
        return 1 / (1 + z)
    else:
        z = exp(x)
        return z / (1 + z)

Or perhaps this is more accurate:

import numpy as np

def sigmoid(x):  
    return np.exp(-np.logaddexp(0, -x))

Internally, it implements the same condition as above, but then uses log1p.

In general, the multinomial logistic sigmoid is:

def nat_to_exp(q):
    max_q = max(0.0, np.max(q))
    rebased_q = q - max_q
    return np.exp(rebased_q - np.logaddexp(-max_q, np.logaddexp.reduce(rebased_q)))

(However, logaddexp.reduce could be more accurate.)

Illegal mix of collations MySQL Error

SET collation_connection = 'utf8_general_ci';

then for your databases

ALTER DATABASE your_database_name CHARACTER SET utf8 COLLATE utf8_general_ci;

ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

MySQL sneaks swedish in there sometimes for no sensible reason.

How do I get the directory that a program is running from?

I know it is very late at the day to throw an answer at this one but I found that none of the answers were as useful to me as my own solution. A very simple way to get the path from your CWD to your bin folder is like this:

int main(int argc, char* argv[])
{
    std::string argv_str(argv[0]);
    std::string base = argv_str.substr(0, argv_str.find_last_of("/"));
}

You can now just use this as a base for your relative path. So for example I have this directory structure:

main
  ----> test
  ----> src
  ----> bin

and I want to compile my source code to bin and write a log to test I can just add this line to my code.

std::string pathToWrite = base + "/../test/test.log";

I have tried this approach on Linux using full path, alias etc. and it works just fine.

NOTE:

If you are on windows you should use a '\' as the file separator not '/'. You will have to escape this too for example:

std::string base = argv[0].substr(0, argv[0].find_last_of("\\"));

I think this should work but haven't tested, so comment would be appreciated if it works or a fix if not.

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

Uncaught ReferenceError: google is not defined error will be gone when removed the async defer from the map API script tag.

How to see the values of a table variable at debug time in T-SQL?

DECLARE @v XML = (SELECT * FROM <tablename> FOR XML AUTO)

Insert the above statement at the point where you want to view the table's contents. The table's contents will be rendered as XML in the locals window, or you can add @v to the watches window.

enter image description here

Where's the DateTime 'Z' format specifier?

Maybe the "K" format specifier would be of some use. This is the only one that seems to mention the use of capital "Z".

"Z" is kind of a unique case for DateTimes. The literal "Z" is actually part of the ISO 8601 datetime standard for UTC times. When "Z" (Zulu) is tacked on the end of a time, it indicates that that time is UTC, so really the literal Z is part of the time. This probably creates a few problems for the date format library in .NET, since it's actually a literal, rather than a format specifier.

Laravel view not found exception

If your path to view is true first try to config:cache and route:cache if nothing changed check your resource path permission are true.

example: your can do it in ubuntu with :

sudo chgrp -R www-data resources/views
sudo usermod -a -G www-data $USER

Convert list of ASCII codes to string (byte array) in Python

struct.pack('B' * len(integers), *integers)

*sequence means "unpack sequence" - or rather, "when calling f(..., *args ,...), let args = sequence".

How to trace the path in a Breadth-First Search?

I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.

In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour will have to be the end, and once that happens the shortest path is found and program can return.

I would modify the the method as follow, pay close attention to the for loop

graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}


    def bfs(graph_to_search, start, end):
        queue = [[start]]
        visited = set()

    while queue:
        # Gets the first path in the queue
        path = queue.pop(0)

        # Gets the last node in the path
        vertex = path[-1]

        # Checks if we got to the end
        if vertex == end:
            return path
        # We check if the current node is already in the visited nodes set in order not to recheck it
        elif vertex not in visited:
            # enumerate all adjacent nodes, construct a new path and push it into the queue
            for current_neighbour in graph_to_search.get(vertex, []):
                new_path = list(path)
                new_path.append(current_neighbour)
                queue.append(new_path)

                #No need to visit other neighbour. Return at once
                if current_neighbour == end
                    return new_path;

            # Mark the vertex as visited
            visited.add(vertex)


print bfs(graph, 1, 13)

The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

In my maven project this error occurs, after i closed my projects and reopens them. The dependencys wasn´t build correctly at that time. So for me the solution was just to update the Maven Dependencies of the projects!

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

AngularJS : Why ng-bind is better than {{}} in angular?

You can refer to this site it will give you a explanation which one is better as i know {{}} this is slower than ng-bind.

http://corpus.hubwiz.com/2/angularjs/16125872.html refer this site.

Reference list item by index within Django template?

{{ data.0 }} should work.

Let's say you wrote data.obj django tries data.obj and data.obj(). If they don't work it tries data["obj"]. In your case data[0] can be written as {{ data.0 }}. But I recommend you to pull data[0] in the view and send it as separate variable.

How can I list all commits that changed a specific file?

If you want to look for all commits by filename and not by filepath, use:

git log --all -- '*.wmv'

jquery onclick change css background image

You need to use background-image instead of backgroundImage. For example:

$(function() {
  $('.home').click(function() {
    $(this).css('background-image', 'url(images/tabs3.png)');
  });
}):

Delete everything in a MongoDB database

By compiling answers from @Robse and @DanH (kudos!), I've got the following solution which completely satisfies me:

db.getCollectionNames().forEach( function(collection_name) { 
  if (collection_name.indexOf("system.") == -1) 
       db[collection_name].drop();
  else  
       db.collection_name.remove({}); 
});

Connect to you database, run the code.

It cleans the database by dropping the user collections and emptying the system collections.

"The operation is not valid for the state of the transaction" error and transaction scope

I also come across same problem, I changed transaction timeout to 15 minutes and it works. I hope this helps.

TransactionOptions options = new TransactionOptions();
options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
options.Timeout = new TimeSpan(0, 15, 0);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,options))
{
    sp1();
    sp2();
    ...

}

Recommended way to insert elements into map

To quote:

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

So insert will not change the value if the key already exists, the [] operator will.

EDIT:

This reminds me of another recent question - why use at() instead of the [] operator to retrieve values from a vector. Apparently at() throws an exception if the index is out of bounds whereas [] operator doesn't. In these situations it's always best to look up the documentation of the functions as they will give you all the details. But in general, there aren't (or at least shouldn't be) two functions/operators that do the exact same thing.

My guess is that, internally, insert() will first check for the entry and afterwards itself use the [] operator.

Iterating through a List Object in JSP

another example with just scriplets, when iterating through an ArrayList that contains Maps.

<%   
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");    

for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>    
</tr>
...
<%}%>

Get the key corresponding to the minimum value within a dictionary

d={}
d[320]=1
d[321]=0
d[322]=3
value = min(d.values())
for k in d.keys(): 
    if d[k] == value:
        print k,d[k]

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Select Project / Specific Folder --> Right Click --> Add Files to Project -- > Select the File you want to add.

This worked for me.

Background thread with QThread in PyQt

I created a little example that shows 3 different and simple ways of dealing with threads. I hope it will help you find the right approach to your problem.

import sys
import time

from PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread,
                          QThreadPool, pyqtSignal)


# Subclassing QThread
# http://qt-project.org/doc/latest/qthread.html
class AThread(QThread):

    def run(self):
        count = 0
        while count < 5:
            time.sleep(1)
            print("A Increasing")
            count += 1

# Subclassing QObject and using moveToThread
# http://blog.qt.digia.com/blog/2007/07/05/qthreads-no-longer-abstract
class SomeObject(QObject):

    finished = pyqtSignal()

    def long_running(self):
        count = 0
        while count < 5:
            time.sleep(1)
            print("B Increasing")
            count += 1
        self.finished.emit()

# Using a QRunnable
# http://qt-project.org/doc/latest/qthreadpool.html
# Note that a QRunnable isn't a subclass of QObject and therefore does
# not provide signals and slots.
class Runnable(QRunnable):

    def run(self):
        count = 0
        app = QCoreApplication.instance()
        while count < 5:
            print("C Increasing")
            time.sleep(1)
            count += 1
        app.quit()


def using_q_thread():
    app = QCoreApplication([])
    thread = AThread()
    thread.finished.connect(app.exit)
    thread.start()
    sys.exit(app.exec_())

def using_move_to_thread():
    app = QCoreApplication([])
    objThread = QThread()
    obj = SomeObject()
    obj.moveToThread(objThread)
    obj.finished.connect(objThread.quit)
    objThread.started.connect(obj.long_running)
    objThread.finished.connect(app.exit)
    objThread.start()
    sys.exit(app.exec_())

def using_q_runnable():
    app = QCoreApplication([])
    runnable = Runnable()
    QThreadPool.globalInstance().start(runnable)
    sys.exit(app.exec_())

if __name__ == "__main__":
    #using_q_thread()
    #using_move_to_thread()
    using_q_runnable()

Currency formatting in Python

This is an ancient post, but I just implemented the following solution which:

  • Doesn't require external modules
  • Doesn't require creating a new function
  • Can be done in-line
  • Handles multiple variables
  • Handles negative dollar amounts

Code:

num1 = 4153.53
num2 = -23159.398598

print 'This: ${:0,.0f} and this: ${:0,.2f}'.format(num1, num2).replace('$-','-$')

Output:

This: $4,154 and this: -$23,159.40

And for the original poster, obviously, just switch $ for £

Get current date/time in seconds

Using new Date().getTime() / 1000 is an incomplete solution for obtaining the seconds, because it produces timestamps with floating-point units.

const timestamp = new Date() / 1000; // 1405792936.933
// Technically, .933 would be milliseconds. 

A better solution would be:

// Rounds the value
const timestamp = Math.round(new Date() / 1000); // 1405792937

// - OR -

// Floors the value
const timestamp = new Date() / 1000 | 0; // 1405792936

Values without floats are also safer for conditional statements, as the float may produce unwanted results. The granularity you obtain with a float may be more than needed.

if (1405792936.993 < 1405792937) // true

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

module.exports vs exports in Node.js

Initially,module.exports=exports , and the require function returns the object module.exports refers to.

if we add property to the object, say exports.a=1, then module.exports and exports still refer to the same object. So if we call require and assign the module to a variable, then the variable has a property a and its value is 1;

But if we override one of them, for example, exports=function(){}, then they are different now: exports refers to a new object and module.exports refer to the original object. And if we require the file, it will not return the new object, since module.exports is not refer to the new object.

For me, i will keep adding new property, or override both of them to a new object. Just override one is not right. And keep in mind that module.exports is the real boss.

Hibernate Auto Increment ID

Hibernate defines five types of identifier generation strategies:

AUTO - either identity column, sequence or table depending on the underlying DB

TABLE - table holding the id

IDENTITY - identity column

SEQUENCE - sequence

identity copy – the identity is copied from another entity

Example using Table

@Id
@GeneratedValue(strategy=GenerationType.TABLE , generator="employee_generator")
@TableGenerator(name="employee_generator", 
                table="pk_table", 
                pkColumnName="name", 
                valueColumnName="value",                            
                allocationSize=100) 
@Column(name="employee_id")
private Long employeeId;

for more details, check the link.

How to display Toast in Android?

Simplest way! (To Display In Your Main Activity, replace First Argument for other activity)

Button.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
        Toast.makeText(MainActivity.this,"Toast Message",Toast.LENGTH_SHORT).show();
    }
}

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

I had a problem there. When I JSON encode a string with a character like "é", every browsers will return the same "é", except IE which will return "\u00e9".

Then with PHP json_decode(), it will fail if it find "é", so for Firefox, Opera, Safari and Chrome, I've to call utf8_encode() before json_decode().

Note : with my tests, IE and Firefox are using their native JSON object, others browsers are using json2.js.

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

Multiple ways to delete Key in Hash. you can use any Method from below

hash = {a: 1, b: 2, c: 3}
hash.except!(:a) # Will remove *a* and return HASH
hash # Output :- {b: 2, c: 3}

hash = {a: 1, b: 2, c: 3}
hash.delete(:a) # will remove *a* and return 1 if *a* not present than return nil

So many ways is there, you can look on Ruby doc of Hash here.

Thank you

How to draw a path on a map using kml file?

There is now a beta available of Google Maps KML Importing Utility.

It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams

KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());

or local resources

KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());

After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.

layer.addLayerToMap();

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

How to comment and uncomment blocks of code in the Office VBA Editor

With MZ-Tools installed, I comment/uncomment blocks in VBE by using the keyboard shortcut
Ctrl+Alt+C (MZ-Tools default)

Forking / Multi-Threaded Processes | Bash

I don't know of any explicit fork call in bash. What you probably want to do is append & to a command that you want to run in the background. You can also use & on functions that you define within a bash script:

do_something_with_line()
{
  line=$1
  foo
  foo2
  foo3
}

for line in file
do
  do_something_with_line $line &
done

EDIT: to put a limit on the number of simultaneous background processes, you could try something like this:

for line in file
do
  while [`jobs | wc -l` -ge 50 ]
  do
    sleep 5
  done
  do_something_with_line $line &
done

sed whole word search and replace

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>

How to know the git username and email saved during configuration?

Considering what @Robert said, I tried to play around with the config command and it seems that there is a direct way to know both the name and email.

To know the username, type:

git config user.name

To know the email, type:

git config user.email

These two output just the name and email respectively and one doesn't need to look through the whole list. Comes in handy.

Initial size for the ArrayList

I faced with the similar issue, and just knowing the arrayList is a resizable-array implementation of the List interface, I also expect you can add element to any point, but at least have the option to define the initial size. Anyway, you can create an array first and convert that to a list like:

  int index = 5;
  int size = 10;

  Integer[] array = new Integer[size];
  array[index] = value;
  ...
  List<Integer> list = Arrays.asList(array);

or

  List<Integer> list = Arrays.asList(new Integer[size]);
  list.set(index, value);

What is the difference between map and flatMap and a good use case for each?

all examples are good....Here is nice visual illustration... source courtesy : DataFlair training of spark

Map : A map is a transformation operation in Apache Spark. It applies to each element of RDD and it returns the result as new RDD. In the Map, operation developer can define his own custom business logic. The same logic will be applied to all the elements of RDD.

Spark RDD map function takes one element as input process it according to custom code (specified by the developer) and returns one element at a time. Map transforms an RDD of length N into another RDD of length N. The input and output RDDs will typically have the same number of records.

enter image description here

Example of map using scala :

val x = spark.sparkContext.parallelize(List("spark", "map", "example",  "sample", "example"), 3)
val y = x.map(x => (x, 1))
y.collect
// res0: Array[(String, Int)] = 
//    Array((spark,1), (map,1), (example,1), (sample,1), (example,1))

// rdd y can be re writen with shorter syntax in scala as 
val y = x.map((_, 1))
y.collect
// res1: Array[(String, Int)] = 
//    Array((spark,1), (map,1), (example,1), (sample,1), (example,1))

// Another example of making tuple with string and it's length
val y = x.map(x => (x, x.length))
y.collect
// res3: Array[(String, Int)] = 
//    Array((spark,5), (map,3), (example,7), (sample,6), (example,7))

FlatMap :

A flatMap is a transformation operation. It applies to each element of RDD and it returns the result as new RDD. It is similar to Map, but FlatMap allows returning 0, 1 or more elements from map function. In the FlatMap operation, a developer can define his own custom business logic. The same logic will be applied to all the elements of the RDD.

What does "flatten the results" mean?

A FlatMap function takes one element as input process it according to custom code (specified by the developer) and returns 0 or more element at a time. flatMap() transforms an RDD of length N into another RDD of length M.

enter image description here

Example of flatMap using scala :

val x = spark.sparkContext.parallelize(List("spark flatmap example",  "sample example"), 2)

// map operation will return Array of Arrays in following case : check type of res0
val y = x.map(x => x.split(" ")) // split(" ") returns an array of words
y.collect
// res0: Array[Array[String]] = 
//  Array(Array(spark, flatmap, example), Array(sample, example))

// flatMap operation will return Array of words in following case : Check type of res1
val y = x.flatMap(x => x.split(" "))
y.collect
//res1: Array[String] = 
//  Array(spark, flatmap, example, sample, example)

// RDD y can be re written with shorter syntax in scala as 
val y = x.flatMap(_.split(" "))
y.collect
//res2: Array[String] = 
//  Array(spark, flatmap, example, sample, example)

C# naming convention for constants?

Leave Hungarian to the Hungarians.

In the example I'd even leave out the definitive article and just go with

private const int Answer = 42;

Is that answer or is that the answer?

*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to life, the universe and everything.

Hibernate Delete query

instead of using

session.delete(object)

use

getHibernateTemplate().delete(object)

In both place for select query and also for delete use getHibernateTemplate()

In select query you have to use DetachedCriteria or Criteria

Example for select query

List<foo> fooList = new ArrayList<foo>();
DetachedCriteria queryCriteria = DetachedCriteria.forClass(foo.class);
queryCriteria.add(Restrictions.eq("Column_name",restriction));
fooList = getHibernateTemplate().findByCriteria(queryCriteria);

In hibernate avoid use of session,here I am not sure but problem occurs just because of session use

SQL: How do I SELECT only the rows with a unique value on certain column?

Sorry you're not using PostgreSQL...

SELECT DISTINCT ON contract, activity * FROM thetable ORDER BY contract, activity

http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT

Oh wait. You only want values with exactly one...

SELECT contract, activity, count() FROM thetable GROUP BY contract, activity HAVING count() = 1

Bash script to run php script

If you have PHP installed as a command line tool (try issuing php to the terminal and see if it works), your shebang (#!) line needs to look like this:

#!/usr/bin/php

Put that at the top of your script, make it executable (chmod +x myscript.php), and make a Cron job to execute that script (same way you'd execute a bash script).

You can also use php myscript.php.

HTML how to clear input using javascript?

You don't need to bother with that. Just write

<input type="text" name="email" placeholder="[email protected]" size="30">

replace the value with placeholder

iOS 7 status bar back to iOS 6 default style in iPhone app?

This might be too late to share, but I have something to contribute which might help someone, I was trying to sub-class the UINavigationBar and wanted to make it look like ios 6 with black status bar and status bar text in white.

Here is what I found working for that

        self.navigationController?.navigationBar.clipsToBounds = true
        self.navigationController?.navigationBar.translucent = false
        self.navigationController?.navigationBar.barStyle = .Black
        self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()

It made my status bar background black, status bar text white and navigation bar's color white.

iOS 9.3, XCode 7.3.1

How to properly exit a C# application?

This will work from anywhere, inside Form(), Form_Load(), or any event handler. I posted before, but I don't see it now?!?

public void exit(int exitCode)
{
    if (System.Windows.Forms.Application.MessageLoop)
    {
       // Use this since we are in a running Form
       System.Windows.Forms.Application.Exit();
       System.Environment.Exit(exitCode);
    }
    else
    {
       // Form ended or never .Run
       System.Environment.Exit(exitCode);
    }
} //* end exit()

How do I delete specific lines in Notepad++?

Here is a way that removes the lines containing "YOURTEXT" completely:

  • Open the Replace dialog
  • Enter the following search string: .*YOURTEXT.*[\r]?[\n] (replace YOURTEXT with your text)
  • Enable "Regular expression"
  • Disable ". matches newline"

The given regular expression matches both Windows and Unix end of lines.

If your text contains characters that have a special meaning for regular expression, like the backslash, you will need to escape them.

How can I delete a query string parameter in JavaScript?

You can change the URL with:

window.history.pushState({}, document.title, window.location.pathname);

this way, you can overwrite the URL without the search parameter, I use it to clean the URL after take the GET parameters.

How does strcmp() work?

Here is the BSD implementation:

int
strcmp(s1, s2)
    register const char *s1, *s2;
{
    while (*s1 == *s2++)
        if (*s1++ == 0)
            return (0);
    return (*(const unsigned char *)s1 - *(const unsigned char *)(s2 - 1));
}

Once there is a mismatch between two characters, it just returns the difference between those two characters.

Node.js Error: connect ECONNREFUSED

The Unhandled 'error' event is referring not providing a function to the request to pass errors. Without this event the node process ends with the error instead of failing gracefully and providing actual feedback. You can set the event just before the request.write line to catch any issues:

request.on('error', function(err)
{
    console.log(err);
});

More examples below:

https://nodejs.org/api/http.html#http_http_request_options_callback

What's the most concise way to read query parameters in AngularJS?

You can inject $routeParams (requires ngRoute) into your controller. Here's an example from the docs:

// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}

EDIT: You can also get and set query parameters with the $location service (available in ng), particularly its search method: $location.search().

$routeParams are less useful after the controller's initial load; $location.search() can be called anytime.

Import SQL file by command line in Windows 7

To import database from dump file use:

mysql -u UserName -p Password DatabaseName < FileName.sql 

In wamp

C:\wamp\bin\mysql\mysql5.0.51b\bin>mysql mysql -uroot -p DatabaseName < FileName.sql 

Override intranet compatibility mode IE8

Try this metatag:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

It should force IE8 to render as IE8 Standard Mode even if "Display intranet sites in compatibility view" is checked [either for intranet or all websites],I tried it my self on IE 8.0.6

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

I had the same error and struggled to fix it, then answer above by Nagaraja JB helped me to fix it. In my case:

Was before: JSONObject response_json = new JSONObject(response_data);

Changed it to: JSONArray response_json = new JSONArray(response_data);

This fixed it.

Exec : display stdout "live"

exec will also return a ChildProcess object that is an EventEmitter.

var exec = require('child_process').exec;
var coffeeProcess = exec('coffee -cw my_file.coffee');

coffeeProcess.stdout.on('data', function(data) {
    console.log(data); 
});

OR pipe the child process's stdout to the main stdout.

coffeeProcess.stdout.pipe(process.stdout);

OR inherit stdio using spawn

spawn('coffee -cw my_file.coffee', { stdio: 'inherit' });

How to resolve symbolic links in a shell script

Try this:

cd $(dirname $([ -L $0 ] && readlink -f $0 || echo $0))

Recording video feed from an IP camera over a network

about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.

Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.

So i found the solution!

If you want something done right, do it yourself.

I present to you Shinobi! Shinobi : The Open Source CCTV Platform

enter image description here

Best cross-browser method to capture CTRL+S with JQuery?

To Alan Bellows answer: !(e.altKey) added for users who use AltGr when typing (e.g Poland). Without this pressing AltGr+S will give same result as Ctrl+S

$(document).keydown(function(e) {
if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
    e.preventDefault();
    alert("Ctrl-s pressed");
    return false;
}
return true; });

Delete empty lines using sed

Another option without sed, awk, perl, etc

strings $file > $output

strings - print the strings of printable characters in files.

JavaScript for handling Tab Key press

try this

 <body>
   <div class="linkCollection">
             <a tabindex=1 href="www.demo1.com">link</a>    
             <a tabindex=2 href="www.demo2.com">link</a>    
             <a tabindex=3 href="www.demo3.com">link</a>    
             <a tabindex=4 href="www.demo4.com">link</a>    
             <a tabindex=5 href="www.demo5.com">link</a>    
             <a tabindex=6 href="www.demo6.com">link</a>    
             <a tabindex=7 href="www.demo7.com">link</a>    
             <a tabindex=8 href="www.demo8.com">link</a>    
             <a tabindex=9 href="www.demo9.com">link</a>    
             <a tabindex=10 href="www.demo10.com">link</a>   
        </div>

</body>

<script>
$(document).ready(function(){
  $(".linkCollection a").focus(function(){
    var href=$(this).attr('href');
    console.log(href);
    // href variable holds the active selected link.
  });
});
</script>

don't forgot to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

Setting different color for each series in scatter plot on matplotlib

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

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


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

plt.close('all')

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

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

plt.show()

Add a property to a JavaScript object using a variable as the name?

You can even make List of objects like this

var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
    var feeType = {};

    var $ID = $(this).find("input[id^=txtFeeType]").attr('id');

    feeType["feeTypeID"] = $('#ddlTerm').val();
    feeType["feeTypeName"] = $('#ddlProgram').val();
    feeType["feeTypeDescription"] = $('#ddlBatch').val();

    feeTypeList.push(feeType);
});

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

mysql data directory location

If you install MySQL via homebrew on MacOS, you might need to delete your old data directory /usr/local/var/mysql. Otherwise, it will fail during the initialization process with the following error:

==> /usr/local/Cellar/mysql/8.0.16/bin/mysqld --initialize-insecure --user=hohoho --basedir=/usr/local/Cellar/mysql/8.0.16 --datadir=/usr/local/var/mysql --tmpdir=/tmp
2019-07-17T16:30:51.828887Z 0 [System] [MY-013169] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld (mysqld 8.0.16) initializing of server in progress as process 93487
2019-07-17T16:30:51.830375Z 0 [ERROR] [MY-010457] [Server] --initialize specified but the data directory has files in it. Aborting.
2019-07-17T16:30:51.830381Z 0 [ERROR] [MY-013236] [Server] Newly created data directory /usr/local/var/mysql/ is unusable. You can safely remove it.
2019-07-17T16:30:51.830410Z 0 [ERROR] [MY-010119] [Server] Aborting
2019-07-17T16:30:51.830540Z 0 [System] [MY-010910] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld: Shutdown complete (mysqld 8.0.16)  Homebrew.

What is `related_name` used for in Django?

The related name parameter is actually an option. If we do not set it, Django automatically creates the other side of the relation for us. In the case of the Map model, Django would have created a map_set attribute, allowing access via m.map_set in your example(m being your class instance). The formula Django uses is the name of the model followed by the string _set. The related name parameter thus simply overrides Django’s default rather than providing new behavior.

Return the most recent record from ElasticSearch index

If you are using python elasticsearch5 module or curl:

  1. make sure each document that gets inserted has
    • a timestamp field that is type datetime
    • and you are monotonically increasing the timestamp value for each document
  2. from python you do

    es = elasticsearch5.Elasticsearch('my_host:my_port')
    es.search(
        index='my_index', 
        size=1,
        sort='my_timestamp:desc'
        )
    

If your documents are not inserted with any field that is of type datetime, then I don't believe you can get the N "most recent".

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

findAll() in yii

This is your safest way to do it:

$id =101;
//$user_id=25;
$criteria=new CDbCriteria;
$criteria->condition="email_id < :email_id";
//$criteria->addCondition("user_id=:user_id");
$criteria->params=array(
  ':email_id' => $id,
  //':user_id' => $user_id,
);
$comments=EmailArchive::model()->findAll($criteria);

Note that if you comment out the commented lines you get a way to add more filtering to your search.

After this it is recommend to check if there is any data returned like:

if (isset($comments)) { // We found some comments, we can sleep well tonight
  // do comments process or whatever
}

How to convert an OrderedDict into a regular dict in python3

If you are looking for a recursive version without using the json module:

def ordereddict_to_dict(value):
    for k, v in value.items():
        if isinstance(v, dict):
            value[k] = ordereddict_to_dict(v)
    return dict(value)

GSON - Date format

It seems that you need to define formats for both date and time part or use String-based formatting. For example:

Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();

or using java.text.DateFormat

Gson gson = new GsonBuilder()
   .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();

or do it with serializers:

I believe that formatters cannot produce timestamps, but this serializer/deserializer-pair seems to work

JsonSerializer<Date> ser = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext 
             context) {
    return src == null ? null : new JsonPrimitive(src.getTime());
  }
};

JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
  @Override
  public Date deserialize(JsonElement json, Type typeOfT,
       JsonDeserializationContext context) throws JsonParseException {
    return json == null ? null : new Date(json.getAsLong());
  }
};

Gson gson = new GsonBuilder()
   .registerTypeAdapter(Date.class, ser)
   .registerTypeAdapter(Date.class, deser).create();

If using Java 8 or above you should use the above serializers/deserializers like so:

JsonSerializer<Date> ser = (src, typeOfSrc, context) -> src == null ? null
            : new JsonPrimitive(src.getTime());

JsonDeserializer<Date> deser = (jSon, typeOfT, context) -> jSon == null ? null : new Date(jSon.getAsLong());

The transaction manager has disabled its support for remote/network transactions

Make sure that the "Distributed Transaction Coordinator" Service is running on both database and client. Also make sure you check "Network DTC Access", "Allow Remote Client", "Allow Inbound/Outbound" and "Enable TIP".

To enable Network DTC Access for MS DTC transactions

  1. Open the Component Services snap-in.

    To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER.

  2. Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access.

  3. On the Action menu, click Properties.

  4. Click the Security tab and make the following changes: In Security Settings, select the Network DTC Access check box.

    In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes.

How to combine two lists in R

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

Rename a table in MySQL

group is a keyword (part of GROUP BY) in MySQL, you need to surround it with backticks to show MySQL that you want it interpreted as a table name:

RENAME TABLE `group` TO `member`;

added(see comments)- Those are not single quotes.

Android Debug Bridge (adb) device - no permissions

I'll prepend this postscript here at the top so it won't get lost in my earlier explanation.

I can reliably produce and resolve the no-permissions problem by simply changing the USB connection type from Camera (PTP) to Media device (MTP). The camera mode allows debugging; the media mode causes the no-permissions response in ADB.

The reasoning seems pretty evident after reflecting on that for a moment. Unsecured content on the device would be made accessible by the debugger in media server mode.

===========

The device is unpermissioned until you accept the RSA encryption warning on the debugged device. At some point after connecting, the device will ask to accept the debugging connection. It's a minimal security protocol that ensures you can access the device beyond the initial swipe lock. Developer mode needs to be enabled, I believe.

The "no permissions" flag is actually a good first indicator that adb recognizes the device as a valid debugging target. Notice that it doesn't list your other USB devices.

Details at the following and related pages.

http://developer.android.com/tools/device.html

Command line input in Python

It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:

For interactive user input (or piped commands or redirected input)

Use raw_input in Python 2.x, and input in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)

For example:

user_input = raw_input("Some input please: ")

More details can be found here.

So, for example, you might have a script that looks like this

# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)

# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3

# Now do something with the above
print(user_input)

If you saved this in foo.py, you could just call the script from the command line, it would print out tok tiktok, then ask you for input. You could enter bar baz (followed by the enter key) and it would print bar baz. Here's what that would look like:

$ python foo.py
tok tiktok
Some input please: bar baz
bar baz

Here, $ represents the command-line prompt (so you don't actually type that), and I hit Enter after typing bar baz when it asked for input.

For command-line arguments

Suppose you have a script named foo.py and want to call it with arguments bar and baz from the command line like

$ foo.py bar baz

(Again, $ represents the command-line prompt.) Then, you can do that with the following in your script:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]

Here, the variable arg1 will contain the string 'bar', and arg2 will contain 'baz'. The object sys.argv is just a list containing everything from the command line. Note that sys.argv[0] is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:].

merge one local branch into another local branch

To merge one branch into another, such as merging "feature_x" branch into "master" branch:

git checkout master

git merge feature_x

This page is the first result for several search engines when looking for "git merge one branch into another". However, the original question is more specific and special case than the title would suggest.
It is also more complex than both the subject and the search expression. As such, this is a minimal but explanatory answer for the benefit of most visitors.

What's the difference between Unicode and UTF-8?

There's a lot of misunderstanding being displayed here. Unicode isn't an encoding, but the Unicode standard is devoted primarily to encoding anyway.

ISO 10646 is the international character set you (probably) care about. It defines a mapping between a set of named characters (e.g., "Latin Capital Letter A" or "Greek small letter alpha") and a set of code points (a number assigned to each -- for example, 61 hexadecimal and 3B1 hexadecimal for those two respectively; for Unicode code points, the standard notation would be U+0061 and U+03B1).

At one time, Unicode defined its own character set, more or less as a competitor to ISO 10646. That was a 16-bit character set, but it was not UTF-16; it was known as UCS-2. It included a rather controversial technique to try to keep the number of necessary characters to a minimum (Han Unification -- basically treating Chinese, Japanese and Korean characters that were quite a bit alike as being the same character).

Since then, the Unicode consortium has tacitly admitted that that wasn't going to work, and now concentrate primarily on ways to encode the ISO 10646 character set. The primary methods are UTF-8, UTF-16 and UCS-4 (aka UTF-32). Those (except for UTF-8) also have LE (little endian) and BE (big-endian) variants.

By itself, "Unicode" could refer to almost any of the above (though we can probably eliminate the others that it shows explicitly, such as UTF-8). Unqualified use of "Unicode" probably happens the most often on Windows, where it will almost certainly refer to UTF-16. Early versions of Windows NT adopted Unicode when UCS-2 was current. After UCS-2 was declared obsolete (around Win2k, if memory serves), they switched to UTF-16, which is the most similar to UCS-2 (in fact, it's identical for characters in the "basic multilingual plane", which covers a lot, including all the characters for most Western European languages).

Chart.js v2 hide dataset labels

It's just as simple as adding this: legend: { display: false, }

// Or if you want you could use this other option which should also work:

Chart.defaults.global.legend.display = false;

Can a CSV file have a comment?

I think the best way to add comments to a CSV file would be to add a "Comments" field or record right into the data.

Most CSV-parsing applications that I've used implement both field-mapping and record-choosing. So, to comment on the properties of a field, add a record just for field descriptions. To comment on a record, add a field at the end of it (well, all records, really) just for comments.

These are the only two reasons I can think of to comment a CSV file. But the only problem I can foresee would be programs that refuse to accept the file at all if any single record doesn't pass some validation rules. In that case, you'd have trouble writing a string-type field description record for any numeric fields.

I am by no means an expert, though, so feel free to point out any mistakes in my theory.

How to get current class name including package name in Java?

There is a class, Class, that can do this:

Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass();          // if you want to use the current class

System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());

If c represented the class MyClass in the package mypackage, the above code would print:

Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass

You can take this information and modify it for whatever you need, or go check the API for more information.

Python: Continuing to next iteration in outer loop

We want to find something and then stop the inner iteration. I use a flag system.

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

How to set the component size with GridLayout? Is there a better way?

An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.

How to sync with a remote Git repository?

Assuming their updates are on master, and you are on the branch you want to merge the changes into.

git remote add origin https://github.com/<github-username>/<repo-name>.git
git pull origin master

Also note that you will then want to push the merge back to your copy of the repository:

git push origin master

Sniff HTTP packets for GET and POST requests from an application

You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.

Flutter does not find android sdk

Deleting and reinstalling Android Studio fixes the issue with the SDK.

Getting A File's Mime Type In Java

I was just wondering how most people fetch a mime type from a file in Java?

I've published my SimpleMagic Java package which allows content-type (mime-type) determination from files and byte arrays. It is designed to read and run the Unix file(1) command magic files that are a part of most ~Unix OS configurations.

I tried Apache Tika but it is huge with tons of dependencies, URLConnection doesn't use the bytes of the files, and MimetypesFileTypeMap also just looks at files names.

With SimpleMagic you can do something like:

// create a magic utility using the internal magic file
ContentInfoUtil util = new ContentInfoUtil();
// if you want to use a different config file(s), you can load them by hand:
// ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
...
ContentInfo info = util.findMatch("/tmp/upload.tmp");
// or
ContentInfo info = util.findMatch(inputStream);
// or
ContentInfo info = util.findMatch(contentByteArray);

// null if no match
if (info != null) {
   String mimeType = info.getMimeType();
}

Create a new database with MySQL Workbench

first, you have to create Models. default model is sakila, so you have to create one. if you already created the new one, go to Database > Forward Engineer. then, your model will exist in local instance:80

Forward engineer is to create database in your choosed host!

Is there an alternative sleep function in C to milliseconds?

Alternatively to usleep(), which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep():

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

Disable sorting for a particular column in jQuery DataTables

"aoColumnDefs" : [   
{
  'bSortable' : false,  
  'aTargets' : [ 0 ]
}]

Here 0 is the index of the column, if you want multiple columns to be not sorted, mention column index values seperated by comma(,)

Return the characters after Nth character in a string

Mid(strYourString, 4) (i.e. without the optional length argument) will return the substring starting from the 4th character and going to the end of the string.

UIScrollView Scrollable Content Size Ambiguity

Using Autolayout

Add your scroll view inside a well defined view and then add the stack view inside the scroll view

Add top, left, right, bottom, center X and center Y constraints from scroll view and stack view to their relevant super views

Make sure that constraints are linked from stack view to the rightful superview (scrollview) since current default setting is to add an Align Top constraint and not a Top Space one.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

SQLite add Primary Key

You can do it like this:

CREATE TABLE mytable (
field1 text,
field2 text,
field3 integer,
PRIMARY KEY (field1, field2)
);

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

How to import CSV file data into a PostgreSQL table?

Take a look at this short article.


Solution paraphrased here:

Create your table:

CREATE TABLE zip_codes 
(ZIP char(5), LATITUDE double precision, LONGITUDE double precision, 
CITY varchar, STATE char(2), COUNTY varchar, ZIP_CLASS varchar);

Copy data from your CSV file to the table:

COPY zip_codes FROM '/path/to/csv/ZIP_CODES.txt' WITH (FORMAT csv);

Change a column type from Date to DateTime during ROR migration

First in your terminal:

rails g migration change_date_format_in_my_table

Then in your migration file:

For Rails >= 3.2:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
    change_column :my_table, :my_column, :datetime
  end

  def down
    change_column :my_table, :my_column, :date
  end
end

How to construct a set out of list items in python?

One general way to construct set in iterative way like this:

aset = {e for e in alist}

c# dictionary How to add multiple values for single key?

You could use my implementation of a multimap, which derives from a Dictionary<K, List<V>>. It is not perfect, however it does a good job.

/// <summary>
/// Represents a collection of keys and values.
/// Multiple values can have the same key.
/// </summary>
/// <typeparam name="TKey">Type of the keys.</typeparam>
/// <typeparam name="TValue">Type of the values.</typeparam>
public class MultiMap<TKey, TValue> : Dictionary<TKey, List<TValue>>
{

    public MultiMap()
        : base()
    {
    }

    public MultiMap(int capacity)
        : base(capacity)
    {
    }

    /// <summary>
    /// Adds an element with the specified key and value into the MultiMap. 
    /// </summary>
    /// <param name="key">The key of the element to add.</param>
    /// <param name="value">The value of the element to add.</param>
    public void Add(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            valueList.Add(value);
        } else {
            valueList = new List<TValue>();
            valueList.Add(value);
            Add(key, valueList);
        }
    }

    /// <summary>
    /// Removes first occurence of an element with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the element to remove.</param>
    /// <param name="value">The value of the element to remove.</param>
    /// <returns>true if the an element is removed;
    /// false if the key or the value were not found.</returns>
    public bool Remove(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            if (valueList.Remove(value)) {
                if (valueList.Count == 0) {
                    Remove(key);
                }
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// Removes all occurences of elements with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the elements to remove.</param>
    /// <param name="value">The value of the elements to remove.</param>
    /// <returns>Number of elements removed.</returns>
    public int RemoveAll(TKey key, TValue value)
    {
        List<TValue> valueList;
        int n = 0;

        if (TryGetValue(key, out valueList)) {
            while (valueList.Remove(value)) {
                n++;
            }
            if (valueList.Count == 0) {
                Remove(key);
            }
        }
        return n;
    }

    /// <summary>
    /// Gets the total number of values contained in the MultiMap.
    /// </summary>
    public int CountAll
    {
        get
        {
            int n = 0;

            foreach (List<TValue> valueList in Values) {
                n += valueList.Count;
            }
            return n;
        }
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific
    /// key / value pair.
    /// </summary>
    /// <param name="key">Key of the element to search for.</param>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            return valueList.Contains(value);
        }
        return false;
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific value.
    /// </summary>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TValue value)
    {
        foreach (List<TValue> valueList in Values) {
            if (valueList.Contains(value)) {
                return true;
            }
        }
        return false;
    }

}

Note that the Add method looks if a key is already present. If the key is new, a new list is created, the value is added to the list and the list is added to the dictionary. If the key was already present, the new value is added to the existing list.

How to add new elements to an array?

String[] source = new String[] { "a", "b", "c", "d" };
String[] destination = new String[source.length + 2];
destination[0] = "/bin/sh";
destination[1] = "-c";
System.arraycopy(source, 0, destination, 2, source.length);

for (String parts : destination) {
  System.out.println(parts);
}

Custom CSS for <audio> tag?

Besides the box-shadow, transform and border options mentioned in other answers, WebKit browsers currently also obey -webkit-text-fill-color to set the colour of the "time elapsed" numbers, but since there is no way to set their background (which might vary with platform, e.g. inverted high-contrast modes on some operating systems), you would be advised to set -webkit-text-fill-color to the value "initial" if you've used it elsewhere and the audio element is inheriting this, otherwise some users might find those numbers unreadable.

Visual Studio Code Tab Key does not insert a tab

Click on the explorer or any other window that is not the editor then press Ctrl + Shift (for Mac only) + M, this is the command to "Toggle Tab Key Moves Focus" on the Keyboard Shortcuts.

How to generate random float number in C

This generates a random float between two floats.

float RandomFloat(float min, float max){
   return ((max - min) * ((float)rand() / RAND_MAX)) + min;
}

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Got to this answer ? probably the answers above are to long ...

just type in :

echo "setenv M2_HOME $M2_HOME" | sudo tee -a /etc/launchd.conf

and restart your mac (thats it!)

restarting is annoying ? just use the command :

grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl

and restart IntelliJ IDEA

MySQL query to get column names?

i no expert, but this works for me..

$sql = "desc MyTable";
$result = @mysql_query($sql);
while($row = @mysql_fetch_array($result)){
    echo $row[0]."<br>"; // returns the first column of array. in this case Field

      // the below code will return a full array-> Field,Type,Null,Key,Default,Extra    
      // for ($c=0;$c<sizeof($row);$c++){echo @$row[$c]."<br>";}    

}

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

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

const readFiles = (dirname) => {

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

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

readFiles(sourceFolder)
  .then( allContents => {

    // handle success treatment

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

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

I would also like to point out that you can use a javascript approach, window.history.replaceState to prevent a resubmit on refresh and back button.

<script>
    if ( window.history.replaceState ) {
        window.history.replaceState( null, null, window.location.href );
    }
</script>

Proof of concept here: https://dtbaker.net/files/prevent-post-resubmit.php

I would still recommend a Post/Redirect/Get approach, but this is a novel JS solution.

Working with Enums in android

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

display: flex not working on Internet Explorer

Internet Explorer doesn't fully support Flexbox due to:

Partial support is due to large amount of bugs present (see known issues).

enter image description here Screenshot and infos taken from caniuse.com

Notes

Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.

Known issues

  • IE 11 requires a unit to be added to the third argument, the flex-basis property see MSFT documentation.
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property. See bug.
  • In IE10 the default value for flex is 0 0 auto rather than 0 1 auto as defined in the latest spec.
  • IE 11 does not vertically align items correctly when min-height is used. See bug.

Workarounds

Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.

  1. Minimum content sizing of flex items not honored
  2. Column flex items set to align-items: center overflow their container
  3. min-height on a flex container won't apply to its flex items
  4. flex shorthand declarations with unitless flex-basis values are ignored
  5. Column flex items don't always preserve intrinsic aspect ratios
  6. The default flex value has changed
  7. flex-basis doesn't account for box-sizing: border-box
  8. flex-basis doesn't support calc()
  9. Some HTML elements can't be flex containers
  10. align-items: baseline doesn't work with nested flex containers
  11. Min and max size declarations are ignored when wrapping flex items
  12. Inline elements are not treated as flex-items
  13. Importance is ignored on flex-basis when using flex shorthand
  14. Shrink-to-fit containers with flex-flow: column wrap do not contain their items
  15. Column flex items ignore margin: auto on the cross axis
  16. flex-basis cannot be animated
  17. Flex items are not correctly justified when max-width is used

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

How do you use the ? : (conditional) operator in JavaScript?

This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.

  // var firstName = 'John'; // Undefined
  var lastName = 'Doe';

  // if lastName or firstName is undefined, false, null or empty => fallback to empty string
  lastName = lastName || '';
  firstName = firstName || '';

  var displayName = '';

  // if lastName (or firstName) is undefined, false, null or empty
  // displayName equals 'John' OR 'Doe'

  // if lastName and firstName are not empty
  // a space is inserted between the names
  displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;


  // if display name is undefined, false, null or empty => fallback to 'Unnamed'
  displayName = displayName || 'Unnamed';

  console.log(displayName);

Ternary Operator

What is FCM token in Firebase?

What is it exactly?

An FCM Token, or much commonly known as a registrationToken like in . As described in the GCM FCM docs:

An ID issued by the GCM connection servers to the client app that allows it to receive messages. Note that registration tokens must be kept secret.


How can I get that token?

Update: The token can still be retrieved by calling getToken(), however, as per FCM's latest version, the FirebaseInstanceIdService.onTokenRefresh() has been replaced with FirebaseMessagingService.onNewToken() -- which in my experience functions the same way as onTokenRefresh() did.


Old answer:

As per the FCM docs:

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token.

You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. FirebaseInstanceID.getToken() returns null if the token has not yet been generated.

After you've obtained the token, you can send it to your app server and store it using your preferred method. See the Instance ID API reference for full detail on the API.

How to change python version in anaconda spyder

If you are using anaconda to go into python environment you should have build up different environment for different python version

The following scripts may help you build up a new environment(running in anaconda prompt)

conda create -n py27 python=2.7  #for version 2.7
activate py27

conda create -n py36 python=3.6  #for version 3.6
activate py36

you may leave the environment back to your global env by typing
deactivate py27 
or 
deactivate py36 

and then you can either switch to different environment using your anaconda UI with @Francisco Camargo 's answer

or you can stick to anaconda prompt using @Dan 's answer

how to reference a YAML "setting" from elsewhere in the same YAML file?

Yes, using custom tags. Example in Python, making the !join tag join strings in an array:

import yaml

## define custom tag handler
def join(loader, node):
    seq = loader.construct_sequence(node)
    return ''.join([str(i) for i in seq])

## register the tag handler
yaml.add_constructor('!join', join)

## using your sample data
yaml.load("""
paths:
    root: &BASE /path/to/root/
    patha: !join [*BASE, a]
    pathb: !join [*BASE, b]
    pathc: !join [*BASE, c]
""")

Which results in:

{
    'paths': {
        'patha': '/path/to/root/a',
        'pathb': '/path/to/root/b',
        'pathc': '/path/to/root/c',
        'root': '/path/to/root/'
     }
}

The array of arguments to !join can have any number of elements of any data type, as long as they can be converted to string, so !join [*a, "/", *b, "/", *c] does what you would expect.

C# declare empty string array

Try this

string[] arr = new string[] {};

Write a file on iOS

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

NSLog(@"%@",documentsDirectory);

and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

Why is Ant giving me a Unsupported major.minor version error

In my case, the project was a Maven, I had JDK 1.8.0, Eclipse : Kepler, and I installed the M2Eclipse plugin from Eclipse Marketplace.

Changing compiler level didn't help.

Finally I used latest version of eclipse (Luna), compiler level 1.7, same M2Eclipse plugin and problem was solved.

CSS to select/style first word

Same thing, with jQuery:

$('#links a').each(function(){
    var me = $(this);
    me.html( me.text().replace(/(^\w+)/,'<strong>$1</strong>') );
  });

or

$('#links a').each(function(){
    var me = $(this)
       , t = me.text().split(' ');
    me.html( '<strong>'+t.shift()+'</strong> '+t.join(' ') );
  });

(Via 'Wizzud' on the jQuery Mailing List)

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

Try to disable SELinux by this command /usr/sbin/setenforce 0. In my case it solved the problem.

Split text with '\r\n'

This worked for me.

using System.IO;

//  

    string readStr = File.ReadAllText(file.FullName);          
    string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);

How do I make a textbox that only accepts numbers?

I had created a Re-Usable Textbox Extension class for all sorts of validations and thought about sharing it.

All you need to do is raise a TextChange event and then call the Validate method. It looks like this:

private void tbxAmount_TextChanged(object sender, EventArgs e)
{ 
    tbxAmount.Validate(TextValidator.ValidationType.Amount);
}

Here is the extension class:

public static class TextValidator
{
    public enum ValidationType
    {
        Amount,
        Integer
    }

    /// <summary>
    /// Validate a textbox on text change.
    /// </summary>
    /// <param name="tbx"></param>
    /// <param name="validationType"></param>
    public static void Validate(this TextBox tbx, ValidationType validationType)
    {
        PerformValidation(tbx, validationType);
        tbx.Select(tbx.Text.Length, 0);
    }


    private static void PerformValidation(this TextBox tbx, ValidationType validationType)
    {
        char[] enteredString = tbx.Text.ToCharArray();
        switch (validationType)
        {
            case ValidationType.Amount:
                tbx.Text = AmountValidation(enteredString);
                break;

            case ValidationType.Integer:
                tbx.Text = IntegerValidation(enteredString);
                break;

            default:
                break;
        }

        tbx.SelectionStart = tbx.Text.Length;
    }



    private static string AmountValidation(char[] enteredString)
    {
        string actualString = string.Empty;
        int count = 0;
        foreach (char c in enteredString.AsEnumerable())
        {
            if (count >= 1 && c == '.')
            { actualString.Replace(c, ' '); actualString.Trim(); }
            else
            {
                if (Char.IsDigit(c))
                {
                    actualString = actualString + c;
                }

                if (c == '.')
                {
                    actualString = actualString + c; count++;
                }

                else
                {
                    actualString.Replace(c, ' ');
                    actualString.Trim();
                }
            }
        }
        return actualString;
    }


    private static string IntegerValidation(char[] enteredString)
    {
        string actualString = string.Empty;
        foreach (char c in enteredString.AsEnumerable())
        {
            if (Char.IsDigit(c))
            {
                actualString = actualString + c;
            }
            else
            {
                actualString.Replace(c, ' ');
                actualString.Trim();
            }
        }
        return actualString;
    }
}

You can find the full code here

How to perform update operations on columns of type JSONB in Postgres 9.4

Maybe: UPDATE test SET data = '"my-other-name"'::json WHERE id = 1;

It worked with my case, where data is a json type