Programs & Examples On #Osx snow leopard

Mac OS X Snow Leopard (10.6) is the seventh major release of Mac OS X, Apple's desktop and server operating system for Macintosh computers.

Check mySQL version on Mac 10.8.5

To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:

./mysql --version

Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.

After adding the mysql bin dir to your $PATH, verify it's there by executing:

echo $PATH

Thereafter you can check your mysql version from anywhere by running (note no "./"):

mysql --version

PostgreSQL error 'Could not connect to server: No such file or directory'

If you are running Homebrew, uninstall Postgresql end pg gems:*

$ gem uninstall pg
$ brew uninstall postgresql

Download and run the following script to fix permission on /usr/local:* https://gist.github.com/rpavlik/768518

$ ruby fix_homebrew.rb

Then install Postgres again and pg gem:*

$ brew install postgresql  
$ initdb /usr/local/var/postgres -E utf8

To have launchd start postgresql at login run:

$ ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents 

Or start manually.

Install pg gem

$ gem install pg

I hope have helped

can't start MySql in Mac OS 10.6 Snow Leopard

Have you considered installing MacPorts 1.8.0 (release candidate), and keeping MySQL up-to-date that way? That will build MySQL for the architecture and OS that you're using, rather than installing a 10.5 version on 10.6.

Eclipse hangs on loading workbench

The procedure shown at http://off-topic.biz/en/eclipse-hangs-at-startup-showing-only-the-splash-screen/ worked for me:

  1. cd .metadata/.plugins
  2. mv org.eclipse.core.resources org.eclipse.core.resources.bak
  3. Start eclipse. (It should show an error message or an empty workspace because no project is found.)
  4. Close all open editors tabs.
  5. Exit eclipse.
  6. rm -rf org.eclipse.core.resources (Delete the newly created directory.)
  7. mv org.eclipse.core.resources.bak/ org.eclipse.core.resources (Restore the original directory.)
  8. Start eclipse and start working. :-)

In other answers:

eclipse -clean -clearPersistedState

is mentioned - which seems to have the same or even better effect.

Here is a script for MacOS (using Macports) and Linux (tested on Ubuntu with Eclipse Equinox) to do the start with an an optional kill of the running eclipse. You might want to adapt the script to your needs. If you add new platforms please edit the script right in this answer.

#!/bin/bash
# WF 2014-03-14
#
# ceclipse:
#   start Eclipse cleanly
#
#   this script calls eclipse with -clean and -clearPersistedState
#   if an instance of eclipse is already running the user is asked
#   if it should be killed first and if answered yes the process will be killed
#
# usage: ceclipse
#

#
# error
#
#   show an error message and exit
#
#   params:
#     1: l_msg - the message to display
error() {
  local l_msg="$1"
  echo "error: $l_msg" 1>&2
  exit 1 
}

#
# autoinstall
#
#  check that l_prog is available by calling which
#  if not available install from given package depending on Operating system
#
#  params: 
#    1: l_prog: The program that shall be checked
#    2: l_linuxpackage: The apt-package to install from
#    3: l_macospackage: The MacPorts package to install from
#
autoinstall() {
  local l_prog=$1
  local l_linuxpackage=$2
  local l_macospackage=$3
  echo "checking that $l_prog  is installed on os $os ..."
  which $l_prog 
  if [ $? -eq 1 ]
  then
    case $os in 
      # Mac OS
      Darwin) 
        echo "installing $l_prog from MacPorts package $l_macospackage"        
        sudo port install $l_macospackage
      ;;
      # e.g. Ubuntu/Fedora/Debian/Suse
      Linux)
        echo "installing $l_prog from apt-package $l_linuxpackage"        
        sudo apt-get install $l_linuxpackage
      ;;
      # git bash (Windows)
      MINGW32_NT-6.1)
        error "$l_prog ist not installed"
      ;;
      *)
        error "unknown operating system $os" 
    esac
  fi
}

# global operating system variable
os=`uname`

# first set 
#  eclipse_proc - the name of the eclipse process to look for
#  eclipse_app - the name of the eclipse application to start
case $os in 
    # Mac OS
    Darwin) 
      eclipse_proc="Eclipse.app" 
      eclipse_app="/Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse"
      ;;
    # e.g. Ubuntu/Fedora/Debian/Suse
    Linux)
      eclipse_proc="/usr/lib/eclipse//plugins/org.eclipse.equinox.launcher_1.2.0.dist.jar"
      eclipse_app=`which eclipse`
      ;;
    # git bash (Windows)
    MINGW32_NT-6.1)
      eclipse_app=`which eclipse`
      error "$os not implemented yet"
      ;;
    *)
      error "unknown operating system $os" 
esac

# check that pgrep is installed or install it
autoinstall pgrep procps

# check whether eclipse process is running
# first check that we only find one process
echo "looking for $eclipse_proc process"
pgrep -fl "$eclipse_proc"
# can't use -c option on MacOS - use platform independent approach 
#eclipse_count=`pgrep -cfl "$eclipse_proc"`
eclipse_count=`pgrep -fl "$eclipse_proc" | wc -l | tr -d ' '`

# check how many processes matched
case $eclipse_count in
  # no eclipse - do nothing
  0) ;;
  # exactly one - offer to kill it
  1) 
     echo "Eclipse is running - shall i kill and restart it with -clean? y/n?"
       read answer
       case $answer in
         y|Y) ;;
           *) error "aborted ..." ;;
       esac
     echo "killing current $eclipse_proc"
     pkill -f "$eclipse_proc"
     ;;
  # multiple - this is bogus
  *) error "$eclipse_count processes matching $eclipse_proc found - please adapt $0";;
esac

tmp=/tmp/eclipse$$
echo "starting eclipse cleanly ... using $tmp for nohup.out"
mkdir -p $tmp
cd $tmp

# start eclipse with clean options
nohup $eclipse_app -clean -clearPersistedState&

How do you uninstall MySQL from Mac OS X?

For me, I had installed MariaDB years ago using homebrew. Correct uninstall procedure was: brew uninstall mariadb.

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

Authorize a non-admin developer in Xcode / Mac OS

You need to add your macOS user name to the _developer group. See the posts in this thread for more information. The following command should do the trick:

sudo dscl . append /Groups/_developer GroupMembership <username>

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

To complete your setup or MySQL:

sudo vim /etc/profile
  1. Add alias

    alias mysql=/usr/local/mysql/bin/mysql
    alias mysqladmin=/usr/local/mysql/bin/mysqladmin
    
  2. Then set your root password

    mysqladmin -u root password 'yourPassword'
    
  3. Then you can login with

    mysql -u root -p
    

Pandas: Subtracting two date columns and the result being an integer

Create a vectorized method

def calc_xb_minus_xa(df):
    time_dict = {
        '<Minute>': 'm',
        '<Hour>': 'h',
        '<Day>': 'D',
        '<Week>': 'W',
        '<Month>': 'M',
        '<Year>': 'Y'
    }

    time_delta = df.at[df.index[0], 'end_time'] - df.at[df.index[0], 'open_time']
    offset_base_name = str(to_offset(time_delta).base)
    time_term = time_dict.get(offset_base_name)

    result = (df.end_time - df.open_time) / np.timedelta64(1, time_term)
    return result

Then in your df do:

df['x'] = calc_xb_minus_xa(df)

This will work for minutes, hours, days, weeks, month and Year. open_time and end_time need to change according your df

How to run an .ipynb Jupyter Notebook from terminal?

You can export all your code from .ipynb and save it as a .py script. Then you can run the script in your terminal.

code export sample

Hope it helps.

String compare in Perl with "eq" vs "=="

Did you try to chomp the $str1 and $str2?

I found a similar issue with using (another) $str1 eq 'Y' and it only went away when I first did:

chomp($str1);
if ($str1 eq 'Y') {
....
}

works after that.

Hope that helps.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

Since ASP.NET MVC 3 RTM is out there is no need for config section for Razor. And these sections can be safely removed.

How to exit from ForEach-Object in PowerShell

You have two options to abruptly exit out of ForEach-Object pipeline in PowerShell:

  1. Apply exit logic in Where-Object first, then pass objects to Foreach-Object, or
  2. (where possible) convert Foreach-Object into a standard Foreach looping construct.

Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":

Solution-1: use Where-Object filter BEFORE Foreach-Object:

[boolean]$exit = $false;
1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
     if($_ -eq 2) {$exit = $true}    #OR $exit = ($_ -eq 2);
     $_;
}

OR

1..10 | Where-Object {$_ -le 2} | Foreach-Object {
     $_;
}

Solution-2: Converted Foreach-Object into standard Foreach looping construct:

Foreach ($i in 1..10) { 
     if ($i -eq 3) {break;}
     $i;
}

PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object pipeline. Note: return doesn't exit, it only skips specific iteration (similar to continue in most programming languages), here is an example of return:

Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
1..10 | Foreach-Object {
     if ($_ -eq 3) {return;}  #skips only 3rd iteration.
     $_;
}

HTH

How to Store Historical Data

Just wanted to add an option that I started using because I use Azure SQL and the multiple table thing was way too cumbersome for me. I added an insert/update/delete trigger on my table and then converted the before/after change to json using the "FOR JSON AUTO" feature.

 SET @beforeJson = (SELECT * FROM DELETED FOR JSON AUTO)
SET @afterJson = (SELECT * FROM INSERTED FOR JSON AUTO)

That returns a JSON representation fo the record before/after the change. I then store those values in a history table with a timestamp of when the change occurred (I also store the ID for current record of concern). Using the serialization process, I can control how data is backfilled in the case of changes to schema.

I learned about this from this link here

How do I make a column unique and index it in a Ruby on Rails migration?

You might want to add name for the unique key as many times the default unique_key name by rails can be too long for which the DB can throw the error.

To add name for your index just use the name: option. The migration query might look something like this -

add_index :table_name, [:column_name_a, :column_name_b, ... :column_name_n], unique: true, name: 'my_custom_index_name'

More info - http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

var functionName = function() {} vs function functionName() {}

The two code snippets you've posted there will, for almost all purposes, behave the same way.

However, the difference in behaviour is that with the first variant (var functionOne = function() {}), that function can only be called after that point in the code.

With the second variant (function functionTwo()), the function is available to code that runs above where the function is declared.

This is because with the first variant, the function is assigned to the variable foo at run time. In the second, the function is assigned to that identifier, foo, at parse time.

More technical information

JavaScript has three ways of defining functions.

  1. Your first snippet shows a function expression. This involves using the "function" operator to create a function - the result of that operator can be stored in any variable or object property. The function expression is powerful that way. The function expression is often called an "anonymous function", because it does not have to have a name,
  2. Your second example is a function declaration. This uses the "function" statement to create a function. The function is made available at parse time and can be called anywhere in that scope. You can still store it in a variable or object property later.
  3. The third way of defining a function is the "Function()" constructor, which is not shown in your original post. It's not recommended to use this as it works the same way as eval(), which has its problems.

Inline comments for Bash?

How about storing it in a variable?

#extraargs=-F
ls -l $extraargs -a /etc

Serializing class instance to JSON

Python3.x

The best aproach I could reach with my knowledge was this.
Note that this code treat set() too.
This approach is generic just needing the extension of class (in the second example).
Note that I'm just doing it to files, but it's easy to modify the behavior to your taste.

However this is a CoDec.

With a little more work you can construct your class in other ways. I assume a default constructor to instance it, then I update the class dict.

import json
import collections


class JsonClassSerializable(json.JSONEncoder):

    REGISTERED_CLASS = {}

    def register(ctype):
        JsonClassSerializable.REGISTERED_CLASS[ctype.__name__] = ctype

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        if isinstance(obj, JsonClassSerializable):
            jclass = {}
            jclass["name"] = type(obj).__name__
            jclass["dict"] = obj.__dict__
            return dict(_class_object=jclass)
        else:
            return json.JSONEncoder.default(self, obj)

    def json_to_class(self, dct):
        if '_set_object' in dct:
            return set(dct['_set_object'])
        elif '_class_object' in dct:
            cclass = dct['_class_object']
            cclass_name = cclass["name"]
            if cclass_name not in self.REGISTERED_CLASS:
                raise RuntimeError(
                    "Class {} not registered in JSON Parser"
                    .format(cclass["name"])
                )
            instance = self.REGISTERED_CLASS[cclass_name]()
            instance.__dict__ = cclass["dict"]
            return instance
        return dct

    def encode_(self, file):
        with open(file, 'w') as outfile:
            json.dump(
                self.__dict__, outfile,
                cls=JsonClassSerializable,
                indent=4,
                sort_keys=True
            )

    def decode_(self, file):
        try:
            with open(file, 'r') as infile:
                self.__dict__ = json.load(
                    infile,
                    object_hook=self.json_to_class
                )
        except FileNotFoundError:
            print("Persistence load failed "
                  "'{}' do not exists".format(file)
                  )


class C(JsonClassSerializable):

    def __init__(self):
        self.mill = "s"


JsonClassSerializable.register(C)


class B(JsonClassSerializable):

    def __init__(self):
        self.a = 1230
        self.c = C()


JsonClassSerializable.register(B)


class A(JsonClassSerializable):

    def __init__(self):
        self.a = 1
        self.b = {1, 2}
        self.c = B()

JsonClassSerializable.register(A)

A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
print(b.b)
print(b.c.a)

Edit

With some more of research I found a way to generalize without the need of the SUPERCLASS register method call, using a metaclass

import json
import collections

REGISTERED_CLASS = {}

class MetaSerializable(type):

    def __call__(cls, *args, **kwargs):
        if cls.__name__ not in REGISTERED_CLASS:
            REGISTERED_CLASS[cls.__name__] = cls
        return super(MetaSerializable, cls).__call__(*args, **kwargs)


class JsonClassSerializable(json.JSONEncoder, metaclass=MetaSerializable):

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        if isinstance(obj, JsonClassSerializable):
            jclass = {}
            jclass["name"] = type(obj).__name__
            jclass["dict"] = obj.__dict__
            return dict(_class_object=jclass)
        else:
            return json.JSONEncoder.default(self, obj)

    def json_to_class(self, dct):
        if '_set_object' in dct:
            return set(dct['_set_object'])
        elif '_class_object' in dct:
            cclass = dct['_class_object']
            cclass_name = cclass["name"]
            if cclass_name not in REGISTERED_CLASS:
                raise RuntimeError(
                    "Class {} not registered in JSON Parser"
                    .format(cclass["name"])
                )
            instance = REGISTERED_CLASS[cclass_name]()
            instance.__dict__ = cclass["dict"]
            return instance
        return dct

    def encode_(self, file):
        with open(file, 'w') as outfile:
            json.dump(
                self.__dict__, outfile,
                cls=JsonClassSerializable,
                indent=4,
                sort_keys=True
            )

    def decode_(self, file):
        try:
            with open(file, 'r') as infile:
                self.__dict__ = json.load(
                    infile,
                    object_hook=self.json_to_class
                )
        except FileNotFoundError:
            print("Persistence load failed "
                  "'{}' do not exists".format(file)
                  )


class C(JsonClassSerializable):

    def __init__(self):
        self.mill = "s"


class B(JsonClassSerializable):

    def __init__(self):
        self.a = 1230
        self.c = C()


class A(JsonClassSerializable):

    def __init__(self):
        self.a = 1
        self.b = {1, 2}
        self.c = B()


A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
# 1
print(b.b)
# {1, 2}
print(b.c.a)
# 1230
print(b.c.c.mill)
# s

How to convert date into this 'yyyy-MM-dd' format in angular 2

_x000D_
_x000D_
const formatDate=(dateObj)=>{
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const dateOrdinal=(dom)=> {
    if (dom == 31 || dom == 21 || dom == 1) return dom + "st";
    else if (dom == 22 || dom == 2) return dom + "nd";
    else if (dom == 23 || dom == 3) return dom + "rd";
    else return dom + "th";
};
return dateOrdinal(dateObj.getDate())+', '+days[dateObj.getDay()]+' '+ months[dateObj.getMonth()]+', '+dateObj.getFullYear();
}
const ddate = new Date();
const result=formatDate(ddate)
document.getElementById("demo").innerHTML = result
_x000D_
<!DOCTYPE html>
<html>
<body>
<h2>Example:20th, Wednesday September, 2020 <h2>
<p id="demo"></p>
</body>
</html>
_x000D_
_x000D_
_x000D_

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

Show "loading" animation on button click

$("#btnId").click(function(e){
      e.preventDefault();
      $.ajax({
        ...
        beforeSend : function(xhr, opts){
            //show loading gif
        },
        success: function(){

        },
        complete : function() {
           //remove loading gif
        }
    });
});

Generating HTML email body in C#

You can use the MailDefinition class.

This is how you use it:

MailDefinition md = new MailDefinition();
md.From = "[email protected]";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";

ListDictionary replacements = new ListDictionary();
replacements.Add("{name}", "Martin");
replacements.Add("{country}", "Denmark");

string body = "<div>Hello {name} You're from {country}.</div>";

MailMessage msg = md.CreateMailMessage("[email protected]", replacements, body, new System.Web.UI.Control());

Also, I've written a blog post on how to generate HTML e-mail body in C# using templates using the MailDefinition class.

window.onload vs document.onload

Window.onload is the standard, however - the web browser in the PS3 (based on Netfront) doesn't support the window object, so you can't use it there.

Character Limit in HTML

use the "maxlength" attribute as others have said.

if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: How to impose maxlength on textArea in HTML using JavaScript

c++ array assignment of multiple values

There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.

Here is what you can do:

#include <algorithm>

int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);

However, in C++0x, you can do this:

std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};

Of course, if you choose to use std::vector instead of raw array.

How to create a printable Twitter-Bootstrap page

In case someone is looking for a solution for Bootstrap v2.X.X here. I am leaving the solution I was using. This is not fully tested on all browsers however it could be a good start.

1) make sure the media attribute of bootstrap-responsive.css is screen.

<link href="/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />

2) create a print.css and make sure its media attribute print

<link href="/css/print.css" rel="stylesheet" media="print" />

3) inside print.css, add the "width" of your website in html & body

html, 
body {
    width: 1200px !important;
}

4.) reproduce the necessary media query classes in print.css because they were inside bootstrap-responsive.css and we have disabled it when printing.

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Here is full version of print.css:

html, 
body {
    width: 1200px !important;
}

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Quickly reading very large tables as dataframes

Instead of the conventional read.table I feel fread is a faster function. Specifying additional attributes like select only the required columns, specifying colclasses and string as factors will reduce the time take to import the file.

data_frame <- fread("filename.csv",sep=",",header=FALSE,stringsAsFactors=FALSE,select=c(1,4,5,6,7),colClasses=c("as.numeric","as.character","as.numeric","as.Date","as.Factor"))

creating array without declaring the size - java

Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.

Example:

List<Float> unindexedVectors = new ArrayList<Float>();

unindexedVectors.add(2.22f);

unindexedVectors.get(2);

Converting cv::Mat to IplImage*

Personaly I think it's not the problem caused by type casting but a buffer overflow problem; it is this line

cvCopy(iplimagearray[i], xyz);   

that I think will cause segment fault, I suggest that you confirm the array iplimagearray[i] have enough size of buffer to receive copyed data

Selecting data from two different servers in SQL Server

I know this is an old question but I use synonyms. Supposedly the query is executed within database server A, and looks for a table in a database server B that does not exist on server A. Add then a synonym on A database that calls your table from server B. Your query doesn't have to include any schemas, or different database names, just call the table name per usual and it will work.

There's no need to link servers as synonyms per say are sort of linking.

What is the easiest way to get current GMT time in Unix timestamp format?

#First Example:
from datetime import datetime, timezone    
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)

Output: 1572878043380

#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)

Output: 1572878043

  • Here, we can see the first example gives more accurate time than second one.
  • Here I am using the first one.

Creating and writing lines to a file

' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")

' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close

' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
    Line = File.ReadLine
    WScript.Echo(Line)
Loop
File.Close

' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close

Is it possible to implement a Python for range loop without an iterator variable?

You can use _11 (or any number or another invalid identifier) to prevent name-colision with gettext. Any time you use underscore + invalid identifier you get a dummy name that can be used in for loop.

Select row on click react-table

Another mechanism for dynamic styling is to define it in the JSX for your component. For example, the following could be used to selectively style the current step in the React tic-tac-toe tutorial (one of the suggested extra credit enhancements:

  return (
    <li key={move}>
      <button style={{fontWeight:(move === this.state.stepNumber ? 'bold' : '')}} onClick={() => this.jumpTo(move)}>{desc}</button>
    </li>
  );

Granted, a cleaner approach would be to add/remove a 'selected' CSS class but this direct approach might be helpful in some cases.

Execute JavaScript code stored as a string

eval(s);

Remember though, that eval is very powerful and quite unsafe. You better be confident that the script you are executing is safe and unmutable by users.

set dropdown value by text using jquery

For the exact match use

    $("#HowYouKnow option").filter(function(index) { return $(this).text() === "GOOGLE"; }).attr('selected', 'selected');

contains is going to select the last match which might not be exact.

Keyboard shortcuts with jQuery

Since this question was originally asked, John Resig (the primary author of jQuery) has forked and improved the js-hotkeys project. His version is available at:

http://github.com/jeresig/jquery.hotkeys

Remove a folder from git tracking

I came across this question while Googling for "git remove folder from tracking". The OP's question lead me to the answer. I am summarizing it here for future generations.

Question

How do I remove a folder from my git repository without deleting it from my local machine (i.e., development environment)?

Answer

Step 1. Add the folder path to your repo's root .gitignore file.

path_to_your_folder/

Step 2. Remove the folder from your local git tracking, but keep it on your disk.

git rm -r --cached path_to_your_folder/

Step 3. Push your changes to your git repo.

The folder will be considered "deleted" from Git's point of view (i.e. they are in past history, but not in the latest commit, and people pulling from this repo will get the files removed from their trees), but stay on your working directory because you've used --cached.

how to re-format datetime string in php?

For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php

$datetime = "20130409163705"; 
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want

Result:

09/04/2013 16:37:05

Format Date/Time in XAML in Silverlight

<TextBlock Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}" />

will return you

04/07/2011 at 1:28 PM (-04)

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

This crash is due to a FragmentTransaction being committed after its owning Activity's lifecycle has already run onSaveInstanceState. This is often caused by committing FragmentTransactions from an asynchronous callback. Check out the linked resource for more details.

Fragment Transactions & Activity State Loss

http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

By mistake I added the compile com.google.android.gms:play-services:5.+ in dependencies in build script block. You should add it in the second dependency block. make changes->synch project with gradle.

How do I activate a Spring Boot profile when running from IntelliJ?

I added -Dspring.profiles.active=test to VM Options and then re-ran that configuration. It worked perfectly.

This can be set by

  • Choosing Run | Edit Configurations...
  • Go to the Configuration tab
  • Expand the Environment section to reveal VM options

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

I used this:

HTMLDatetoIsoDate(htmlDate){
  let year = Number(htmlDate.toString().substring(0, 4))
  let month = Number(htmlDate.toString().substring(5, 7))
  let day = Number(htmlDate.toString().substring(8, 10))
  return new Date(year, month - 1, day)
}

isoDateToHtmlDate(isoDate){
  let date = new Date(isoDate);
  let dtString = ''
  let monthString = ''
  if (date.getDate() < 10) {
    dtString = '0' + date.getDate();
  } else {
    dtString = String(date.getDate())
  }
  if (date.getMonth()+1 < 10) {
    monthString = '0' + Number(date.getMonth()+1);
  } else {
    monthString = String(date.getMonth()+1);
  }
  return date.getFullYear()+'-' + monthString + '-'+dtString
}

Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/

How to set thousands separator in Java?

DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
formatSymbols.setDecimalSeparator('|');
formatSymbols.setGroupingSeparator(' ');

String strange = "#,##0.###";
DecimalFormat df = new DecimalFormat(strange, formatSymbols);
df.setGroupingSize(4);

String out = df.format(new BigDecimal(300000).doubleValue());

System.out.println(out);

What good are SQL Server schemas?

I know it's an old thread, but I just looked into schemas myself and think the following could be another good candidate for schema usage:

In a Datawarehouse, with data coming from different sources, you can use a different schema for each source, and then e.g. control access based on the schemas. Also avoids the possible naming collisions between the various source, as another poster replied above.

Pass table as parameter into sql server UDF

To obtain the column count on a table, use this:

select count(id) from syscolumns where id = object_id('tablename')

and to pass a table to a function, try XML as show here:

create function dbo.ReadXml (@xmlMatrix xml)
returns table
as
return
( select
t.value('./@Salary', 'integer') as Salary,
t.value('./@Age', 'integer') as Age
from @xmlMatrix.nodes('//row') x(t)
)
go

declare @source table
( Salary integer,
age tinyint
)
insert into @source
select 10000, 25 union all
select 15000, 27 union all
select 12000, 18 union all
select 15000, 36 union all
select 16000, 57 union all
select 17000, 44 union all
select 18000, 32 union all
select 19000, 56 union all
select 25000, 34 union all
select 7500, 29
--select * from @source

declare @functionArgument xml

select @functionArgument =
( select
Salary as [row/@Salary],
Age as [row/@Age]
from @source
for xml path('')
)
--select @functionArgument as [@functionArgument]

select * from readXml(@functionArgument)

/* -------- Sample Output: --------
Salary Age
----------- -----------
10000 25
15000 27
12000 18
15000 36
16000 57
17000 44
18000 32
19000 56
25000 34
7500 29
*/

Python : List of dict, if exists increment a dict value, if not append a new dict

This always works fine for me:

for url in list_of_urls:
    urls.setdefault(url, 0)
    urls[url] += 1

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

Get selected key/value of a combo box using jQuery

$("#elementName option").text(); 

This will give selected text of Combo-Box.

$("#elementName option").val();

This will give selected value associated selected item in Combo-Box.

$("#elementName option").length;

It will give the multi-select combobox values in the array and length will give number of element of the array.

Note:#elementName is id the Combo-box.

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

Listening for variable changes in JavaScript

It's not directly possible.

However, this can be done using CustomEvent: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent

The below method accepts an array of variable names as an input and adds event listener for each variable and triggers the event for any changes to the value of the variables.

The Method uses polling to detect the change in the value. You can increase the value for timeout in milliseconds.

function watchVariable(varsToWatch) {
    let timeout = 1000;
    let localCopyForVars = {};
    let pollForChange = function () {
        for (let varToWatch of varsToWatch) {
            if (localCopyForVars[varToWatch] !== window[varToWatch]) {
                let event = new CustomEvent('onVar_' + varToWatch + 'Change', {
                    detail: {
                        name: varToWatch,
                        oldValue: localCopyForVars[varToWatch],
                        newValue: window[varToWatch]
                    }
                });
                document.dispatchEvent(event);
                localCopyForVars[varToWatch] = window[varToWatch];
            }
        }
        setTimeout(pollForChange, timeout);
    };
    let respondToNewValue = function (varData) {
        console.log("The value of the variable " + varData.name + " has been Changed from " + varData.oldValue + " to " + varData.newValue + "!!!"); 
    }
    for (let varToWatch of varsToWatch) {
        localCopyForVars[varToWatch] = window[varToWatch];
        document.addEventListener('onVar_' + varToWatch + 'Change', function (e) {
            respondToNewValue(e.detail);
        });
    }
    setTimeout(pollForChange, timeout);
}

By calling the Method:

watchVariables(['username', 'userid']);

It will detect the changes to variables username and userid.

Increasing Google Chrome's max-connections-per-server limit to more than 6

IE is even worse with 2 connection per domain limit. But I wouldn't rely on fixing client browsers. Even if you have control over them, browsers like chrome will auto update and a future release might behave differently than you expect. I'd focus on solving the problem within your system design.

Your choices are to:

  1. Load the images in sequence so that only 1 or 2 XHR calls are active at a time (use the success event from the previous image to check if there are more images to download and start the next request).

  2. Use sub-domains like serverA.myphotoserver.com and serverB.myphotoserver.com. Each sub domain will have its own pool for connection limits. This means you could have 2 requests going to 5 different sub-domains if you wanted to. The downfall is that the photos will be cached according to these sub-domains. BTW, these don't need to be "mirror" domains, you can just make additional DNS pointers to the exact same website/server. This means you don't have the headache of administrating many servers, just one server with many DNS records.

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

I imagine that these might possibly be changed with some styling options. But as far as default values go, these are taken from my version of Excel 2010 which should have the defaults.

"Bad" Red Font: 156, 0, 6; Fill: 255, 199, 206

"Good" Green Font: 0, 97, 0; Fill: 198, 239, 206

"Neutral" Yellow Font: 156, 101, 0; Fill: 255, 235, 156

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

If you have used CHECK CONSTRAINT on table for string field length

e.g: to check username length >= 8

use:

CHECK (CHAR_LENGTH(username)>=8)

instead of

CHECK (username>=8)

fix the check constraint if any have wrong datatype comparison

NHibernate.MappingException: No persister for: XYZ

This error occurs because of invalid mapping configuration. You should check where you set .Mappings for your session factory. Basically search for ".Mappings(" in your project and make sure you specified correct entity class in below line.

.Mappings(m => m.FluentMappings.AddFromAssemblyOf<YourEntityClassName>())

How to check if a function exists on a SQL database

Why not just:

IF object_id('YourFunctionName', 'FN') IS NOT NULL
BEGIN
    DROP FUNCTION [dbo].[YourFunctionName]
END
GO

The second argument of object_id is optional, but can help to identify the correct object. There are numerous possible values for this type argument, particularly:

  • FN : Scalar function
  • IF : Inline table-valued function
  • TF : Table-valued-function
  • FS : Assembly (CLR) scalar-function
  • FT : Assembly (CLR) table-valued function

Oracle JDBC intermittent Connection Issue

-Djava.security.egd=file:/dev/./urandom should be right! not -Djava.security.egd=file:/dev/../dev/urandom or -Djava.security.egd=file:///dev/urandom

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Simplest working solution:

Download the MySQL Connector C 6.0.2 from below link and Install.

http://dev.mysql.com/downloads/connector/c/6.0.html#downloads

After installing the MySQL Connector C 6.0.2, copy the folder "MySQL Connector C 6.0.2" from "C:\Program Files\MySQL" to "C:\Program Files (x86)\MySQL".

Then type

pip install MySQL-python

It will definitely work.

what is the differences between sql server authentication and windows authentication..?

I don't know SQLServer as well as other DBMS' but I imagine the benefit is the same as with DB2 and Oracle. If you use Windows authentication, you only have to maintain one set of users and/or passwords, that of Windows, which is already done for you.

DBMS authentication means having a separate set of users and/or passwords which must be maintained.

In addition, Windows passwords allow them to be configured centrally for the enterprise (Active Directory) whereas SQLServer has to maintain one set for each DBMS instance.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

Since you're only dealing with a 3x3 matrix of possible locations, it'd be pretty easy to just write a search through all possibilities without taxing you computing power. For each open space, compute through all the possible outcomes after that marking that space (recursively, I'd say), then use the move with the most possibilities of winning.

Optimizing this would be a waste of effort, really. Though some easy ones might be:

  • Check first for possible wins for the other team, block the first one you find (if there are 2 the games over anyway).
  • Always take the center if it's open (and the previous rule has no candidates).
  • Take corners ahead of sides (again, if the previous rules are empty)

Pointer-to-pointer dynamic two-dimensional array

this can be done this way

  1. I have used Operator Overloading
  2. Overloaded Assignment
  3. Overloaded Copy Constructor

    /*
     * Soumil Nitin SHah
     * Github: https://github.com/soumilshah1995
     */
    
    #include <iostream>
    using namespace std;
            class Matrix{
    
    public:
        /*
         * Declare the Row and Column
         *
         */
        int r_size;
        int c_size;
        int **arr;
    
    public:
        /*
         * Constructor and Destructor
         */
    
        Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
        {
            arr = new int*[r_size];
            // This Creates a 2-D Pointers
            for (int i=0 ;i < r_size; i++)
            {
                arr[i] = new int[c_size];
            }
    
            // Initialize all the Vector to 0 initially
            for (int row=0; row<r_size; row ++)
            {
                for (int column=0; column < c_size; column ++)
                {
                    arr[row][column] = 0;
                }
            }
            std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
        }
    
        ~Matrix()
        {
            std::cout << "Destructpr  -- Deleting  Array Size ::" << r_size <<" " << c_size << endl;
    
        }
    
        Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
    
        {
            for (int row=0; row<source.r_size; row ++)
            {
                for (int column=0; column < source.c_size; column ++)
                {
                    arr[row][column] = source.arr[row][column];
                }
            }
    
            cout << "Copy Constructor " << endl;
        }
    
    
    public:
        /*
         * Operator Overloading
         */
    
        friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
        {
            int rowCounter = 0;
            int columnCOUNTER = 0;
            int globalCounter = 0;
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    globalCounter = globalCounter + 1;
                }
                rowCounter = rowCounter + 1;
            }
    
    
            os << "Total There are " << globalCounter << " Elements" << endl;
            os << "Array Elements are as follow -------" << endl;
            os << "\n";
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    os << rhs.arr[row][column] << " ";
                }
            os <<"\n";
            }
            return os;
        }
    
        void operator()(int row, int column , int Data)
        {
            arr[row][column] = Data;
        }
    
        int &operator()(int row, int column)
        {
            return arr[row][column];
        }
    
        Matrix &operator=(Matrix &rhs)
                {
                    cout << "Assingment Operator called " << endl;cout <<"\n";
                    if(this == &rhs)
                    {
                        return *this;
                    } else
                        {
                        delete [] arr;
    
                            arr = new int*[r_size];
                            // This Creates a 2-D Pointers
                            for (int i=0 ;i < r_size; i++)
                            {
                                arr[i] = new int[c_size];
                            }
    
                            // Initialize all the Vector to 0 initially
                            for (int row=0; row<r_size; row ++)
                            {
                                for (int column=0; column < c_size; column ++)
                                {
                                    arr[row][column] = rhs.arr[row][column];
                                }
                            }
    
                            return *this;
                        }
    
                }
    
    };
    
                int main()
    {
    
        Matrix m1(3,3);         // Initialize Matrix 3x3
    
        cout << m1;cout << "\n";
    
        m1(0,0,1);
        m1(0,1,2);
        m1(0,2,3);
    
        m1(1,0,4);
        m1(1,1,5);
        m1(1,2,6);
    
        m1(2,0,7);
        m1(2,1,8);
        m1(2,2,9);
    
        cout << m1;cout <<"\n";             // print Matrix
        cout << "Element at Position (1,2) : " << m1(1,2) << endl;
    
        Matrix m2(3,3);
        m2 = m1;
        cout << m2;cout <<"\n";
    
        print(m2);
    
        return 0;
    }
    

Kubernetes how to make Deployment to update image

kubectl rollout restart deployment myapp

This is the current way to trigger a rolling update and leave the old replica sets in place for other operations provided by kubectl rollout like rollbacks.

How to draw interactive Polyline on route google maps v2 android

Using the google maps projection api to draw the polylines on an overlay view enables us to do a lot of things. Check this repo that has an example.

enter image description here

Get all files and directories in specific path fast

You can use this to get all directories and sub-directories. Then simply loop through to process the files.

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

foreach(string f in folders)
{
   //call some function to get all files in folder
}

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

Key should be readable by the logged in user.

Try this:

chmod 400 ~/.ssh/Key file
chmod 400 ~/.ssh/vm_id_rsa.pub

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

This is old post and I am sorry but even installing of KB2999226 will not help if you don't have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) update package. Without it the installation of KB2999226 returns error "The update is not applicable to your computer". Typically you will get this problem if you have some offline envinroment for example dev virtual machines without access to the WSUS or Windows Update services and old ISO images of Windows 8.1, Server 2012 R2.

Jenkins Slave port number for firewall

I have a similar scenario, and had no problem connecting after setting the JNLP port as you describe, and adding a single firewall rule allowing a connection on the server using that port. Granted it is a randomly selected client port going to a known server port (a host:ANY -> server:1 rule is needed).

From my reading of the source code, I don't see a way to set the local port to use when making the request from the slave. It's unfortunate, it would be a nice feature to have.

Alternatives:

Use a simple proxy on your client that listens on port N and then does forward all data to the actual Jenkins server on the remote host using a constant local port. Connect your slave to this local proxy instead of the real Jenkins server.

Create a custom Jenkins slave build that allows an option to specify the local port to use.

Remember also if you are using HTTPS via a self-signed certificate, you must alter the configuration jenkins-slave.xml file on the slave to specify the -noCertificateCheck option on the command line.

finished with non zero exit value

Please make sure your gradle build your compileSdkVersion has its sdk installed in your project. Then just reload your project everything should be fine.

How do I dynamically set HTML5 data- attributes using react?

You should not wrap JavaScript expressions in quotes.

<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>

Take a look at the JavaScript Expressions docs for more info.

Simulate a specific CURL in PostMan

1) Put https://api-server.com/API/index.php/member/signin in the url input box and choose POST from the dropdown

2) In Headers tab, enter:

Content-Type: image/jpeg

Content-Transfer-Encoding: binary

3) In Body tab, select the raw radio button and write:

{"description":"","phone":"","lastname":"","app_version":"2.6.2","firstname":"","password":"my_pass","city":"","apikey":"213","lang":"fr","platform":"1","email":"[email protected]","pseudo":"example"}

select form-data radio button and write:

key = name Value = userfile Select Text key = filename Select File and upload your profil.jpg

Downloading a picture via urllib and python

Using requests

import requests
import shutil,os

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
currentDir = os.getcwd()
path = os.path.join(currentDir,'Images')#saving images to Images folder

def ImageDl(url):
    attempts = 0
    while attempts < 5:#retry 5 times
        try:
            filename = url.split('/')[-1]
            r = requests.get(url,headers=headers,stream=True,timeout=5)
            if r.status_code == 200:
                with open(os.path.join(path,filename),'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw,f)
            print(filename)
            break
        except Exception as e:
            attempts+=1
            print(e)

if __name__ == '__main__':
    ImageDl(url)

Submit form using AJAX and jQuery

First give your form an id attribute, then use code like this:

$(document).ready( function() {
  var form = $('#my_awesome_form');

  form.find('select:first').change( function() {
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );

} );

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

Execute jQuery function after another function completes

You could also use custom events:

function Typer() {
    // Some stuff

    $(anyDomElement).trigger("myCustomEvent");
}


$(anyDomElement).on("myCustomEvent", function() {
    // Some other stuff
});

Expected block end YAML error

I would like to make this answer for meaningful, so the same kind of erroneous user can enjoy without feel any hassle.

Actually, i was getting the same error but for the different reason, in my case I didn't used any kind of quoted, still getting the same error like expected <block end>, but found BlockMappingStart.

I have solved it by fixing, the Alignment issue inside the same .yml file.

If we don't manage the proper 'tab-space(Keyboard key)' for maintaining successor or ancestor then we have to phase such kind of things.

Now i am doing well.

Sum up a column from a specific row down

=Sum(C:C)-Sum(C1:C5)

Sum everything then remove the sum of the values in the cells you don't want, no Volatile Offset's, Indirect's, or Array's needed.

Just for fun if you don't like that method you could also use:

=SUM($C$6:INDEX($C:$C,MATCH(9.99999999999999E+307,$C:$C))

The above formula will Sum only from C6 through the last cell in C:C where a match of a number is found. This is also non-volatile, but I believe more costly and sloppy. Just added it in case you'd prefer this anyways.

If you would like to do function like CountA for text using the last text value in a column you could use.

=COUNTIF(C6:INDEX($C:$C,MATCH(REPT("Z",255),$C:$C)),"T")

you could also use other combinations like:

=Sum($C$6:$C$65536) 

or

=CountIF($C$6:$C$65536,"T") 

The above would do what you ask in Excel 2003 and lower

=Sum($C$6:$C$1048576) 

or

=CountIF($C$6:$C$1048576,"T")

Would both work for Excel 2007+

All above functions would simply ignore all the blank values under the last value.

How can I drop all the tables in a PostgreSQL database?

If you want to nuke all tables anyway, you can dispense with niceties such as CASCADE by putting all tables into a single statement. This also makes execution quicker.

SELECT 'TRUNCATE TABLE ' || string_agg('"' || tablename || '"', ', ') || ';' 
FROM pg_tables WHERE schemaname = 'public';

Executing it directly:

DO $$
DECLARE tablenames text;
BEGIN    
    tablenames := string_agg('"' || tablename || '"', ', ') 
        FROM pg_tables WHERE schemaname = 'public';
    EXECUTE 'TRUNCATE TABLE ' || tablenames;
END; $$

Replace TRUNCATE with DROP as applicable.

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

Try looking here: Best way to get application folder path

To quote from there:

System.IO.Directory.GetCurrentDirectory() returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

How to declare a inline object with inline variables without a parent class

You can also declare 'x' with the keyword var:

var x = new
{
  driver = new
  {
    firstName = "john",
    lastName = "walter"
  },
  car = new
  {
    brand = "BMW"
  }
};

This will allow you to declare your x object inline, but you will have to name your 2 anonymous objects, in order to access them. You can have an array of "x" :

x.driver.firstName // "john"
x.car.brand // "BMW"

var y = new[] { x, x, x, x };
y[1].car.brand; // "BMW"

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Here you go:

USE information_schema;
SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id';

If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database:

SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id'
  AND TABLE_SCHEMA = 'your_database_name';

How to place and center text in an SVG rectangle

alignment-baseline is not the right attribute to use here. The correct answer is to use a combination of dominant-baseline="central" and text-anchor="middle":

_x000D_
_x000D_
<svg width="200" height="100">_x000D_
    <g>_x000D_
        <rect x="0" y="0" width="200" height="100" style="stroke:red; stroke-width:3px; fill:white;"/>_x000D_
        <text x="50%" y="50%" style="dominant-baseline:central; text-anchor:middle; font-size:40px;">TEXT</text>_x000D_
    </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Querying a linked sql server

The accepted answer works for me.

Also, in MSSQLMS, you can browse the tree in the Object Explorer to the table you want to query.

[Server] -> Server Objects -> Linked Servers -> [Linked server] -> Catalogs -> [Database] -> [table]

then Right click, Script Table as, SELECT To, New Query Window

And the query will be generated for you with the right FROM, which you can use in your JOIN

Should we @Override an interface's method implementation?

You should use @Override whenever possible. It prevents simple mistakes from being made. Example:

class C {
    @Override
    public boolean equals(SomeClass obj){
        // code ...
    }
}

This doesn't compile because it doesn't properly override public boolean equals(Object obj).

The same will go for methods that implement an interface (1.6 and above only) or override a Super class's method.

Why do I get a C malloc assertion failure?

You are probably overrunning beyond the allocated mem somewhere. then the underlying sw doesn't pick up on it until you call malloc

There may be a guard value clobbered that is being caught by malloc.

edit...added this for bounds checking help

http://www.lrde.epita.fr/~akim/ccmp/doc/bounds-checking.html

CSS : center form in page horizontally and vertically

If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.

<div align="center"><form id="form_login"><!--form content here--></form></div>

UPDATE

@G-Cyr is right. align="center" attribute is now obsolete. You can use text-align attribute for this as following.

<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>

This will center all the content inside the parent DIV. An optional way is to use margin: auto CSS attribute with predefined widths and heights. Please follow the following thread for more information.

How to horizontally center a in another ?

Vertical centering is little difficult than that. To do that, you can do the following stuff.

html

<body>
<div id="parent">
    <form id="form_login">
     <!--form content here-->
    </form>
</div>
</body>

Css

#parent {
   display: table;
   width: 100%;
}
#form_login {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

I have faced the same issue with you, then solved it, Here are solutions, I wish it maybe can help
First

In the IIS modules Configuration, loop up the WebDAVModule, if your web server has it, then remove it

Second

In the IIS handler mappings configuration, you can see the list of enabling handler, to choose the PHP item, edit it, on the edit page, click request restrictions button, then select the verbs tab in the modal, in the specify the verbs to be handle label, check the all verbs radio, then click ok, you also maybe see a warning, it shows us that use double quotation marks to PHP-CGI execution, then do it

if done it, then restart IIS server, it will be ok

enter image description here

Evaluate expression given as a string

The eval() function evaluates an expression, but "5+5" is a string, not an expression. Use parse() with text=<string> to change the string into an expression:

> eval(parse(text="5+5"))
[1] 10
> class("5+5")
[1] "character"
> class(parse(text="5+5"))
[1] "expression"

Calling eval() invokes many behaviours, some are not immediately obvious:

> class(eval(parse(text="5+5")))
[1] "numeric"
> class(eval(parse(text="gray")))
[1] "function"
> class(eval(parse(text="blue")))
Error in eval(expr, envir, enclos) : object 'blue' not found

See also tryCatch.

Storing SHA1 hash values in MySQL

Output size of sha1 is 160 bits. Which is 160/8 == 20 chars (if you use 8-bit chars) or 160/16 = 10 (if you use 16-bit chars).

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

https://github.com/rackt/react-router/blob/e7c6f3d848e55dda11595447928e843d39bed0eb/examples/query-params/app.js#L4 Router is also one of the properties of react-router. So change your modules require code like that:

  var reactRouter = require('react-router')
  var Router = reactRouter.Router
  var Route = reactRouter.Route
  var Link = reactRouter.Link

If you want to use ES6 syntax the link use(import), use babel as helper.

BTW, to make your code works, we can add {this.props.children} in the App, like

render() {
  return (
    <div>
      <h1>App</h1>
      <ul>
        <li><Link to="/about">About</Link></li>
      </ul>
      {this.props.children}
    </div>

  )
}

TempData keep() vs peek()

Just finished understanding Peek and Keep and had same confusion initially. The confusion arises becauses TempData behaves differently under different condition. You can watch this video which explains the Keep and Peek with demonstration https://www.facebook.com/video.php?v=689393794478113

Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”.

If we understand these 4 points you would see more clarity.Below is a diagram with all 4 conditions, read the third and fourth point which talks about Peek and Keep.

enter image description here

Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.

Condition 2 ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.

string str = TempData["MyData"];

Even if you are displaying it’s a normal read like the code below.

@TempData["MyData"];

Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.

@TempData["MyData"];
TempData.Keep("MyData");

Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.

string str = TempData.Peek("Td").ToString();

Reference :- http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

How to find foreign key dependencies in SQL Server?

Just a note for @"John Sansom" answer,

If the foreign key dependencies are sought, I think that the PT Where clause should be:

i1.CONSTRAINT_TYPE = 'FOREIGN KEY'  -- instead of 'PRIMARY KEY'

and its the ON condition:

ON PT.TABLE_NAME = FK.TABLE_NAME – instead of PK.TABLE_NAME

As commonly is used the primary key of the foreign table, I think this issue has not been noticed before.

Uninstalling Android ADT

The only way to remove the ADT plugin from Eclipse is to go to Help > About Eclipse/About ADT > Installation Details.

Select a plug-in you want to uninstall, then click Uninstall... button at the bottom.

enter image description here

If you cannot remove ADT from this location, then your best option is probably to start fresh with a clean Eclipse install.

Changing the git user inside Visual Studio Code

Press Ctrl + Shift + G in Visual Studio Code and go to more and select Show git output. Click Terminal and type git remote -v and verify that the origin branch has latest username in it like:

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (fetch)

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (push)

Here DroidPulkit is my username.

If the username is not what you wanted it to be then change it with:

git add remote origin [email protected]:newUserName/RepoName.git

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

Cut off text in string after/before separator in powershell

This does work for a specific delimiter for a specific amount of characters between the delimiter. I had many issues attempting to use this in a for each loop where the position changed but the delimiter was the same. For example I was using the backslash as the delimiter and wanted to only use everything to the right of the backslash. The issue was that once the position was defined (71 characters from the beginning) it would use $pos as 71 every time regardless of where the delimiter actually was in the script. I found another method of using a delimiter and .split to break things up then used the split variable to call the sections For instance the first section was $variable[0] and the second section was $variable[1].

Last non-empty cell in a column

A simple one which works for me:

=F7-INDEX(A:A,COUNT(A:A))

How to make a smaller RatingBar?

The Best Answer for small ratingbar

<RatingBar
                    android:layout_width="wrap_content"
                    style = "?android:attr/ratingBarStyleSmall"
                    android:layout_height="wrap_content" />

How to enable CORS on Firefox?

just type in your browser CORS add in firefox Then download this and install on browser finally you found top right side one Core spell to toggle that green for enable and red for not enable

How do I get the current year using SQL on Oracle?

Use extract(datetime) function it's so easy, simple.

It returns year, month, day, minute, second

Example:

select extract(year from sysdate) from dual;

Force IE compatibility mode off using tags

There is the "edge" mode.

<html>
   <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <title>My Web Page</title>
   </head>
   <body>
      <p>Content goes here.</p>
   </body>
</html>

From the linked MSDN page:

Edge mode tells Windows Internet Explorer to display content in the highest mode available, which actually breaks the “lock-in” paradigm. With Internet Explorer 8, this is equivalent to IE8 mode. If a (hypothetical) future release of Internet Explorer supported a higher compatibility mode, pages set to Edge mode would appear in the highest mode supported by that version; however, those same pages would still appear in IE8 mode when viewed with Internet Explorer 8.

However, "edge" mode is not encouraged in production use:

It is recommended that Web developers restrict their use of Edge mode to test pages and other non-production uses because of the possible unexpected results of rendering page content in future versions of Windows Internet Explorer.

I honestly don't entirely understand why. But according to this, the best way to go at the moment is using IE=8.

How to do the Recursive SELECT query in MySQL?

leftclickben answer worked for me, but I wanted a path from a given node back up the tree to the root, and these seemed to be going the other way, down the tree. So, I had to flip some of the fields around and renamed for clarity, and this works for me, in case this is what anyone else wants too--

item | parent
-------------
1    | null
2    | 1
3    | 1
4    | 2
5    | 4
6    | 3

and

select t.item_id as item, @pv:=t.parent as parent
from (select * from item_tree order by item_id desc) t
join
(select @pv:=6)tmp
where t.item_id=@pv;

gives:

item | parent
-------------
6    | 3
3    | 1
1    | null

Understanding the ngRepeat 'track by' expression

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

Typescript: How to extend two classes?

In design patterns there is a principle called "favouring composition over inheritance". It says instead of inheriting Class B from Class A ,put an instance of class A inside class B as a property and then you can use functionalities of class A inside class B. You can see some examples of that here and here.

how to remove multiple columns in r dataframe?

@Ahmed Elmahy following approach should help you out, when you have got a vector of column names you want to remove from your dataframe:

test_df <- data.frame(col1 = c("a", "b", "c", "d", "e"), col2 = seq(1, 5), col3 = rep(3, 5))
rm_col <- c("col2")
test_df[, !(colnames(test_df) %in% rm_col), drop = FALSE]

All the best, ExploreR

How to debug an apache virtual host configuration?

First check out config files for syntax errors with apachectl configtest and then look into apache error logs.

How to increase timeout for a single test case in mocha

You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. Using Sinon, you can decouple the app from the network service, focusing your development efforts.

jQuery Change event on an <input> element - any way to retain previous value?

Every DOM element has an attribute called defaultValue. You can use that to get the default value if you just want to compare the first changing of data.

Concatenating Files And Insert New Line In Between Files

You can do:

for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done

Make sure the file finalfile.txt does not exist before you run the above command.

If you are allowed to use awk you can do:

awk 'FNR==1{print ""}1' *.txt > finalfile.txt

makefile:4: *** missing separator. Stop

make has a very stupid relationship with tabs. All actions of every rule are identified by tabs. And, no, four spaces don't make a tab. Only a tab makes a tab.

To check, I use the command cat -e -t -v makefile_name.

It shows the presence of tabs with ^I and line endings with $. Both are vital to ensure that dependencies end properly and tabs mark the action for the rules so that they are easily identifiable to the make utility.

Example:

Kaizen ~/so_test $ cat -e -t -v  mk.t
all:ll$      ## here the $ is end of line ...                   
$
ll:ll.c   $
^Igcc  -c  -Wall -Werror -02 c.c ll.c  -o  ll  $@  $<$ 
## the ^I above means a tab was there before the action part, so this line is ok .
 $
clean :$
   \rm -fr ll$
## see here there is no ^I which means , tab is not present .... 
## in this case you need to open the file again and edit/ensure a tab 
## starts the action part

Install a Nuget package in Visual Studio Code

You can use the NuGet Package Manager extension.

After you've installed it, to add a package, press Ctrl+Shift+P, and type >nuget and press Enter:

enter image description here

Type a part of your package's name as search string:

enter image description here

Choose the package:

enter image description here

And finally the package version (you probably want the newest one):

enter image description here

How can I use JQuery to post JSON data?

I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data

$.fn.postJSON = function(url, data) {
    return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json'
        });

Center a column using Twitter Bootstrap 3

Try this code.

<body class="container">
    <div class="col-lg-1 col-lg-offset-10">
        <img data-src="holder.js/100x100" alt="" />
    </div>
</body>

Here I have used col-lg-1, and the offset should be 10 for properly centered the div on large devices. If you need it to center on medium-to-large devices then just change the lg to md and so on.

How do I activate a virtualenv inside PyCharm's terminal?

If your Pycharm 2016.1.4v and higher you should use "default path" /K "<path-to-your-activate.bat>" don't forget quotes

How to display tables on mobile using Bootstrap?

You might also consider trying one of these approaches, since larger tables aren't exactly friendly on mobile even if it works:

http://elvery.net/demo/responsive-tables/

I'm partial to 'No More Tables' but that obviously depends on your application.

Twitter Bootstrap: Print content of modal window

_x000D_
_x000D_
@media print{_x000D_
 body{_x000D_
  visibility: hidden; /* no print*/_x000D_
 }_x000D_
 .print{_x000D_
  _x000D_
  visibility:visible; /*print*/_x000D_
 }_x000D_
}
_x000D_
<body>_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="print">   <!---print--->_x000D_
  <div class="print">   <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

What is a 'NoneType' object?

NoneType is simply the type of the None singleton:

>>> type(None)
<type 'NoneType'>

From the latter link above:

None

The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.

In your case, it looks like one of the items you are trying to concatenate is None, hence your error.

How to set the opacity/alpha of a UIImage?

Swift 5:

extension UIImage {
  func withAlphaComponent(_ alpha: CGFloat) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(size, false, scale)
    defer { UIGraphicsEndImageContext() }

    draw(at: .zero, blendMode: .normal, alpha: alpha)
    return UIGraphicsGetImageFromCurrentImageContext()
  }
}

How do I use Linq to obtain a unique list of properties from a list of objects?

IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();

How to log in to phpMyAdmin with WAMP, what is the username and password?

I installed Bitnami WAMP Stack 7.1.29-0 and it asked for a password during installation. In this case it was

username: root
password: <password set by you during install>

How to make an element width: 100% minus padding?

You can try some positioning tricks. You can put the input in a div with position: relative and a fixed height, then on the input have position: absolute; left: 0; right: 0;, and any padding you like.

Live example

Show ProgressDialog Android

I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.

private class GetData extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = ProgressDialog.show(Calendar.this,
                    "", "");

        }

        @Override
        protected JSONObject doInBackground(String... params) {

            String response;

            try {

                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost(url);

                HttpResponse responce = httpclient.execute(httppost);

                HttpEntity httpEntity = responce.getEntity();

                response = EntityUtils.toString(httpEntity);

                Log.d("response is", response);

                return new JSONObject(response);

            } catch (Exception ex) {

                ex.printStackTrace();

            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) 
        {
            super.onPostExecute(result);

            progressDialog.dismiss();

            if(result != null)
            {
                try
                {
                    JSONObject jobj = result.getJSONObject("result");

                    String status = jobj.getString("status");

                    if(status.equals("true"))
                    {
                        JSONArray array = jobj.getJSONArray("data");

                        for(int x = 0; x < array.length(); x++)
                        {
                            HashMap<String, String> map = new HashMap<String, String>();

                            map.put("name", array.getJSONObject(x).getString("name"));

                            map.put("date", array.getJSONObject(x).getString("date"));

                            map.put("description", array.getJSONObject(x).getString("description"));

                            list.add(map);
                        }

                        CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);

                        list_of_calendar.setAdapter(adapter);
                    }
                }
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }
            else
            {
                Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
            }
        }

    }

and execute it in OnCreate Method like new GetData().execute();

where Calendar is my calendarActivity and i have also created a CalendarAdapter to set these values to a list view.

File size exceeds configured limit (2560000), code insight features not available

Changing the above options form Help menu didn't work for me. You have edit idea.properties file and change to some large no.

MAC: /Applications/<Android studio>.app/Contents/bin[Open App contents] 

Idea.max.intellisense.filesize=999999 

WINDOWS: IDE_HOME\bin\idea.properties

Accessing MP3 metadata with Python

easiest method is songdetails..

for read data

import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
    print song.artist

similarly for edit

import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
    song.artist = u"The Great Blah"
    song.save()

Don't forget to add u before name until you know chinese language.

u can read and edit in bulk using python glob module

ex.

import glob
songs = glob.glob('*')   # script should be in directory of songs.
for song in songs:
    # do the above work.

SQL query for getting data for last 3 months

Last 3 months

SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(mm,-3,GETDATE())),0)

Today

SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)

Comparing date part only without comparing time in JavaScript

After reading this question quite same time after it is posted I have decided to post another solution, as I didn't find it that quite satisfactory, at least to my needs:

I have used something like this:

var currentDate= new Date().setHours(0,0,0,0);

var startDay = new Date(currentDate - 86400000 * 2);
var finalDay = new Date(currentDate + 86400000 * 2);

In that way I could have used the dates in the format I wanted for processing afterwards. But this was only for my need, but I have decided to post it anyway, maybe it will help someone

Edittext change border color with shape.xml

i use as following for over come this matter

edittext_style.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="1dp"
        android:color="#c8c8c8"/>
<corners android:radius="0dp" />

And applied as bellow

<EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editTextName"
            android:background="@drawable/edit_text_style"/>

try like this..

how to print an exception using logger?

You should probably clarify which logger are you using.

org.apache.commons.logging.Log interface has method void error(Object message, Throwable t) (and method void info(Object message, Throwable t)), which logs the stack trace together with your custom message. Log4J implementation has this method too.

So, probably you need to write:

logger.error("BOOM!", e);

If you need to log it with INFO level (though, it might be a strange use case), then:

logger.info("Just a stack trace, nothing to worry about", e);

Hope it helps.

php mail setup in xampp

My favorite smtp server is hMailServer.

It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.

It can proxy through your gmail/yahoo/etc account or send email directly.

Once it is installed, email in xampp just works with no config changes.

document.getElementById('btnid').disabled is not working in firefox and chrome

use setAttribute() and removeAttribute()

function disbtn(e) { 
    if ( someCondition == true ) {
       document.getElementById('btn1').setAttribute("disabled","disabled");
    } else {
       document.getElementById('btn1').removeAttribute("disabled");
    }
}

SEE DEMO

Formatting a Date String in React Native

The beauty of the React Native is that it supports lots of JS libraries like Moment.js. Using moment.js would be a better/easier way to handle date/time instead coding from scratch

just run this in the terminal (yarn add moment also works if using React's built-in package manager):

npm install moment --save

And in your React Native js page:

import Moment from 'moment';

render(){
    Moment.locale('en');
    var dt = '2016-05-02T00:00:00';
    return(<View> {Moment(dt).format('d MMM')} </View>) //basically you can do all sorts of the formatting and others
}

You may check the moment.js official docs here https://momentjs.com/docs/

convert string to number node.js

Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

Answer is adding this 2 lines of code to Global.asax.cs Application_Start method

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All;

Reference: Handling Circular Object References

App.Config change value

You cannot use AppSettings static object for this. Try this

string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);          
string configFile = System.IO.Path.Combine(appPath, "App.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();         
configFileMap.ExeConfigFilename = configFile;          
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

config.AppSettings.Settings["YourThing"].Value = "New Value"; 
config.Save(); 

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Javascript Equivalent to C# LINQ Select

You can also try linq.js

In linq.js your

selectedFruits.select(fruit=>fruit.id);

will be

Enumerable.From(selectedFruits).Select(function (fruit) { return fruit.id;  });

module.exports vs. export default in Node.js and ES6

The issue is with

  • how ES6 modules are emulated in CommonJS
  • how you import the module

ES6 to CommonJS

At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?

Many people consider module.exports = ... to be equivalent to export default ... and exports.foo ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.

ES6 default exports are actually also named exports, except that default is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:

// input
export const foo = 42;
export default 21;

// output
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var foo = exports.foo = 42;
exports.default = 21; 

Here we can see that the default export becomes a property on the exports object, just like foo.

Import the module

We can import the module in two ways: Either using CommonJS or using ES6 import syntax.

Your issue: I believe you are doing something like:

var bar = require('./input');
new bar();

expecting that bar is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default property!

So in order to access the default export we actually have to do

var bar = require('./input').default;

If we use ES6 module syntax, namely

import bar from './input';
console.log(bar);

Babel will transform it to

'use strict';

var _input = require('./input');

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log(_input2.default);

You can see that every access to bar is converted to access .default.

How to change Hash values?

Try this function:

h = {"a" => "b", "c" => "d"}
h.each{|i,j| j.upcase!} # now contains {"a" => "B", "c" => "D"}.

List of all index & index columns in SQL Server DB

with connect(schema_name,table_name,index_name,index_column_id,column_name) as
(   select s.name schema_name, t.name table_name, i.name index_name, index_column_id, cast(c.name as varchar(max)) column_name
 from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id=i.index_id
        inner join sys.columns c on c.object_id = t.object_id and
                ic.column_id = c.column_id
                where index_column_id=1
union all
select s.name schema_name, t.name table_name, i.name index_name, ic.index_column_id, cast(connect.column_name + ',' + c.name as varchar(max)) column_name
 from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id=i.index_id
        inner join sys.columns c on c.object_id = t.object_id and
                ic.column_id = c.column_id join connect on
connect.index_column_id+1 = ic.index_column_id
and connect.schema_name = s.name
and connect.table_name = t.name
and connect.index_name = i.name)
select connect.schema_name,connect.table_name,connect.index_name,connect.column_name
from connect join (select schema_name,table_name,index_name,MAX(index_column_id) index_column_id
from connect group by schema_name,table_name,index_name) mx
on connect.schema_name = mx.schema_name
and connect.table_name = mx.table_name
and connect.index_name = mx.index_name
and connect.index_column_id = mx.index_column_id
order by 1,2,3

Why can't I change my input value in React even with the onChange listener

In React, the component will re-render (or update) only if the state or the prop changes.

In your case you have to update the state immediately after the change so that the component will re-render with the updates state value.

onTodoChange(event) {
        // update the state
    this.setState({name: event.target.value});
}

Multiple inputs with same name through POST in php

For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.

The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval] (string or int) which then allows you to refer to an existing record.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

This is how I managed to do what I was trying to do:

[Test]
public void TransferHandlesDisconnect()
{
    // ... set up config here
    var methodTester = new Mock<Transfer>(configInfo);
    methodTester.CallBase = true;
    methodTester
        .Setup(m => 
            m.GetFile(
                It.IsAny<IFileConnection>(), 
                It.IsAny<string>(), 
                It.IsAny<string>()
            ))
        .Throws<System.IO.IOException>();

    methodTester.Object.TransferFiles("foo1", "foo2");
    Assert.IsTrue(methodTester.Object.Status == TransferStatus.TransferInterrupted);
}

If there is a problem with this method, I would like to know; the other answers suggest I am doing this wrong, but this was exactly what I was trying to do.

Uncaught TypeError: Cannot read property 'split' of undefined

Your question answers itself ;) If og_date contains the date, it's probably a string, so og_date.value is undefined.

Simply use og_date.split('-') instead of og_date.value.split('-')

How to sort pandas data frame using values from several columns?

Use of sort can result in warning message. See github discussion. So you might wanna use sort_values, docs here

Then your code can look like this:

df = df.sort_values(by=['c1','c2'], ascending=[False,True])

getting a checkbox array value from POST

// if you do the input like this
<input id="'.$userid.'" value="'.$userid.'"  name="invite['.$userid.']" type="checkbox">

// you can access the value directly like this:
$invite = $_POST['invite'][$userid];

"This operation requires IIS integrated pipeline mode."

This error means the application pool to which your deployed application belongs is not in Integrated mode.

  1. Create a new application pool with .NET 4 version selected, and Managed Pipeline mode as Integrated.
  2. Change your application's app pool to the above created one and try now.

How to print Unicode character in Python?

Print a unicode character in Python:

Print a unicode character directly from python interpreter:

el@apollo:~$ python
Python 2.7.3
>>> print u'\u2713'
?

Unicode character u'\u2713' is a checkmark. The interpreter prints the checkmark on the screen.

Print a unicode character from a python script:

Put this in test.py:

#!/usr/bin/python
print("here is your checkmark: " + u'\u2713');

Run it like this:

el@apollo:~$ python test.py
here is your checkmark: ?

If it doesn't show a checkmark for you, then the problem could be elsewhere, like the terminal settings or something you are doing with stream redirection.

Store unicode characters in a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

When should I really use noexcept?

  1. There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?

noexcept is tricky, as it is part of the functions interface. Especially, if you are writing a library, your client code can depend on the noexcept property. It can be difficult to change it later, as you might break existing code. That might be less of a concern when you are implementing code that is only used by your application.

If you have a function that cannot throw, ask yourself whether it will like stay noexcept or would that restrict future implementations? For example, you might want to introduce error checking of illegal arguments by throwing exceptions (e.g., for unit tests), or you might depend on other library code that could change its exception specification. In that case, it is safer to be conservative and omit noexcept.

On the other hand, if you are confident that the function should never throw and it is correct that it is part of the specification, you should declare it noexcept. However, keep in mind that the compiler will not be able to detect violations of noexcept if your implementation changes.

  1. For which situations should I be more careful about the use of noexcept, and for which situations can I get away with the implied noexcept(false)?

There are four classes of functions that should you should concentrate on because they will likely have the biggest impact:

  1. move operations (move assignment operator and move constructors)
  2. swap operations
  3. memory deallocators (operator delete, operator delete[])
  4. destructors (though these are implicitly noexcept(true) unless you make them noexcept(false))

These functions should generally be noexcept, and it is most likely that library implementations can make use of the noexcept property. For example, std::vector can use non-throwing move operations without sacrificing strong exception guarantees. Otherwise, it will have to fall back to copying elements (as it did in C++98).

This kind of optimization is on the algorithmic level and does not rely on compiler optimizations. It can have a significant impact, especially if the elements are expensive to copy.

  1. When can I realistically expect to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

The advantage of noexcept against no exception specification or throw() is that the standard allows the compilers more freedom when it comes to stack unwinding. Even in the throw() case, the compiler has to completely unwind the stack (and it has to do it in the exact reverse order of the object constructions).

In the noexcept case, on the other hand, it is not required to do that. There is no requirement that the stack has to be unwound (but the compiler is still allowed to do it). That freedom allows further code optimization as it lowers the overhead of always being able to unwind the stack.

The related question about noexcept, stack unwinding and performance goes into more details about the overhead when stack unwinding is required.

I also recommend Scott Meyers book "Effective Modern C++", "Item 14: Declare functions noexcept if they won't emit exceptions" for further reading.

Django values_list vs values

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

Standard SQL provides the MERGE statement for this task. Not all DBMS support the MERGE statement.

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}

Does Python have a package/module management system?

It's called setuptools. You run it with the "easy_install" command.

You can find the directory at http://pypi.python.org/

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
{
    [XmlAttribute]
    public int Value { get; set; }
}

public class SomeStringInfo
{
    [XmlAttribute]
    public string Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeStringInfo SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeIntInfo SomeInfo { get; set; }
}

or a more generic approach if you prefer:

public class SomeInfo<T>
{
    [XmlAttribute]
    public T Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeInfo<string> SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeInfo<int> SomeInfo { get; set; }
}

And then:

class Program
{
    static void Main()
    {
        var model = new SomeModel
        {
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        };
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);
    }
}

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />
</SomeModel>

How do I connect to a specific Wi-Fi network in Android programmatically?

Try this method. It's very easy:

public static boolean setSsidAndPassword(Context context, String ssid, String ssidPassword) {
    try {
        WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
        Method getConfigMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
        WifiConfiguration wifiConfig = (WifiConfiguration) getConfigMethod.invoke(wifiManager);

        wifiConfig.SSID = ssid;
        wifiConfig.preSharedKey = ssidPassword;

        Method setConfigMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
        setConfigMethod.invoke(wifiManager, wifiConfig);

        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

Convert JS Object to form data

Sorry for a late answer, but I was struggling with this as Angular 2 currently does not support file upload. So, the way to do it was sending a XMLHttpRequest with FormData. So, I created a function to do it. I'm using Typescript. To convert it to Javascript just remove data types declaration.

/**
     * Transforms the json data into form data.
     *
     * Example:
     *
     * Input:
     * 
     * fd = new FormData();
     * dob = {
     *  name: 'phone',
     *  photos: ['myphoto.jpg', 'myotherphoto.png'],
     *  price: '615.99',
     *  color: {
     *      front: 'red',
     *      back: 'blue'
     *  },
     *  buttons: ['power', 'volup', 'voldown'],
     *  cameras: [{
     *      name: 'front',
     *      res: '5Mpx'
     *  },{
     *      name: 'back',
     *      res: '10Mpx'
     *  }]
     * };
     * Say we want to replace 'myotherphoto.png'. We'll have this 'fob'.
     * fob = {
     *  photos: [null, <File object>]
     * };
     * Say we want to wrap the object (Rails way):
     * p = 'product';
     *
     * Output:
     *
     * 'fd' object updated. Now it will have these key-values "<key>, <value>":
     *
     * product[name], phone
     * product[photos][], myphoto.jpg
     * product[photos][], <File object>
     * product[color][front], red
     * product[color][back], blue
     * product[buttons][], power
     * product[buttons][], volup
     * product[buttons][], voldown
     * product[cameras][][name], front
     * product[cameras][][res], 5Mpx
     * product[cameras][][name], back
     * product[cameras][][res], 10Mpx
     * 
     * @param {FormData}  fd  FormData object where items will be appended to.
     * @param {Object}    dob Data object where items will be read from.
     * @param {Object =   null} fob File object where items will override dob's.
     * @param {string =   ''} p Prefix. Useful for wrapping objects and necessary for internal use (as this is a recursive method).
     */
    append(fd: FormData, dob: Object, fob: Object = null, p: string = ''){
        let apnd = this.append;

        function isObj(dob, fob, p){
            if(typeof dob == "object"){
                if(!!dob && dob.constructor === Array){
                    p += '[]';
                    for(let i = 0; i < dob.length; i++){
                        let aux_fob = !!fob ? fob[i] : fob;
                        isObj(dob[i], aux_fob, p);
                    }
                } else {
                    apnd(fd, dob, fob, p);
                }
            } else {
                let value = !!fob ? fob : dob;
                fd.append(p, value);
            }
        }

        for(let prop in dob){
            let aux_p = p == '' ? prop : `${p}[${prop}]`;
            let aux_fob = !!fob ? fob[prop] : fob;
            isObj(dob[prop], aux_fob, aux_p);
        }
    }

How to change letter spacing in a Textview?

As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:

Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......

How to write to an existing excel file without overwriting data (using pandas)?

There is a better solution in pandas 0.24:

with pd.ExcelWriter(path, mode='a') as writer:
    s.to_excel(writer, sheet_name='another sheet', index=False)

before:

enter image description here

after:

enter image description here

so upgrade your pandas now:

pip install --upgrade pandas

jQuery disable a link

This works for links that have the onclick attribute set inline. This also allows you to later remove the "return false" in order to enable it.

        //disable all links matching class
        $('.yourLinkClass').each(function(index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", "return false; " + OnClickValue);
        });

        //enable all edit links
        $('.yourLinkClass').each(function (index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", OnClickValue.replace("return false; ", ""));
        });

Regex match one of two words

This will do:

/^(apple|banana)$/

to exclude from captured strings (e.g. $1,$2):

(?:apple|banana)

How to know if a Fragment is Visible?

If you want to know when use is looking at the fragment you should use

yourFragment.isResumed()

instead of

yourFragment.isVisible()

First of all isVisible() already checks for isAdded() so no need for calling both. Second, non-of these two means that user is actually seeing your fragment. Only isResumed() makes sure that your fragment is in front of the user and user can interact with it if thats whats you are looking for.

Append key/value pair to hash with << in Ruby

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}

Yahoo Finance All Currencies quote API Documentation

As NT3RP told us that:

... we (Yahoo!) don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service...

So I just thought of sharing this site with you:
http://josscrowcroft.github.com/open-exchange-rates/
[update: site has moved to - http://openexchangerates.org]

This site says:

No access fees, no rate limits, no ugly XML - just free, hourly updated exchange rates in JSON format
[update: Free for personal use, a bargain for your business.]

I hope I've helped and this is of some use to you (and others too). : )

What is “2's Complement”?

Two's complement is one of the way of expressing a negative number and most of the controllers and processors store a negative number in 2's complement form

Reading Excel files from C#

How about Excel Data Reader?

http://exceldatareader.codeplex.com/

I've used in it anger, in a production environment, to pull large amounts of data from a variety of Excel files into SQL Server Compact. It works very well and it's rather robust.

What is a reasonable length limit on person "Name" fields?

UK Government Data Standards Catalogue suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name.

Using column alias in WHERE clause of MySQL query produces an error

You can use SUBSTRING(locations.raw,-6,4) for where conditon

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE SUBSTRING(`locations`.`raw`,-6,4) NOT IN #this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
 'australia'
)
)

What is object slicing?

If You have a base class A and a derived class B, then You can do the following.

void wantAnA(A myA)
{
   // work with myA
}

B derived;
// work with the object "derived"
wantAnA(derived);

Now the method wantAnA needs a copy of derived. However, the object derived cannot be copied completely, as the class B could invent additional member variables which are not in its base class A.

Therefore, to call wantAnA, the compiler will "slice off" all additional members of the derived class. The result might be an object you did not want to create, because

  • it may be incomplete,
  • it behaves like an A-object (all special behaviour of the class B is lost).

Dark color scheme for Eclipse

As posted to a few related questions already, I'm working on a plugin for easy, cross-editor color theme management:

http://marketplace.eclipse.org/content/eclipse-color-theme

It is still work in progress, but already supports many editors and a few dark color themes.

C# looping through an array

Here is a more general solution:

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

}

How do I search for an object by its ObjectId in the mongo console?

In MongoDB Stitch functions it can be done using BSON like below:

Use the ObjectId helper in the BSON utility package for this purpose like in the follwing example:

var id = "5bb9e9f84186b222c8901149";  
BSON.ObjectId(id);

Check if all values in list are greater than a certain number

...any reason why you can't use min()?

def above(my_list, minimum):
    if min(my_list) >= minimum:
        print "All values are equal or above", minimum
    else:
        print "Not all values are equal or above", minimum

I don't know if this is exactly what you want, but technically, this is what you asked for...

Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

invalid use of non-static data member

In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. So bar::getA doesn't have any specific instance of foo whose a it can be returning. I'm guessing that what you want is something like:

    class bar {
      private:
        foo * const owner;
      public:
        bar(foo & owner) : owner(&owner) { }
        int getA() {return owner->a;}
    };

But even for this you may have to make some changes, because in versions of C++ before C++11, unlike (again, say) Java, a nested class has no special access to its enclosing class, so it can't see the protected member a. This will depend on your compiler version. (Hat-tip to Ken Wayne VanderLinde for pointing out that C++11 has changed this.)

Sublime Text 2: How to delete blank/empty lines

There's also "Join lines". If on OSX, select all your text, and press CMD-J a few times, and it will collapse your selection by line, removing the line breaks.

Edit: This approach will leave you with everything on one line, which is not what you asked for.

How to run Pip commands from CMD

Make sure to also add "C:\Python27\Scripts" to your path. pip.exe should be in that folder. Then you can just run:

C:\> pip install modulename

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

Functional, Declarative, and Imperative Programming

I think that your taxonomy is incorrect. There are two opposite types imperative and declarative. Functional is just a subtype of declarative. BTW, wikipedia states the same fact.

How to deny access to a file in .htaccess

Well you could use the <Directory> tag for example:

<Directory /inscription>
  <Files log.txt>
    Order allow,deny
    Deny from all
  </Files>
</Directory>

Do not use ./ because if you just use / it looks at the root directory of your site.

For a more detailed example visit http://httpd.apache.org/docs/2.2/sections.html

using c# .net libraries to check for IMAP messages from gmail servers

Cross posted from the other similar question. See what happens when they get so similar?

I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.

There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:

// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "[email protected]", "pass",
                ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
    Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();

I'm not affiliated with this library or anything, but I've found it very fast and stable.

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

Set Focus After Last Character in Text Box

<script type="text/javascript">
    $(function(){
        $('#areaCode,#firstNum,#secNum').keyup(function(e){
            if($(this).val().length==$(this).attr('maxlength'))
                $(this).next(':input').focus()
        })
    })
    </script>

<body>

<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />- 
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />- 
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />

</body>

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

How can I generate an ObjectId with mongoose?

With ES6 syntax

import mongoose from "mongoose";

// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

Add space between two particular <td>s

Try this Demo

HTML

<table>
    <tr>
        <td>One</td>
        <td>Two</td>
        <td>Three</td>
        <td>Four</td>
    </tr>
</table>

CSS

td:nth-of-type(2) {
   padding-right: 10px;
}

codeigniter, result() vs. result_array()

in my experince the problem using result() and result_array() in my JSON if using result() there no problem its works but if using result_array() i got error "Trying to get property of non-object" so im not search into deep the problem so i just using result() if using JSON and using result_array() if not using JSON

How to Flatten a Multidimensional Array?

This is my solution, using a reference:

function arrayFlatten($array_in, &$array_out){

    if(is_array($array_in)){
        foreach ($array_in as $element){
               arrayFlatten($element, $array_out);
        }
    }
    else{
        $array_out[] = $array_in; 
    }
}

$arr1 = array('1', '2', array(array(array('3'), '4', '5')), array(array('6')));

arrayFlatten($arr1, $arr2);

echo "<pre>";
print_r($arr2);
echo "</pre>";

What does @media screen and (max-width: 1024px) mean in CSS?

If your media query condition is true then your CSS with that condition will work. That means CSS within your media query's condition pixel size will effect, or else if the condition will fail that mean if the device's width is greater than 1024px than your CSS will not work.Because your media query condition false.

max-width is your max CSS limit till that width.

Where is my m2 folder on Mac OS X Mavericks

It's in your home folder but it's hidden by default.

Typing the below commands in the terminal made it visible for me (only the .m2 folder that is, not all the other hidden folders).

> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2         

Source

How to make a TextBox accept only alphabetic characters?

        if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]+$"))
        { 
        }
        else
        {
            textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
            MessageBox.Show("Enter only Alphabets");


        }

Please Try this

What does the fpermissive flag do?

The -fpermissive flag causes the compiler to report some things that are actually errors (but are permitted by some compilers) as warnings, to permit code to compile even if it doesn't conform to the language rules. You really should fix the underlying problem. Post the smallest, compilable code sample that demonstrates the problem.

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Add a UIView above all, even the navigation bar

There is more than one way to do it:

1- Add your UIView on UIWindow instead of adding it on UIViewController. This way it will be on top of everything.

   [[(AppDelegate *)[UIApplication sharedApplication].delegate window] addSubview:view];

2- Use custom transition that will keep your UIViewController showing in the back with a 0.5 alpha

For that I recommend you look at this: https://github.com/Citrrus/BlurryModalSegue

JavaScript + Unicode regexes

As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent XRegExp and its Unicode plug-in.

Getting Integer value from a String using javascript/jquery

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

yourString = yourString.replace ( /[^\d.]/g, '' );

your final code will be

  str1 = "test123.00".replace ( /[^\d.]/g, '' );
  str2 = "yes50.00".replace ( /[^\d.]/g, '' );
  total = parseInt(str1, 10) + parseInt(str2, 10);
  alert(total);

Demo

How is __eq__ handled in Python and in what order?

The a == b expression invokes A.__eq__, since it exists. Its code includes self.value == other. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__ to see if it knows how to compare itself to an int.

If you amend your code to show what values are being compared:

class A(object):
    def __eq__(self, other):
        print("A __eq__ called: %r == %r ?" % (self, other))
        return self.value == other
class B(object):
    def __eq__(self, other):
        print("B __eq__ called: %r == %r ?" % (self, other))
        return self.value == other

a = A()
a.value = 3
b = B()
b.value = 4
a == b

it will print:

A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?

How to embed images in email

Correct way of embedding images into Outlook and avoiding security problems is the next:

  1. Use interop for Outlook 2003;
  2. Create new email and set it save folder;
  3. Do not use base64 embedding, outlook 2007 does not support it; do not reference files on your disk, they won't be send; do not use word editor inspector because you will get security warnings on some machines;
  4. Attachment must have png/jpg extension. If it will have for instance tmp extension - Outlook will warn user;
  5. Pay attention how CID is generated without mapi;
  6. Do not access properties via getters or you will get security warnings on some machines.

    public static void PrepareEmail()
    {
        var attachFile = Path.Combine(
            Application.StartupPath, "mySuperImage.png"); // pay attention that image must not contain spaces, because Outlook cannot inline such images
    
        Microsoft.Office.Interop.Outlook.Application outlook = null;
        NameSpace space = null;
        MAPIFolder folder = null;
        MailItem mail = null;
        Attachment attachment = null;
        try
        {
            outlook = new Microsoft.Office.Interop.Outlook.Application();
            space = outlook.GetNamespace("MAPI");
            space.Logon(null, null, true, true);
    
            folder = space.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
            mail = (MailItem) outlook.CreateItem(OlItemType.olMailItem);
    
            mail.SaveSentMessageFolder = folder;
            mail.Subject = "Hi Everyone";
            mail.Attachments.Add(attachFile, OlAttachmentType.olByValue, 0, Type.Missing); 
            // Last Type.Missing - is for not to show attachment in attachments list.
    
            string attachmentId = Path.GetFileName(attachFile);
            mail.BodyFormat = OlBodyFormat.olFormatHTML;
    
             mail.HTMLBody = string.Format("<br/><img src=\'cid:{0}\' />", attachmentId);
    
            mail.Display(false);
        }
        finally
        {
            ReleaseComObject(outlook, space, folder, mail, attachment);
        }
    }
    

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!

One time page refresh after first page load

use this

<body onload =  "if (location.search.length < 1){window.location.reload()}">

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Running unittest with typical test directory structure

If you have multiple directories in your test directory, then you have to add to each directory an __init__.py file.

/home/johndoe/snakeoil
+-- test
    +-- __init__.py        
    +-- frontend
        +-- __init__.py
        +-- test_foo.py
    +-- backend
        +-- __init__.py
        +-- test_bar.py

Then to run every test at once, run:

python -m unittest discover -s /home/johndoe/snakeoil/test -t /home/johndoe/snakeoil

Source: python -m unittest -h

  -s START, --start-directory START
                        Directory to start discovery ('.' default)
  -t TOP, --top-level-directory TOP
                        Top level directory of project (defaults to start
                        directory)

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.