Programs & Examples On #Sharppcap

SharpPcap is a cross-platform packet capture framework for the .NET environment, based on the famous pcap / WinPcap libraries. It provides an API for capturing, injecting, analyzing and building packets using any .NET language such as C# and VB.NET.

How do I 'foreach' through a two-dimensional array?

Using LINQ you can do it like this:

var table_enum = table

    // Convert to IEnumerable<string>
    .OfType<string>()

    // Create anonymous type where Index1 and Index2
    // reflect the indices of the 2-dim. array
    .Select((_string, _index) => new {
        Index1 = (_index / 2),
        Index2 = (_index % 2), // ? I added this only for completeness
        Value = _string
    })

    // Group by Index1, which generates IEnmurable<string> for all Index1 values
    .GroupBy(v => v.Index1)

    // Convert all Groups of anonymous type to String-Arrays
    .Select(group => group.Select(v => v.Value).ToArray());

// Now you can use the foreach-Loop as you planned
foreach(string[] str_arr in table_enum) {
    // …
}

This way it is also possible to use the foreach for looping through the columns instead of the rows by using Index2 in the GroupBy instead of Index 1. If you don't know the dimension of your array then you have to use the GetLength() method to determine the dimension and use that value in the quotient.

Mongoose and multiple database in single node.js project

According to the fine manual, createConnection() can be used to connect to multiple databases.

However, you need to create separate models for each connection/database:

var conn      = mongoose.createConnection('mongodb://localhost/testA');
var conn2     = mongoose.createConnection('mongodb://localhost/testB');

// stored in 'testA' database
var ModelA    = conn.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testA database' }
}));

// stored in 'testB' database
var ModelB    = conn2.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testB database' }
}));

I'm pretty sure that you can share the schema between them, but you have to check to make sure.

FIFO based Queue implementations?

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

1
2

Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.

So this is a Queue only if used in conjunction with add.

Try this :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

2
1

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

Is it wrong to place the <script> tag after the </body> tag?

Modern browsers will take script tags in the body like so:

<body>
    <script src="scripts/main.js"></script>
</body>

Basically, it means that the script will be loaded once the page has finished, which may be useful in certain cases (namely DOM manipulation). However, I highly recommend you take the same script and put it in the head tag with "defer", as it will give the same effect.

<head>
    <script src="scripts/main.js" defer></script>
</head>

How to fetch all Git branches

Set alias: (based on the top answer)

git config --global alias.track-all-branches '!git fetch --all && for remote in `git branch -r`; do git branch --track ${remote#origin/} $remote; done && git fetch --all'

Now to track all the branches:

git track-all-branches

How to get a web page's source code from Java

Try the following code with an added request property:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class SocketConnection
{
    public static String getURLSource(String url) throws IOException
    {
        URL urlObject = new URL(url);
        URLConnection urlConnection = urlObject.openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

        return toString(urlConnection.getInputStream());
    }

    private static String toString(InputStream inputStream) throws IOException
    {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
        {
            String inputLine;
            StringBuilder stringBuilder = new StringBuilder();
            while ((inputLine = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(inputLine);
            }

            return stringBuilder.toString();
        }
    }
}

How to Completely Uninstall Xcode and Clear All Settings

For a complete removal of Xcode 10 delete the following:

  1. /Applications/Xcode.app
  2. ~/Library/Caches/com.apple.dt.Xcode
  3. ~/Library/Developer
  4. ~/Library/MobileDevice
  5. ~/Library/Preferences/com.apple.dt.Xcode.plist
  6. /Library/Preferences/com.apple.dt.Xcode.plist
  7. /System/Library/Receipts/com.apple.pkg.XcodeExtensionSupport.bom
  8. /System/Library/Receipts/com.apple.pkg.XcodeExtensionSupport.plist
  9. /System/Library/Receipts/com.apple.pkg.XcodeSystemResources.bom
  10. /System/Library/Receipts/com.apple.pkg.XcodeSystemResources.plist
  11. /private/var/db/receipts/com.apple.pkg.Xcode.bom

But instead of 11, open up /private/var/in the Finder and search for "Xcode" to see all the 'dna' left behind... and selectively clean that out too. I would post the pathnames but they will include randomized folder names which will not be the same from my Mac to yours.

but if you don't want to lose all of your customizations, consider saving these files or folders before deleting anything:

  1. ~/Library/Developer/Xcode/UserData/CodeSnippets
  2. ~/Library/Developer/Xcode/UserData/FontAndColorThemes
  3. ~/Library/Developer/Xcode/UserData/KeyBindings
  4. ~/Library/Developer/Xcode/Templates
  5. ~/Library/Preferences/com.apple.dt.Xcode.plist
  6. ~/Library/MobileDevice/Provisioning Profiles

bootstrap 3 - how do I place the brand in the center of the navbar?

If you have no other links, then there is no use for navbar-header....

HTML:

<nav class="navbar navbar-inverse navbar-static-top">
    <div class="container">
     <a class="navbar-brand text-center center-block" href="#">Navbar Brand</a>
  .....
</nav>

CSS:

.navbar-brand {
  float: none;
}


However, if you do want other links here's a very effective approach that allows that: https://stackoverflow.com/a/34149840/3123861

Is calling destructor manually always a sign of bad design?

I have never come across a situation where one needs to call a destructor manually. I seem to remember even Stroustrup claims it is bad practice.

Regex Match all characters between two strings

Sublime Text 3x

In sublime text, you simply write the two word you are interested in keeping for example in your case it is

"This is" and "sentence"

and you write .* in between

i.e. This is .* sentence

and this should do you well

How to compare arrays in C#?

You're comparing the object references, and they are not the same. You need to compare the array contents.

.NET2 solution

An option is iterating through the array elements and call Equals() for each element. Remember that you need to override the Equals() method for the array elements, if they are not the same object reference.

An alternative is using this generic method to compare two generic arrays:

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1, a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    var comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}

.NET 3.5 or higher solution

Or use SequenceEqual if Linq is available for you (.NET Framework >= 3.5)

Unable to merge dex

Deleting .gradle as suggested by Suragch wasn't enough for me. Additionally, I had to perform a Build > Clean Project.

Note that, in order to see .gradle, you need to switch to the "Project" view in the navigator on the top left:

Switch to project view

How to add a browser tab icon (favicon) for a website?

There are actually two ways to add a favicon to a website.

<link rel="icon">

Simply add the following code to the <head> element:

<link rel="icon" href="http://example.com/favicon.png">

PNG favicons are supported by most browsers, except IE <= 10. For backwards compatibility, you can use ICO favicons.

Note that you don't have to precede icon in rel attribute with shortcut anymore. From MDN Link types:

The shortcut link type is often seen before icon, but this link type is non-conforming, ignored and web authors must not use it anymore.

favicon.ico in the root directory

From another SO answer (by @mercator):

All modern browsers (tested with Chrome 4, Firefox 3.5, IE8, Opera 10 and Safari 4) will always request a favicon.ico unless you've specified a shortcut icon via <link>.

So all you have to do is to make the /favicon.ico request to your website return your favicon. This option unfortunately doesn't allow you to use a PNG icon.

See also favicon.png vs favicon.ico - why should I use PNG instead of ICO?

Hide Twitter Bootstrap nav collapse on click

I just replicate the 2 attributes of the btn-navbar (data-toggle="collapse" data-target=".nav-collapse.in") on each link like this:

<div class="nav-collapse">
  <ul class="nav" >
    <li class="active"><a href="#home" data-toggle="collapse" data-target=".nav-collapse.in">Home</a></li>
    <li><a href="#about" data-toggle="collapse" data-target=".nav-collapse.in">About</a></li>
    <li><a href="#portfolio" data-toggle="collapse" data-target=".nav-collapse.in">Portfolio</a></li>
    <li><a href="#services" data-toggle="collapse" data-target=".nav-collapse.in">Services</a></li>
    <li><a href="#contact" data-toggle="collapse" data-target=".nav-collapse.in">Contact</a></li>
  </ul>
</div>

In the Bootstrap 4 Navbar, in has changed to show so the syntax would be:

data-toggle="collapse" data-target=".navbar-collapse.show"

How do I group Windows Form radio buttons?

I like the concept of grouping RadioButtons in WPF. There is a property GroupName that specifies which RadioButton controls are mutually exclusive (http://msdn.microsoft.com/de-de/library/system.windows.controls.radiobutton.aspx).

So I wrote a derived class for WinForms that supports this feature:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.ComponentModel;

namespace Use.your.own
{
    public class AdvancedRadioButton : CheckBox
    {
        public enum Level { Parent, Form };

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the level that specifies which RadioButton controls are affected."),
        DefaultValue(Level.Parent)]
        public Level GroupNameLevel { get; set; }

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the name that specifies which RadioButton controls are mutually exclusive.")]
        public string GroupName { get; set; }

        protected override void OnCheckedChanged(EventArgs e)
        {
            base.OnCheckedChanged(e);

            if (Checked)
            {
                var arbControls = (dynamic)null;
                switch (GroupNameLevel)
                {
                    case Level.Parent:
                        if (this.Parent != null)
                            arbControls = GetAll(this.Parent, typeof(AdvancedRadioButton));
                        break;
                    case Level.Form:
                        Form form = this.FindForm();
                        if (form != null)
                            arbControls = GetAll(this.FindForm(), typeof(AdvancedRadioButton));
                        break;
                }
                if (arbControls != null)
                    foreach (Control control in arbControls)
                        if (control != this &&
                            (control as AdvancedRadioButton).GroupName == this.GroupName)
                            (control as AdvancedRadioButton).Checked = false;
            }
        }

        protected override void OnClick(EventArgs e)
        {
            if (!Checked)
                base.OnClick(e);
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            CheckBoxRenderer.DrawParentBackground(pevent.Graphics, pevent.ClipRectangle, this);

            RadioButtonState radioButtonState;
            if (Checked)
            {
                radioButtonState = RadioButtonState.CheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.CheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.CheckedDisabled;
            }
            else
            {
                radioButtonState = RadioButtonState.UncheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.UncheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.UncheckedDisabled;
            }

            Size glyphSize = RadioButtonRenderer.GetGlyphSize(pevent.Graphics, radioButtonState);
            Rectangle rect = pevent.ClipRectangle;
            rect.Width -= glyphSize.Width;
            rect.Location = new Point(rect.Left + glyphSize.Width, rect.Top);

            RadioButtonRenderer.DrawRadioButton(pevent.Graphics, new System.Drawing.Point(0, rect.Height / 2 - glyphSize.Height / 2), rect, this.Text, this.Font, this.Focused, radioButtonState);
        }

        private IEnumerable<Control> GetAll(Control control, Type type)
        {
            var controls = control.Controls.Cast<Control>();

            return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Concat(controls)
                                      .Where(c => c.GetType() == type);
        }
    }
}

Removing pip's cache?

On Ubuntu, I had to delete /tmp/pip-build-root.

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

Setting the classpath in java using Eclipse IDE

You can create new User library,

On

"Configure Build Paths" page -> Add Library -> User Library (on list) -> User Libraries Button (rigth side of page)

and create your library and (add Jars buttons) include your specific Jars.

I hope this can help you.

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

Create a one to many relationship using SQL Server

If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId. If this is not what you are looking for, please elaborate your question.

How to convert a Scikit-learn dataset to a Pandas dataset?

Took me 2 hours to figure this out

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
##iris.keys()


df= pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])

df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)

Get back the species for my pandas

Can't type in React input text field

You haven't properly cased your onchange prop in the input. It needs to be onChange in JSX.

<input
  type="text"
  value={this.props.searchString}
  ref="searchStringInput"
  onchange={this.handleChange} <--[should be onChange]
/>  

The topic of passing a value prop to an <input>, and then somehow changing the value passed in response to user interaction using an onChange handler is pretty well-considered in the docs.

They refer to such inputs as Controlled Components, and refer to inputs that instead let the DOM natively handle the input's value and subsequent changes from the user as Uncontrolled Components.

Whenever you set the value prop of an input to some variable, you have a Controlled Component. This means you must change the value of the variable by some programmatic means or else the input will always hold that value and will never change, even when you type -- the native behaviour of the input, to update its value on typing, is overridden by React here.

So, you're correctly taking that variable from state, and have a handler to update the state all set up fine. The problem was because you have onchange and not the correct onChange the handler was never being called and so the value was never being updated when you type into the input. When you do use onChange the handler is called, the value is updated when you type, and you see your changes.

Is there a Google Voice API?

Well... These are PHP. There is an sms one from google here.

And github has one here.

Another sms one is here. However, this one has a lot more code, so it may take up more space.

Order of execution of tests in TestNG

I've faced the same issue, the possible reason is due to parallel execution of testng and the solution is to add Priority option or simply update preserve-order="true" in your testng.xml.

<test name="Firefox Test" preserve-order="true">

Include jQuery in the JavaScript Console

this answer based on @genesis answer, at first I tried the bookmark version @jondavidjohn, and it is not working, so I change it to this (add it to your bookmark):

javascript:(function(){var s = document.createElement('script');s.src = "//code.jquery.com/jquery-2.2.4.min.js";document.getElementsByTagName('head')[0].appendChild(s);console.log('jquery loaded')}());

words of caution, is not tested in chrome but work in firefox, and not tested in conflict environment.

JavaScript require() on client side

I asked myself the very same questions. When I looked into it I found the choices overwhelming.

Fortunately I found this excellent spreadsheet that helps you choice the best loader based on your requirements:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ

How to add the text "ON" and "OFF" to toggle button

_x000D_
_x000D_
.switch {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  width: 90px;_x000D_
  height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  background-color: #ca2222;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  height: 26px;_x000D_
  width: 26px;_x000D_
  left: 4px;_x000D_
  bottom: 4px;_x000D_
  background-color: white;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
  background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
  box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
  -webkit-transform: translateX(55px);_x000D_
  -ms-transform: translateX(55px);_x000D_
  transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
  color: white;_x000D_
  position: absolute;_x000D_
  transform: translate(-50%,-50%);_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  font-size: 10px;_x000D_
  font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
  border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
  border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
_x000D_
_x000D_

Python reading from a file and saving to utf-8

Process text to and from Unicode at the I/O boundaries of your program using open with the encoding parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False) is the encoding used), so I recommend always explicitly using the encoding parameter for portability and clarity (Python 3 syntax below):

with open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with open(filename, 'w', encoding='utf8') as f:
    f.write(text)

If still using Python 2 or for Python 2/3 compatibility, the io module implements open with the same semantics as Python 3's open and exists in both versions:

import io
with io.open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with io.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE DATE_FORMAT(startTime, "%Y-%m-%d") = '2010-04-29'"

OR

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'

How to get current date in jquery?

The jQuery plugin page is down. So manually:

function strpad00(s)
{
    s = s + '';
    if (s.length === 1) s = '0'+s;
    return s;
}

var now = new Date();
var currentDate = now.getFullYear()+ "/" + strpad00(now.getMonth()+1) + "/" + strpad00(now.getDate());
console.log(currentDate );

How do I call a dynamically-named method in Javascript?

I would recommend NOT to use global / window / eval for this purpose.
Instead, do it this way:

define all methods as properties of Handler:

var Handler={};

Handler.application_run = function (name) {
console.log(name)
}

Now call it like this

var somefunc = "application_run";
Handler[somefunc]('jerry');

Output: jerry


Case when importing functions from different files

import { func1, func2 } from "../utility";

const Handler= {
  func1,
  func2
};

Handler["func1"]("sic mundus");
Handler["func2"]("creatus est");

What is a daemon thread in Java?

Java has a special kind of thread called daemon thread.

  • Very low priority.
  • Only executes when no other thread of the same program is running.
  • JVM ends the program finishing these threads, when daemon threads are the only threads running in a program.

What are daemon threads used for?

Normally used as service providers for normal threads. Usually have an infinite loop that waits for the service request or performs the tasks of the thread. They can’t do important jobs. (Because we don't know when they are going to have CPU time and they can finish any time if there aren't any other threads running. )

A typical example of these kind of threads is the Java garbage collector.

There's more...

  • You only call the setDaemon() method before you call the start() method. Once the thread is running, you can’t modify its daemon status.
  • Use isDaemon() method to check if a thread is a daemon thread or a user thread.

how to configure apache server to talk to HTTPS backend server?

Your server tells you exactly what you need : [Hint: SSLProxyEngine]

You need to add that directive to your VirtualHost before the Proxy directives :

SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/

See the doc for more detail.

JQuery DatePicker ReadOnly

      beforeShow: function(el) {
            if ( el.getAttribute("readonly") !== null ) {
                if ( (el.value == null) || (el.value == '') ) {
                    $(el).datepicker( "option", "minDate", +1 );
                    $(el).datepicker( "option", "maxDate", -1 );
                } else {
                    $(el).datepicker( "option", "minDate", el.value );
                    $(el).datepicker( "option", "maxDate", el.value );
                }
            }
        },

Enum Naming Convention - Plural

If you are trying to write straightforward, yet forbidden code like this:

    public class Person
    {
        public enum Gender
        {
            Male,
            Female
        }
        //Won't compile: auto-property has same name as enum
        public Gender Gender { get; set; }  
    }

Your options are:

  1. Ignore the MS recommendation and use a prefix or suffix on the enum name:

    public class Person
    {
        public enum GenderEnum
        {
            Male,
            Female
        }
        public GenderEnum Gender { get; set; }
    }
    
  2. Move the enum definition outside the class, preferably into another class. Here is an easy solution to the above:

    public class Characteristics
    {
        public enum Gender
        {
            Male,
            Female
        }
    }
    public class Person
    {
        public Characteristics.Gender Gender { get; set; }  
    }
    

How to simulate target="_blank" in JavaScript

I personally prefer using the following code if it is for a single link. Otherwise it's probably best if you create a function with similar code.

onclick="this.target='_blank';"

I started using that to bypass the W3C's XHTML strict test.

How to find sum of multiple columns in a table in SQL Server 2005?

Another example using COALESCE. http://sqlmag.com/t-sql/coalesce-vs-isnull

SELECT (COALESCE(SUM(val1),0) + COALESCE(SUM(val2), 0)
+ COALESCE(SUM(val3), 0) + COALESCE(SUM(val4), 0)) AS 'TOTAL'
FROM Emp

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

Wait a few minutes. The application will start automatically

What is the Python equivalent of static variables inside a function?

Building on Daniel's answer (additions):

class Foo(object): 
    counter = 0  

def __call__(self, inc_value=0):
    Foo.counter += inc_value
    return Foo.counter

foo = Foo()

def use_foo(x,y):
    if(x==5):
        foo(2)
    elif(y==7):
        foo(3)
    if(foo() == 10):
        print("yello")


use_foo(5,1)
use_foo(5,1)
use_foo(1,7)
use_foo(1,7)
use_foo(1,1)

The reason why I wanted to add this part is , static variables are used not only for incrementing by some value, but also check if the static var is equal to some value, as a real life example.

The static variable is still protected and used only within the scope of the function use_foo()

In this example, call to foo() functions exactly as(with respect to the corresponding c++ equivalent) :

stat_c +=9; // in c++
foo(9)  #python equiv

if(stat_c==10){ //do something}  // c++

if(foo() == 10):      # python equiv
  #add code here      # python equiv       

Output :
yello
yello

if class Foo is defined restrictively as a singleton class, that would be ideal. This would make it more pythonic.

How can I create persistent cookies in ASP.NET?

//add cookie

var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(panelIdCookie);

//read cookie

    var httpCookie = Request.Cookies["panelIdCookie"];
                if (httpCookie != null)
                {
                    panelId = Convert.ToInt32(httpCookie["panelId"]);
                }

Set max-height on inner div so scroll bars appear, but not on parent div

It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:

function SetHeight(){
    var h = $(window).height();
    $("#inner-right").height(h-200);    
}

$(document).ready(SetHeight);
$(window).resize(SetHeight);

Google Maps: How to create a custom InfoWindow?

I'm not sure how FWIX.com is doing it specifically, but I'd wager they are using Custom Overlays.

How to round an image with Glide library?

Here is a more modular and cleaner way to circle crop your bitmap in Glide:

  1. Create a custom transformation by extending BitmapTransformation then override transform method like this :

For Glide 4.x.x

public class CircularTransformation extends BitmapTransformation {

@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
    RoundedBitmapDrawable circularBitmapDrawable =
            RoundedBitmapDrawableFactory.create(null, toTransform);
    circularBitmapDrawable.setCircular(true);
    Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
    circularBitmapDrawable.draw(canvas);
    return bitmap;
    }

@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {}

}

For Glide 3.x.x

public class CircularTransformation extends BitmapTransformation {

@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
    RoundedBitmapDrawable circularBitmapDrawable =
            RoundedBitmapDrawableFactory.create(null, toTransform);
    circularBitmapDrawable.setCircular(true);
    Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
    circularBitmapDrawable.draw(canvas);
    return bitmap;
    }

@Override
public String getId() {
    // Return some id that uniquely identifies your transformation.
    return "CircularTransformation";
    }

}
  1. Then set it in Glide builder where you need it:
Glide.with(yourActivity)
   .load(yourUrl)
   .asBitmap()
   .transform(new CircularTransformation())
   .into(yourView);

Hope this helps :)

Understanding timedelta

why do I have to pass seconds = uptime to timedelta

Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int is superfluous as they could also accept floats.

and why does the string casting works so nicely that I get HH:MM:SS ?

It's not the typecasting that formats, is the internal __str__ method of the object. In fact you will achieve the same result if you write:

print datetime.timedelta(seconds=int(uptime))

Finding the number of days between two dates

$datediff = floor(strtotime($date1)/(60*60*24)) - floor(strtotime($date2)/(60*60*24));

and, if needed:

$datediff=abs($datediff);

How to use View.OnTouchListener instead of onClick

Presumably, if one wants to use an OnTouchListener rather than an OnClickListener, then the extra functionality of the OnTouchListener is needed. This is a supplemental answer to show more detail of how an OnTouchListener can be used.

Define the listener

Put this somewhere in your activity or fragment.

private View.OnTouchListener handleTouch = new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i("TAG", "touched down");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i("TAG", "moving: (" + x + ", " + y + ")");
                break;
            case MotionEvent.ACTION_UP:
                Log.i("TAG", "touched up");
                break;
        }

        return true;
    }
};

Set the listener

Set the listener in onCreate (for an Activity) or onCreateView (for a Fragment).

myView.setOnTouchListener(handleTouch);

Notes

  • getX and getY give you the coordinates relative to the view (that is, the top left corner of the view). They will be negative when moving above or to the left of your view. Use getRawX and getRawY if you want the absolute screen coordinates.
  • You can use the x and y values to determine things like swipe direction.

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

Correct way to load a Nib for a UIView subclass

Follow the following steps

  1. Create a class named MyView .h/.m of type UIView.
  2. Create a xib of same name MyView.xib.
  3. Now change the File Owner class to UIViewController from NSObject in xib. See the image below enter image description here
  4. Connect the File Owner View to your View. See the image below enter image description here

  5. Change the class of your View to MyView. Same as 3.

  6. Place controls create IBOutlets.

Here is the code to load the View:

UIViewController *controller=[[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];
MyView* view=(MyView*)controller.view;
[self.view addSubview:myview];

Hope it helps.

Clarification:

UIViewController is used to load your xib and the View which the UIViewController has is actually MyView which you have assigned in the MyView xib..

Demo I have made a demo grab here

How to set tint for an image view programmatically in android?

In case you want to set selector to your tint:

ImageViewCompat.setImageTintList(iv, getResources().getColorStateList(R.color.app_icon_click_color));

How to fix IndexError: invalid index to scalar variable

In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.

How to add parameters into a WebRequest?

For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.

Node.js fs.readdir recursive directory search

This is my answer. Hope it can help somebody.

My focus is to make the searching routine can stop at anywhere, and for a file found, tells the relative depth to the original path.

var _fs = require('fs');
var _path = require('path');
var _defer = process.nextTick;

// next() will pop the first element from an array and return it, together with
// the recursive depth and the container array of the element. i.e. If the first
// element is an array, it'll be dug into recursively. But if the first element is
// an empty array, it'll be simply popped and ignored.
// e.g. If the original array is [1,[2],3], next() will return [1,0,[[2],3]], and
// the array becomes [[2],3]. If the array is [[[],[1,2],3],4], next() will return
// [1,2,[2]], and the array becomes [[[2],3],4].
// There is an infinity loop `while(true) {...}`, because I optimized the code to
// make it a non-recursive version.
var next = function(c) {
    var a = c;
    var n = 0;
    while (true) {
        if (a.length == 0) return null;
        var x = a[0];
        if (x.constructor == Array) {
            if (x.length > 0) {
                a = x;
                ++n;
            } else {
                a.shift();
                a = c;
                n = 0;
            }
        } else {
            a.shift();
            return [x, n, a];
        }
    }
}

// cb is the callback function, it have four arguments:
//    1) an error object if any exception happens;
//    2) a path name, may be a directory or a file;
//    3) a flag, `true` means directory, and `false` means file;
//    4) a zero-based number indicates the depth relative to the original path.
// cb should return a state value to tell whether the searching routine should
// continue: `true` means it should continue; `false` means it should stop here;
// but for a directory, there is a third state `null`, means it should do not
// dig into the directory and continue searching the next file.
var ls = function(path, cb) {
    // use `_path.resolve()` to correctly handle '.' and '..'.
    var c = [ _path.resolve(path) ];
    var f = function() {
        var p = next(c);
        p && s(p);
    };
    var s = function(p) {
        _fs.stat(p[0], function(err, ss) {
            if (err) {
                // use `_defer()` to turn a recursive call into a non-recursive call.
                cb(err, p[0], null, p[1]) && _defer(f);
            } else if (ss.isDirectory()) {
                var y = cb(null, p[0], true, p[1]);
                if (y) r(p);
                else if (y == null) _defer(f);
            } else {
                cb(null, p[0], false, p[1]) && _defer(f);
            }
        });
    };
    var r = function(p) {
        _fs.readdir(p[0], function(err, files) {
            if (err) {
                cb(err, p[0], true, p[1]) && _defer(f);
            } else {
                // not use `Array.prototype.map()` because we can make each change on site.
                for (var i = 0; i < files.length; i++) {
                    files[i] = _path.join(p[0], files[i]);
                }
                p[2].unshift(files);
                _defer(f);
            }
        });
    }
    _defer(f);
};

var printfile = function(err, file, isdir, n) {
    if (err) {
        console.log('-->   ' + ('[' + n + '] ') + file + ': ' + err);
        return true;
    } else {
        console.log('... ' + ('[' + n + '] ') + (isdir ? 'D' : 'F') + ' ' + file);
        return true;
    }
};

var path = process.argv[2];
ls(path, printfile);

how to setup ssh keys for jenkins to publish via ssh

For Windows:

  1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
  2. You can generate a key with Putty key generator, or by running the following command in git bash: $ ssh-keygen -t rsa -b 4096 -C [email protected]
  3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
  4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
  5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

413 Request Entity Too Large - File Upload Issue

I add the changes directly to my virtualhost instead the global config of nginx, like this:

   server {
     client_max_body_size 100M;
     ...
   }

And then I change the params in php.ini, like the comments above:

   max_input_time = 24000
   max_execution_time = 24000
   upload_max_filesize = 12000M
   post_max_size = 24000M
   memory_limit = 12000M

and what you can not forget is to restart nginx and php-fpm, in centos 7 is like this:

  systemctl restart nginx
  systemctl restart php-fpm

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Passing just a type as a parameter in C#

You can use an argument of type Type - iow, pass typeof(int). You can also use generics for a (probably more efficient) approach.

How to execute .sql file using powershell?

with 2008 Server 2008 and 2008 R2

Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100

with 2012 and 2014

Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location

how to use "AND", "OR" for RewriteCond on Apache?

Having trouble wrapping my head around this.

Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D

RewriteCond A       true
RewriteCond B       false
RewriteCond C [OR]  true
RewriteCond D       true
RewriteRule ...

But that seems to be an expression of A and B and (C or D) = false (don't rewrite)

How can I get to the desired expression? (A and B and C) or D = true (rewrite)

Preferably without using the additional steps of setting environment variables.

HELP!!!

How to disable CSS in Browser for testing purposes

I tried in Chrome Developer tools and the method is valid only if the CSS are included as external files and it won't work for inline styles.

Array.prototype.forEach.call(document.querySelectorAll('link'), (element)=>element.remove());

Or

var linkElements = document.querySelectorAll('link');
Array.prototype.forEach.call(linkElements, (element)=>element.remove());

Explanations

  1. document.querySelectorAll('link') gets all the link nodes. This will return array of DOM elements. Note that this is not Array object of javascript.
  2. Array.prototype.forEach.call(linkElements loops through the link elements
  3. element.remove() removes the element from the DOM

Resulting in plain HTML page

Why should I use an IDE?

Saves time to develop
Makes life easier by providing features like Integrated debugging, intellisense.

There are lot many, but will recommend to use one, they are more than obvious.

How to remove item from a python list in a loop?

x = [i for i in x if len(i)==2]

Reflection - get attribute name and value on property

Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttributes() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.

Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):

public static Dictionary<string, string> GetAuthors()
{
    Dictionary<string, string> _dict = new Dictionary<string, string>();

    PropertyInfo[] props = typeof(Book).GetProperties();
    foreach (PropertyInfo prop in props)
    {
        object[] attrs = prop.GetCustomAttributes(true);
        foreach (object attr in attrs)
        {
            AuthorAttribute authAttr = attr as AuthorAttribute;
            if (authAttr != null)
            {
                string propName = prop.Name;
                string auth = authAttr.Name;

                _dict.Add(propName, auth);
            }
        }
    }

    return _dict;
}

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

In motherland Russia we have 4 popular encodings, so your question is in great demand here.

Only by char codes of symbols you can not detect encoding, because code pages intersect. Some codepages in different languages have even full intersection. So, we need another approach.

The only way to work with unknown encodings is working with probabilities. So, we do not want to answer the question "what is encoding of this text?", we are trying to understand "what is most likely encoding of this text?".

One guy here in popular Russian tech blog invented this approach:

Build the probability range of char codes in every encoding you want to support. You can build it using some big texts in your language (e.g. some fiction, use Shakespeare for english and Tolstoy for russian, lol ). You will get smth like this:

    encoding_1:
    190 => 0.095249209893009,
    222 => 0.095249209893009,
    ...
    encoding_2:
    239 => 0.095249209893009,
    207 => 0.095249209893009,
    ...
    encoding_N:
    charcode => probabilty

Next. You take text in unknown encoding and for every encoding in your "probability dictionary" you search for frequency of every symbol in unknown-encoded text. Sum probabilities of symbols. Encoding with bigger rating is likely the winner. Better results for bigger texts.

If you are interested, I can gladly help you with this task. We can greatly increase the accuracy by building two-charcodes probabilty list.

Btw. mb_detect_encoding certanly does not work. Yes, at all. Please, take a look of mb_detect_encoding source code in "ext/mbstring/libmbfl/mbfl/mbfl_ident.c".

Visual Studio Code includePath

This answer maybe late but I just happened to fix the issue. Here is my c_cpp_properties.json file:

{
"configurations": [
    {
        "name": "Linux",
        "includePath": [
            "${workspaceFolder}/**",                
            "/usr/include/c++/5.4.0/",
            "usr/local/include/",
            "usr/include/"
        ],
        "defines": [],
        "compilerPath": "/usr/bin/gcc",
        "cStandard": "c11",
        "cppStandard": "c++14",
        "intelliSenseMode": "clang-x64"
    }
],
"version": 4

}

libstdc++.so.6: cannot open shared object file: No such file or directory

For Fedora use:

yum install libstdc++44.i686

You can find out which versions are supported by running:

yum list all | grep libstdc | grep i686

CSS3 Transition - Fade out effect

You forgot to add a position property to the .dummy-wrap class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)

http://jsfiddle.net/dYBD2/2/

How can I export the schema of a database in PostgreSQL?

pg_dump -d <databasename> -h <hostname> -p <port> -n <schemaname> -f <location of the dump file>

Please notice that you have sufficient privilege to access that schema. If you want take backup as specific user add user name in that command preceded by -U

remove kernel on jupyter notebook

Just for completeness, you can get a list of kernels with jupyter kernelspec list, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel. If you do not see everything in this list when you run jupyter kernelspec list, try looking in common Jupyter folders:

ls ~/.local/share/jupyter/kernels  # usually where local kernels go
ls /usr/local/share/jupyter/kernels  # usually where system-wide kernels go
ls /usr/share/jupyter/kernels  # also where system-wide kernels can go

Also, you can delete a kernel with jupyter kernelspec remove or jupyter kernelspec uninstall. The latter is an alias for remove. From the in-line help text for the command:

uninstall
    Alias for remove
remove
    Remove one or more Jupyter kernelspecs by name.

What is it exactly a BLOB in a DBMS context

They are binary large objects, you can use them to store binary data such as images or serialized objects among other things.

Setting the filter to an OpenFileDialog to allow the typical image formats?

Just a necrocomment for using string.Join and LINQ.

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
dlgOpenMockImage.Filter = string.Format("{0}| All image files ({1})|{1}|All files|*", 
    string.Join("|", codecs.Select(codec => 
    string.Format("{0} ({1})|{1}", codec.CodecName, codec.FilenameExtension)).ToArray()),
    string.Join(";", codecs.Select(codec => codec.FilenameExtension).ToArray()));

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Are there dictionaries in php?

Associative array in PHP actually considered as a dictionary.

An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// Using the short array syntax
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.

Adding Buttons To Google Sheets and Set value to Cells on clicking

You can insert an image that looks like a button. Then attach a script to the image.

  • INSERT menu
  • Image

Insert Image

You can insert any image. The image can be edited in the spreadsheet

Edit Image

Image of a Button

Image of Button

Assign a function name to an image:

Assign Function

Is there a way to programmatically scroll a scroll view to a specific edit text?

reference : https://stackoverflow.com/a/6438240/2624806

Following worked far better.

mObservableScrollView.post(new Runnable() {
            public void run() { 
                mObservableScrollView.fullScroll([View_FOCUS][1]); 
            }
        });

bash: mkvirtualenv: command not found

Since I just went though a drag, I'll try to write the answer I'd have wished for two hours ago. This is for people who don't just want the copy&paste solution

First: Do you wonder why copying and pasting paths works for some people while it doesn't work for others?** The main reason, solutions differ are different python versions, 2.x or 3.x. There are actually distinct versions of virtualenv and virtualenvwrapper that work with either python 2 or 3. If you are on python 2 install like so:

sudo pip install virutalenv
sudo pip install virtualenvwrapper

If you are planning to use python 3 install the related python 3 versions

sudo pip3 install virtualenv
sudo pip3 install virtualenvwrapper

You've successfully installed the packages for your python version and are all set, right? Well, try it. Type workon into your terminal. Your terminal will not be able to find the command (workon is a command of virtualenvwrapper). Of course it won't. Workon is an executable that will only be available to you once you load/source the file virtualenvwrapper.sh. But the official installation guide has you covered on this one, right?. Just open your .bash_profile and insert the following, it says in the documentation:

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

Especially the command source /usr/local/bin/virtualenvwrapper.sh seems helpful since the command seems to load/source the desired file virtualenvwrapper.sh that contains all the commands you want to work with like workon and mkvirtualenv. But yeah, no. When following the official installation guide, you are very likely to receive the error from the initial post: mkvirtualenv: command not found. Still no command is being found and you are still frustrated. So whats the problem here? The problem is that virtualenvwrapper.sh is not were you are looking for it right now. Short reminder ... you are looking here:

source /usr/local/bin/virtualenvwrapper.sh

But there is a pretty straight forward way to finding the desired file. Just type

which virtualenvwrapper

to your terminal. This will search your PATH for the file, since it is very likely to be in some folder that is included in the PATH of your system.

If your system is very exotic, the desired file will hide outside of a PATH folder. In that case you can find the path to virtalenvwrapper.sh with the shell command find / -name virtualenvwrapper.sh

Your result may look something like this: /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh Congratulations. You have found your missing file!. Now all you have to do is changing one command in your .bash_profile. Just change:

source "/usr/local/bin/virtualenvwrapper.sh"

to:

"/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh"

Congratulations. Virtualenvwrapper does now work on your system. But you can do one more thing to enhance your solution. If you've found the file virtualenvwrapper.sh with the command which virtualenvwrapper.sh you know that it is inside of a folder of the PATH. So if you just write the filename, your file system will assume the file is inside of a PATH folder. So you you don't have to write out the full path. Just type:

source "virtualenvwrapper.sh"

Thats it. You are no longer frustrated. You have solved your problem. Hopefully.

Get the index of the object inside an array, matching a condition

Why do you not want to iterate exactly ? The new Array.prototype.forEach are great for this purpose!

You can use a Binary Search Tree to find via a single method call if you want. This is a neat implementation of BTree and Red black Search tree in JS - https://github.com/vadimg/js_bintrees - but I'm not sure whether you can find the index at the same time.

Function for Factorial in Python

def factorial(n):
    if n < 2:
        return 1
    return n * factorial(n - 1)

How do I use the Simple HTTP client in Android?

public static void connect(String url)
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }


    } catch (Exception e) {}
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

Understanding `scale` in R

log simply takes the logarithm (base e, by default) of each element of the vector.
scale, with default settings, will calculate the mean and standard deviation of the entire vector, then "scale" each element by those values by subtracting the mean and dividing by the sd. (If you use scale(x, scale=FALSE), it will only subtract the mean but not divide by the std deviation.)

Note that this will give you the same values

   set.seed(1)
   x <- runif(7)

   # Manually scaling
   (x - mean(x)) / sd(x)

   scale(x)

React Native Change Default iOS Simulator Device

As answered by Ian L, I also use NPM to manage my scripts.

Example:

_x000D_
_x000D_
{_x000D_
  "scripts": {_x000D_
    "ios": "react-native run-ios --simulator=\"iPad Air 2\"",_x000D_
    "devices": "xcrun simctl list devices"_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

This way, I can quickly get what I need:

  1. List all devices: npm run devices
  2. Run the default simulator: npm run ios

Find the most frequent number in a NumPy array

Here is a general solution that may be applied along an axis, regardless of values, using purely numpy. I've also found that this is much faster than scipy.stats.mode if there are a lot of unique values.

import numpy

def mode(ndarray, axis=0):
    # Check inputs
    ndarray = numpy.asarray(ndarray)
    ndim = ndarray.ndim
    if ndarray.size == 1:
        return (ndarray[0], 1)
    elif ndarray.size == 0:
        raise Exception('Cannot compute mode on empty array')
    try:
        axis = range(ndarray.ndim)[axis]
    except:
        raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))

    # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
    if all([ndim == 1,
            int(numpy.__version__.split('.')[0]) >= 1,
            int(numpy.__version__.split('.')[1]) >= 9]):
        modals, counts = numpy.unique(ndarray, return_counts=True)
        index = numpy.argmax(counts)
        return modals[index], counts[index]

    # Sort array
    sort = numpy.sort(ndarray, axis=axis)
    # Create array to transpose along the axis and get padding shape
    transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
    shape = list(sort.shape)
    shape[axis] = 1
    # Create a boolean array along strides of unique values
    strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
                                 numpy.diff(sort, axis=axis) == 0,
                                 numpy.zeros(shape=shape, dtype='bool')],
                                axis=axis).transpose(transpose).ravel()
    # Count the stride lengths
    counts = numpy.cumsum(strides)
    counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
    counts[strides] = 0
    # Get shape of padded counts and slice to return to the original shape
    shape = numpy.array(sort.shape)
    shape[axis] += 1
    shape = shape[transpose]
    slices = [slice(None)] * ndim
    slices[axis] = slice(1, None)
    # Reshape and compute final counts
    counts = counts.reshape(shape).transpose(transpose)[slices] + 1

    # Find maximum counts and return modals/counts
    slices = [slice(None, i) for i in sort.shape]
    del slices[axis]
    index = numpy.ogrid[slices]
    index.insert(axis, numpy.argmax(counts, axis=axis))
    return sort[index], counts[index]

Standard deviation of a list

In python 2.7 you can use NumPy's numpy.std() gives the population standard deviation.

In Python 3.4 statistics.stdev() returns the sample standard deviation. The pstdv() function is the same as numpy.std().

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

jQuery Cycle is one of my favourite light weight libraries.

What you want to achieve could be done in just

    jQuery("#slideshow").cycle({
    timeout:0, // no autoplay
    fx: 'fade', //fade effect, although there are heaps
    next: '#next',
    prev: '#prev'
    });

JSFIDDLE TO SEE HOW EASY IT IS

What is the 'dynamic' type in C# 4.0 used for?

The dynamic keyword was added, together with many other new features of C# 4.0, to make it simpler to talk to code that lives in or comes from other runtimes, that has different APIs.

Take an example.

If you have a COM object, like the Word.Application object, and want to open a document, the method to do that comes with no less than 15 parameters, most of which are optional.

To call this method, you would need something like this (I'm simplifying, this is not actual code):

object missing = System.Reflection.Missing.Value;
object fileName = "C:\\test.docx";
object readOnly = true;
wordApplication.Documents.Open(ref fileName, ref missing, ref readOnly,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing);

Note all those arguments? You need to pass those since C# before version 4.0 did not have a notion of optional arguments. In C# 4.0, COM APIs have been made easier to work with by introducing:

  1. Optional arguments
  2. Making ref optional for COM APIs
  3. Named arguments

The new syntax for the above call would be:

wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);

See how much easier it looks, how much more readable it becomes?

Let's break that apart:

                                    named argument, can skip the rest
                                                   |
                                                   v
wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);
                                 ^                         ^
                                 |                         |
                               notice no ref keyword, can pass
                               actual parameter values instead

The magic is that the C# compiler will now inject the necessary code, and work with new classes in the runtime, to do almost the exact same thing that you did before, but the syntax has been hidden from you, now you can focus on the what, and not so much on the how. Anders Hejlsberg is fond of saying that you have to invoke different "incantations", which is a sort of pun on the magic of the whole thing, where you typically have to wave your hand(s) and say some magic words in the right order to get a certain type of spell going. The old API way of talking to COM objects was a lot of that, you needed to jump through a lot of hoops in order to coax the compiler to compile the code for you.

Things break down in C# before version 4.0 even more if you try to talk to a COM object that you don't have an interface or class for, all you have is an IDispatch reference.

If you don't know what it is, IDispatch is basically reflection for COM objects. With an IDispatch interface you can ask the object "what is the id number for the method known as Save", and build up arrays of a certain type containing the argument values, and finally call an Invoke method on the IDispatch interface to call the method, passing all the information you've managed to scrounge together.

The above Save method could look like this (this is definitely not the right code):

string[] methodNames = new[] { "Open" };
Guid IID = ...
int methodId = wordApplication.GetIDsOfNames(IID, methodNames, methodNames.Length, lcid, dispid);
SafeArray args = new SafeArray(new[] { fileName, missing, missing, .... });
wordApplication.Invoke(methodId, ... args, ...);

All this for just opening a document.

VB had optional arguments and support for most of this out of the box a long time ago, so this C# code:

wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);

is basically just C# catching up to VB in terms of expressiveness, but doing it the right way, by making it extendable, and not just for COM. Of course this is also available for VB.NET or any other language built on top of the .NET runtime.

You can find more information about the IDispatch interface on Wikipedia: IDispatch if you want to read more about it. It's really gory stuff.

However, what if you wanted to talk to a Python object? There's a different API for that than the one used for COM objects, and since Python objects are dynamic in nature as well, you need to resort to reflection magic to find the right methods to call, their parameters, etc. but not the .NET reflection, something written for Python, pretty much like the IDispatch code above, just altogether different.

And for Ruby? A different API still.

JavaScript? Same deal, different API for that as well.

The dynamic keyword consists of two things:

  1. The new keyword in C#, dynamic
  2. A set of runtime classes that knows how to deal with the different types of objects, that implement a specific API that the dynamic keyword requires, and maps the calls to the right way of doing things. The API is even documented, so if you have objects that comes from a runtime not covered, you can add it.

The dynamic keyword is not, however, meant to replace any existing .NET-only code. Sure, you can do it, but it was not added for that reason, and the authors of the C# programming language with Anders Hejlsberg in the front, has been most adamant that they still regard C# as a strongly typed language, and will not sacrifice that principle.

This means that although you can write code like this:

dynamic x = 10;
dynamic y = 3.14;
dynamic z = "test";
dynamic k = true;
dynamic l = x + y * z - k;

and have it compile, it was not meant as a sort of magic-lets-figure-out-what-you-meant-at-runtime type of system.

The whole purpose was to make it easier to talk to other types of objects.

There's plenty of material on the internet about the keyword, proponents, opponents, discussions, rants, praise, etc.

I suggest you start with the following links and then google for more:

How do you explicitly set a new property on `window` in TypeScript?

Make a custom interface extends the Window and add your custom property as optional.

Then, let the customWindow that use the custom interface, but valued with the original window.

It's worked with the [email protected].

interface ICustomWindow extends Window {
  MyNamespace?: any
}

const customWindow:ICustomWindow = window;

customWindow.MyNamespace = customWindow.MyNamespace {} 

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Replace and overwrite instead of appending

Using truncate(), the solution could be

import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
    #convert to string:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
    f.truncate()

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Okay Recently I faced this problem I have very simple solution for solve this Issue , follow these steps: go to these directories src-> app-> index.html open the index.html and find <base href="your app name ">change this to <base href="/">

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

Your second delegate is not a rewrite of the first in anonymous delegate (rather than lambda) format. Look at your conditions.

First:

x.ID == packageId || x.Parent.ID == packageId || x.Parent.Parent.ID == packageId

Second:

(x.ID == packageId) || (x.Parent != null && x.Parent.ID == packageId) || 
(x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)

The call to the lambda would throw an exception for any x where the ID doesn't match and either the parent is null or doesn't match and the grandparent is null. Copy the null checks into the lambda and it should work correctly.

Edit after Comment to Question

If your original object is not a List<T>, then we have no way of knowing what the return type of FindAll() is, and whether or not this implements the IQueryable interface. If it does, then that likely explains the discrepancy. Because lambdas can be converted at compile time into an Expression<Func<T>> but anonymous delegates cannot, then you may be using the implementation of IQueryable when using the lambda version but LINQ-to-Objects when using the anonymous delegate version.

This would also explain why your lambda is not causing a NullReferenceException. If you were to pass that lambda expression to something that implements IEnumerable<T> but not IQueryable<T>, runtime evaluation of the lambda (which is no different from other methods, anonymous or not) would throw a NullReferenceException the first time it encountered an object where ID was not equal to the target and the parent or grandparent was null.

Added 3/16/2011 8:29AM EDT

Consider the following simple example:

IQueryable<MyObject> source = ...; // some object that implements IQueryable<MyObject>

var anonymousMethod =  source.Where(delegate(MyObject o) { return o.Name == "Adam"; });    
var expressionLambda = source.Where(o => o.Name == "Adam");

These two methods produce entirely different results.

The first query is the simple version. The anonymous method results in a delegate that's then passed to the IEnumerable<MyObject>.Where extension method, where the entire contents of source will be checked (manually in memory using ordinary compiled code) against your delegate. In other words, if you're familiar with iterator blocks in C#, it's something like doing this:

public IEnumerable<MyObject> MyWhere(IEnumerable<MyObject> dataSource, Func<MyObject, bool> predicate)
{
    foreach(MyObject item in dataSource)
    {
        if(predicate(item)) yield return item;
    }
}

The salient point here is that you're actually performing your filtering in memory on the client side. For example, if your source were some SQL ORM, there would be no WHERE clause in the query; the entire result set would be brought back to the client and filtered there.

The second query, which uses a lambda expression, is converted to an Expression<Func<MyObject, bool>> and uses the IQueryable<MyObject>.Where() extension method. This results in an object that is also typed as IQueryable<MyObject>. All of this works by then passing the expression to the underlying provider. This is why you aren't getting a NullReferenceException. It's entirely up to the query provider how to translate the expression (which, rather than being an actual compiled function that it can just call, is a representation of the logic of the expression using objects) into something it can use.

An easy way to see the distinction (or, at least, that there is) a distinction, would be to put a call to AsEnumerable() before your call to Where in the lambda version. This will force your code to use LINQ-to-Objects (meaning it operates on IEnumerable<T> like the anonymous delegate version, not IQueryable<T> like the lambda version currently does), and you'll get the exceptions as expected.

TL;DR Version

The long and the short of it is that your lambda expression is being translated into some kind of query against your data source, whereas the anonymous method version is evaluating the entire data source in memory. Whatever is doing the translating of your lambda into a query is not representing the logic that you're expecting, which is why it isn't producing the results you're expecting.

Initialise numpy array of unknown length

You can do this:

a = np.array([])
for x in y:
    a = np.append(a, x)

Deleting a local branch with Git

Ran into this today and switching to another branch didn't help. It turned out that somehow my worktree information had gotten corrupted and there was a worktree with the same folder path as my working directory with a HEAD pointing at the branch (git worktree list). I deleted the .git/worktree/ folder that was referencing it and git branch -d worked.

Only mkdir if it does not exist

Try using this:-

mkdir -p dir;

NOTE:- This will also create any intermediate directories that don't exist; for instance,

Check out mkdir -p

or try this:-

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$Message" 1>&2
fi

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Not really answer to the question, but one-liners for foldl and foldr:

a = [8,3,4]

## Foldl
reduce(lambda x,y: x**y, a)
#68719476736

## Foldr
reduce(lambda x,y: y**x, a[::-1])
#14134776518227074636666380005943348126619871175004951664972849610340958208L

Remove white space above and below large text in an inline-block element

span::before,
span::after {
    content: '';
    display: block;
    height: 0;
    width: 0;
}

span::before{
    margin-top:-6px;
}

span::after{
    margin-bottom:-8px;
}

Find out the margin-top and margin-bottom negative margins with this tool: http://text-crop.eightshapes.com/

The tool also gives you SCSS, LESS and Stylus examples. You can read more about it here: https://medium.com/eightshapes-llc/cropping-away-negative-impacts-of-line-height-84d744e016ce

StringStream in C#

You have a number of options:

One is to not use streams, but use the TextWriter

   void Print(TextWriter writer) 
   {
   }

   void Main() 
  {
    var textWriter = new StringWriter();
    Print(writer);
    string myString = textWriter.ToString();
   }

It's likely that TextWriter is the appropriate level of abstraction for your print function. Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.

If your motivation is that you also want your Print function to write to files, you can get a text writer from a filestream as well.

void Print(TextWriter writer) 
{
}

void PrintToFile(string filePath) 
{
     using(var textWriter = new StreamWriter(filePath))
     {
         Print(writer);
     }
}

If you REALLY want a stream you can look at MemoryStream.

MVC which submit button has been pressed

To make it easier I will say you can change your buttons to the following:

<input name="btnSubmit" type="submit" value="Save" />
<input name="btnProcess" type="submit" value="Process" />

Your controller:

public ActionResult Create(string btnSubmit, string btnProcess)
{
    if(btnSubmit != null)
       // do something for the Button btnSubmit
    else 
       // do something for the Button btnProcess
}

How to initialize an array's length in JavaScript?

The array constructor has an ambiguous syntax, and JSLint just hurts your feelings after all.

Also, your example code is broken, the second var statement will raise a SyntaxError. You're setting the property length of the array test, so there's no need for another var.

As far as your options go, array.length is the only "clean" one. Question is, why do you need to set the size in the first place? Try to refactor your code to get rid of that dependency.

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

Does return stop a loop?

Yes, return stops execution and exits the function. return always** exits its function immediately, with no further execution if it's inside a for loop.

It is easily verified for yourself:

_x000D_
_x000D_
function returnMe() {
  for (var i = 0; i < 2; i++) {
    if (i === 1) return i;
  }
}

console.log(returnMe());
_x000D_
_x000D_
_x000D_

** Notes: See this other answer about the special case of try/catch/finally and this answer about how forEach loops has its own function scope will not break out of the containing function.

Converting Integer to String with comma for thousands

Integers:

int value = 100000; 
String.format("%,d", value); // outputs 100,000

Doubles:

double value = 21403.3144d;
String.format("%,.2f", value); // outputs 21,403.31

String.format is pretty powerful.

- Edited per psuzzi feedback.

How to AUTO_INCREMENT in db2?

hi If you are still not able to make column as AUTO_INCREMENT while creating table. As a work around first create table that is:

create table student( sid integer NOT NULL sname varchar(30), PRIMARY KEY (sid) );

and then explicitly try to alter column bu using the following

alter table student alter column sid set GENERATED BY DEFAULT AS IDENTITY

Or

alter table student alter column sid set GENERATED BY DEFAULT AS IDENTITY (start with 100)

How to validate Google reCAPTCHA v3 on server side?

Check below example

<script src='https://www.google.com/recaptcha/api.js'></script>
<script>

function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
         document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}

</script>
<form autocomplete="off" method="post" action=submit.php">

    <input type="text" name="name">
    <input type="text" name="email">
    <div class="g-recaptcha" id="rcaptcha"  data-sitekey="site key"></div>
    <span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
    <input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>

"Could not find bundler" error

You may have to do something like "rvm use 1.9.2" first so that you are using the correct ruby and gemset. You can check which ruby you are using by doing "which ruby"

How do you sort a dictionary by value?

You can sort the Dictionary by value and get the result in dictionary using the code below:

Dictionary <<string, string>> ShareUserNewCopy = 
       ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,
                                                        pair => pair.Value);                                          

What is a Maven artifact?

Usually, when you create a Java project you want to use functionalities made in another Java projects. For example, if your project wants to send one email you dont need to create all the necessary code for doing that. You can bring a java library that does the most part of the work. Maven is a building tool that will help you in several tasks. One of those tasks is to bring these external dependencies or artifacts to your project in an automatic way ( only with some configuration in a XML file ). Of course Maven has more details but, for your question this is enough. And, of course too, Maven can build your project as an artifact (usually a jar file ) that can be used or imported in other projects.

This website has several articles talking about Maven :

https://connected2know.com/programming/what-is-maven/

https://connected2know.com/programming/maven-configuration/

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

How to make use of ng-if , ng-else in angularJS

There is no directive for ng-else

You can use ng-if to achieve if(){..} else{..} in angularJs.

For your current situation,

<div ng-if="data.id == 5">
<!-- If block -->
</div>
<div ng-if="data.id != 5">
<!-- Your Else Block -->
</div>

Handle Button click inside a row in RecyclerView

I wanted a solution that did not create any extra objects (ie listeners) that would have to be garbage collected later, and did not require nesting a view holder inside an adapter class.

In the ViewHolder class

private static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private final TextView ....// declare the fields in your view
        private ClickHandler ClickHandler;

        public MyHolder(final View itemView) {
            super(itemView);
            nameField = (TextView) itemView.findViewById(R.id.name);
            //find other fields here...
            Button myButton = (Button) itemView.findViewById(R.id.my_button);
            myButton.setOnClickListener(this);
        }
        ...
        @Override
        public void onClick(final View view) {
            if (clickHandler != null) {
                clickHandler.onMyButtonClicked(getAdapterPosition());
            }
        }

Points to note: the ClickHandler interface is defined, but not initialized here, so there is no assumption in the onClick method that it was ever initialized.

The ClickHandler interface looks like this:

private interface ClickHandler {
    void onMyButtonClicked(final int position);
} 

In the adapter, set an instance of 'ClickHandler' in the constructor, and override onBindViewHolder, to initialize `clickHandler' on the view holder:

private class MyAdapter extends ...{

    private final ClickHandler clickHandler;

    public MyAdapter(final ClickHandler clickHandler) {
        super(...);
        this.clickHandler = clickHandler;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder viewHolder, final int position) {
        super.onBindViewHolder(viewHolder, position);
        viewHolder.clickHandler = this.clickHandler;
    }

Note: I know that viewHolder.clickHandler is potentially getting set multiple times with the exact same value, but this is cheaper than checking for null and branching, and there is no memory cost, just an extra instruction.

Finally, when you create the adapter, you are forced to pass a ClickHandlerinstance to the constructor, as so:

adapter = new MyAdapter(new ClickHandler() {
    @Override
    public void onMyButtonClicked(final int position) {
        final MyModel model = adapter.getItem(position);
        //do something with the model where the button was clicked
    }
});

Note that adapter is a member variable here, not a local variable

MVC Razor @foreach

What is the best practice on where the logic for the @foreach should be at?

Nowhere, just get rid of it. You could use editor or display templates.

So for example:

@foreach (var item in Model.Foos)
{
    <div>@item.Bar</div>
}

could perfectly fine be replaced by a display template:

@Html.DisplayFor(x => x.Foos)

and then you will define the corresponding display template (if you don't like the default one). So you would define a reusable template ~/Views/Shared/DisplayTemplates/Foo.cshtml which will automatically be rendered by the framework for each element of the Foos collection (IEnumerable<Foo> Foos { get; set; }):

@model Foo
<div>@Model.Bar</div>

Obviously exactly the same conventions apply for editor templates which should be used in case you want to show some input fields allowing you to edit the view model in contrast to just displaying it as readonly.

How to make "if not true condition"?

This one

if [[ !  $(cat /etc/passwd | grep "sysa") ]]
Then echo " something"
exit 2
fi

How to execute a Python script from the Django shell?

django.setup() does not seem to work.

does not seem to be required either.

this alone worked.

import os, django, glob, sys, shelve
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")

Absolute Positioning & Text Alignment

position: absolute;
color: #ffffff;
font-weight: 500;
top: 0%;
left: 0%;
right: 0%;
text-align: center;

How can I enable or disable the GPS programmatically on Android?

This is a more statble code for all Android versions and possibly for new ones

void checkGPS() {
    LocationRequest locationRequest = LocationRequest.create();

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);

    SettingsClient settingsClient = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());

    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            Log.d("GPS_main", "OnSuccess");
            // GPS is ON
        }
    });

    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull final Exception e) {
            Log.d("GPS_main", "GPS off");
            // GPS off
            if (e instanceof ResolvableApiException) {
                ResolvableApiException resolvable = (ResolvableApiException) e;
                try {
                    resolvable.startResolutionForResult(ActivityMain.this, REQUESTCODE_TURNON_GPS);
                } catch (IntentSender.SendIntentException e1) {
                    e1.printStackTrace();
                }
            }
        }
    });
}

And you can handle the GPS state changes here

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == Static_AppVariables.REQUESTCODE_TURNON_GPS) {
        switch (resultCode) {
            case Activity.RESULT_OK:
                // GPS was turned on;
                break;
            case Activity.RESULT_CANCELED:
                // User rejected turning on the GPS
                break;
            default:
                break;
        }
    }
}

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

Based on Cameron's initial answer, here is what I've just added at my enhanced version of SilverFlow library's FloatingWindowHost (copying from FloatingWindowHost.cs at http://clipflair.codeplex.com source code)

    public int MaxZIndex
    {
      get {
        return FloatingWindows.Aggregate(-1, (maxZIndex, window) => {
          int w = Canvas.GetZIndex(window);
          return (w > maxZIndex) ? w : maxZIndex;
        });
      }
    }

    private void SetTopmost(UIElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        Canvas.SetZIndex(element, MaxZIndex + 1);
    }

Worth noting regarding the code above that Canvas.ZIndex is an attached property available for UIElements in various containers, not just used when being hosted in a Canvas (see Controlling rendering order (ZOrder) in Silverlight without using the Canvas control). Guess one could even make a SetTopmost and SetBottomMost static extension method for UIElement easily by adapting this code.

Why is MySQL InnoDB insert so slow?

InnoDB has transaction support, you're not using explicit transactions so innoDB has to do a commit after each statement ("performs a log flush to disk for every insert").

Execute this command before your loop:

START TRANSACTION

and this after you loop

COMMIT

Double border with different color

you can add infinite borders using box-shadow using css3 suppose you want to apply multiple borders on one div then code is like:

div {
    border-radius: 4px;
    /* #1 */
    border: 5px solid hsl(0, 0%, 40%);
    
    /* #2 */
    padding: 5px;
    background: hsl(0, 0%, 20%);
    
    /* #3 */
    outline: 5px solid hsl(0, 0%, 60%);
    
    /* #4 AND INFINITY!!! (CSS3 only) */
    box-shadow:
        0 0 0 10px red,
        0 0 0 15px orange,
        0 0 0 20px yellow,
        0 0 0 25px green,
        0 0 0 30px blue;
}

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

Use LINQ to get items in one List<>, that are not in another List<>

If you override the equality of People then you can also use:

peopleList2.Except(peopleList1)

Except should be significantly faster than the Where(...Any) variant since it can put the second list into a hashtable. Where(...Any) has a runtime of O(peopleList1.Count * peopleList2.Count) whereas variants based on HashSet<T> (almost) have a runtime of O(peopleList1.Count + peopleList2.Count).

Except implicitly removes duplicates. That shouldn't affect your case, but might be an issue for similar cases.

Or if you want fast code but don't want to override the equality:

var excludedIDs = new HashSet<int>(peopleList1.Select(p => p.ID));
var result = peopleList2.Where(p => !excludedIDs.Contains(p.ID));

This variant does not remove duplicates.

Adding an .env file to React Project

1. Create the .env file on your root folder

some sources prefere to use .env.development and .env.production but that's not obligatory.

2. The name of your VARIABLE -must- begin with REACT_APP_YOURVARIABLENAME

it seems that if your environment variable does not start like that so you will have problems

3. Include your variable

to include your environment variable just put on your code process.env.REACT_APP_VARIABLE

You don't have to install any external dependency

Python Prime number checker

Prime number check.

def is_prime(x):
    if x < 2:
        return False
    else:
        if x == 2:
            return True
        else:
            for i in range(2, x):
                if x % i == 0:
                    return False
            return True
x = int(raw_input("enter a prime number"))
print is_prime(x)

What's the difference between HEAD^ and HEAD~ in Git?

Here's a very good explanation taken verbatim from http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde :

ref~ is shorthand for ref~1 and means the commit's first parent. ref~2 means the commit's first parent's first parent. ref~3 means the commit's first parent's first parent's first parent. And so on.

ref^ is shorthand for ref^1 and means the commit's first parent. But where the two differ is that ref^2 means the commit's second parent (remember, commits can have two parents when they are a merge).

The ^ and ~ operators can be combined.

enter image description here

What encoding/code page is cmd.exe using?

I've been frustrated for long by Windows code page issues, and the C programs portability and localisation issues they cause. The previous posts have detailed the issues at length, so I'm not going to add anything in this respect.

To make a long story short, eventually I ended up writing my own UTF-8 compatibility library layer over the Visual C++ standard C library. Basically this library ensures that a standard C program works right, in any code page, using UTF-8 internally.

This library, called MsvcLibX, is available as open source at https://github.com/JFLarvoire/SysToolsLib. Main features:

  • C sources encoded in UTF-8, using normal char[] C strings, and standard C library APIs.
  • In any code page, everything is processed internally as UTF-8 in your code, including the main() routine argv[], with standard input and output automatically converted to the right code page.
  • All stdio.h file functions support UTF-8 pathnames > 260 characters, up to 64 KBytes actually.
  • The same sources can compile and link successfully in Windows using Visual C++ and MsvcLibX and Visual C++ C library, and in Linux using gcc and Linux standard C library, with no need for #ifdef ... #endif blocks.
  • Adds include files common in Linux, but missing in Visual C++. Ex: unistd.h
  • Adds missing functions, like those for directory I/O, symbolic link management, etc, all with UTF-8 support of course :-).

More details in the MsvcLibX README on GitHub, including how to build the library and use it in your own programs.

The release section in the above GitHub repository provides several programs using this MsvcLibX library, that will show its capabilities. Ex: Try my which.exe tool with directories with non-ASCII names in the PATH, searching for programs with non-ASCII names, and changing code pages.

Another useful tool there is the conv.exe program. This program can easily convert a data stream from any code page to any other. Its default is input in the Windows code page, and output in the current console code page. This allows to correctly view data generated by Windows GUI apps (ex: Notepad) in a command console, with a simple command like: type WINFILE.txt | conv

This MsvcLibX library is by no means complete, and contributions for improving it are welcome!

Appending an element to the end of a list in Scala

This is similar to one of the answers but in different way :

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

Besides all above solutions, check if you have the "id" or any custom defined parameter in the DELETE method is matching the route config.

public void Delete(int id)
{
    //some code here
}

If you hit with repeated 405 errors better reset the method signature to default as above and try.

The route config by default will look for id in the URL. So the parameter name id is important here unless you change the route config under the App_Start folder.

You may change the data type of the id though.

For example the method below should work just fine:

public void Delete(string id)
{
    //some code here
}

Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.

DELETE http://{url}/{action}/{id}

Example:

DELETE http://localhost/item/1

Hope it helps.

How to set a cron job to run every 3 hours

The unix setup should be like the following:

 0 */3 * * * sh cron/update_old_citations.sh

good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/

How to return Json object from MVC controller to view

<script type="text/javascript">
jQuery(function () {
    var container = jQuery("\#content");
    jQuery(container)
     .kendoGrid({
         selectable: "single row",
         dataSource: new kendo.data.DataSource({
             transport: {
                 read: {
                     url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
                     dataType: "json",
                 },
             },
             batch: true,
         }),
         editable: "popup",
         columns: [
            { field: "Id", title: "Id", width: 250, hidden: true },
            { field: "Data", title: "Message Body", width: 100 },
           { field: "mobile", title: "Mobile Number", width: 100 },
         ]
     });
});

Shortcut to open file in Vim

If you're editing files in a common directory, you can :cd to that directory, then use :e on just the filename.

For example, rather than:

:e /big/long/path/that/takes/a/while/to/type/or/tab/complete/thingy.rb
:sp /big/long/path/that/takes/a/while/to/type/or/tab/complete/other_thingy.c
:vs /big/long/path/that/takes/a/while/to/type/or/tab/complete/one_more_thingy.java

You can do:

:cd /big/long/path/that/takes/a/while/to/type/or/tab/complete/
:e thingy.rb
:sp other_thingy.c
:vs one_more_thingy.java

Or, if you already have a file in the desired directory open, you can use the % shorthand for the current filename, and trim it to the current directory with the :h modifier (:help :_%:) :

:e /big/long/path/that/takes/a/while/to/type/or/tab/complete/thingy.rb
:cd %:h
:sp other_thingy.c
:vs one_more_thingy.java

And, like others have said, you can tab-complete file names on the ex-line (see :help cmdline-completion for more).

How do I properly clean up Excel interop objects?

I found a useful generic template that can help implement the correct disposal pattern for COM objects, that need Marshal.ReleaseComObject called when they go out of scope:

Usage:

using (AutoReleaseComObject<Application> excelApplicationWrapper = new AutoReleaseComObject<Application>(new Application()))
{
    try
    {
        using (AutoReleaseComObject<Workbook> workbookWrapper = new AutoReleaseComObject<Workbook>(excelApplicationWrapper.ComObject.Workbooks.Open(namedRangeBase.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing)))
        {
           // do something with your workbook....
        }
    }
    finally
    {
         excelApplicationWrapper.ComObject.Quit();
    } 
}

Template:

public class AutoReleaseComObject<T> : IDisposable
{
    private T m_comObject;
    private bool m_armed = true;
    private bool m_disposed = false;

    public AutoReleaseComObject(T comObject)
    {
        Debug.Assert(comObject != null);
        m_comObject = comObject;
    }

#if DEBUG
    ~AutoReleaseComObject()
    {
        // We should have been disposed using Dispose().
        Debug.WriteLine("Finalize being called, should have been disposed");

        if (this.ComObject != null)
        {
            Debug.WriteLine(string.Format("ComObject was not null:{0}, name:{1}.", this.ComObject, this.ComObjectName));
        }

        //Debug.Assert(false);
    }
#endif

    public T ComObject
    {
        get
        {
            Debug.Assert(!m_disposed);
            return m_comObject;
        }
    }

    private string ComObjectName
    {
        get
        {
            if(this.ComObject is Microsoft.Office.Interop.Excel.Workbook)
            {
                return ((Microsoft.Office.Interop.Excel.Workbook)this.ComObject).Name;
            }

            return null;
        }
    }

    public void Disarm()
    {
        Debug.Assert(!m_disposed);
        m_armed = false;
    }

    #region IDisposable Members

    public void Dispose()
    {
        Dispose(true);
#if DEBUG
        GC.SuppressFinalize(this);
#endif
    }

    #endregion

    protected virtual void Dispose(bool disposing)
    {
        if (!m_disposed)
        {
            if (m_armed)
            {
                int refcnt = 0;
                do
                {
                    refcnt = System.Runtime.InteropServices.Marshal.ReleaseComObject(m_comObject);
                } while (refcnt > 0);

                m_comObject = default(T);
            }

            m_disposed = true;
        }
    }
}

Reference:

http://www.deez.info/sengelha/2005/02/11/useful-idisposable-class-3-autoreleasecomobject/

How do I find the location of my Python site-packages directory?

This works for me. It will get you both dist-packages and site-packages folders. If the folder is not on Python's path, it won't be doing you much good anyway.

import sys; 
print [f for f in sys.path if f.endswith('packages')]

Output (Ubuntu installation):

['/home/username/.local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']

Where can I view Tomcat log files in Eclipse?

Looks like the logs are scattered? I found access logs under <ProjectLocation>\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\logs

"Could not find Developer Disk Image"

For the case XCode version is lower than iOS device's image, you can either copy the disk image from other already updated XCode(or maybe the internet) or upgrade your XCode.

The image is a folder with size about over 10MB, and place(find or put it) here under this path "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSup??port/".

To enter Xcode.app package, hold control key and click on Xcode.app, you will find additional option like show package content or some word similar. Choose this option and you will enter Xcode.app like entering a normal folder.

Hope it's helpful and good luck!

Preloading images with jQuery

This works for me even in IE9:

$('<img src="' + imgURL + '"/>').on('load', function(){ doOnLoadStuff(); });

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Combine Powershell into a batch file and use the meta variables to assign each:

@echo off
for /f "tokens=1-6 delims=-" %%a in ('PowerShell -Command "& {Get-Date -format "yyyy-MM-dd-HH-mm-ss"}"') do (
    echo year: %%a
    echo month: %%b
    echo day: %%c
    echo hour: %%d
    echo minute: %%e
    echo second: %%f
)

You can also change the the format if you prefer name of the month MMM or MMMM and 12 hour to 24 hour formats hh or HH

Replace CRLF using powershell

The following will be able to process very large files quickly.

$file = New-Object System.IO.StreamReader -Arg "file1.txt"
$outstream = [System.IO.StreamWriter] "file2.txt"
$count = 0 

while ($line = $file.ReadLine()) {
      $count += 1
      $s = $line -replace "`n", "`r`n"
      $outstream.WriteLine($s)
  }

$file.close()
$outstream.close()

Write-Host ([string] $count + ' lines have been processed.')

What is a method group in C#?

Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup).

So, for example, I have:

private string DoSomethingToMyString(string input)
{
    // blah
}

Instead of explicitly stating the variable to be used like this:

public List<string> GetStringStuff()
{
    return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}

I can just omit the name of the var:

public List<string> GetStringStuff()
{
    return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Just open your sql file with a text editor and search for 'utf8mb4' and replace with utf8.I hope it would work for you

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I think I found the answer in my kernel source documentation: /usr/src/linux-2.6.37-rc3/Documentation/filesystems/proc.txt

1.7 TTY info in /proc/tty
-------------------------

Information about  the  available  and actually used tty's can be found in the
directory /proc/tty.You'll  find  entries  for drivers and line disciplines in
this directory, as shown in Table 1-11.


Table 1-11: Files in /proc/tty
..............................................................................
 File          Content                                        
 drivers       list of drivers and their usage                
 ldiscs        registered line disciplines                    
 driver/serial usage statistic and status of single tty lines 
..............................................................................

To see  which  tty's  are  currently in use, you can simply look into the file
/proc/tty/drivers:

  > cat /proc/tty/drivers 
  pty_slave            /dev/pts      136   0-255 pty:slave 
  pty_master           /dev/ptm      128   0-255 pty:master 
  pty_slave            /dev/ttyp       3   0-255 pty:slave 
  pty_master           /dev/pty        2   0-255 pty:master 
  serial               /dev/cua        5   64-67 serial:callout 
  serial               /dev/ttyS       4   64-67 serial 
  /dev/tty0            /dev/tty0       4       0 system:vtmaster 
  /dev/ptmx            /dev/ptmx       5       2 system 
  /dev/console         /dev/console    5       1 system:console 
  /dev/tty             /dev/tty        5       0 system:/dev/tty 
  unknown              /dev/tty        4    1-63 console 

Here is a link to this file: http://git.kernel.org/?p=linux/kernel/git/next/linux-next.git;a=blob_plain;f=Documentation/filesystems/proc.txt;hb=e8883f8057c0f7c9950fa9f20568f37bfa62f34a

How to detect if CMD is running as Administrator/has elevated privileges?

The easiest way to do this on Vista, Win 7 and above is enumerating token groups and looking for the current integrity level (or the administrators sid, if only group memberhip is important):

Check if we are running elevated:

whoami /groups | find "S-1-16-12288" && Echo I am running elevated, so I must be an admin anyway ;-)

Check if we belong to local administrators:

whoami /groups | find "S-1-5-32-544" && Echo I am a local admin

Check if we belong to domain admins:

whoami /groups | find "-512 " && Echo I am a domain admin

The following article lists the integrity level SIDs windows uses: http://msdn.microsoft.com/en-us/library/bb625963.aspx

How can I run a PHP script in the background after a form is submitted?

This is works for me. tyr this

exec(“php asyn.php”.” > /dev/null 2>/dev/null &“);

Check if a string is a valid date using DateTime.TryParse

Try using

DateTime.ParseExact(
    txtPaymentSummaryBeginDate.Text.Trim(),
    "MM/dd/yyyy", 
    System.Globalization.CultureInfo.InvariantCulture
);

It throws an exception if the input string is not in proper format, so in the catch section you can return false;

SQL Server add auto increment primary key to existing table

Here is an idea you can try. Original table - no identity column table1 create a new table - call table2 along with identity column. copy the data from table1 to table2 - the identity column is populated automatically with auto incremented numbers.

rename the original table - table1 to table3 rename the new table - table2 to table1 (original table) Now you have the table1 with identity column included and populated for the existing data. after making sure there is no issue and working properly, drop the table3 when no longer needed.

How to read file with space separated values in pandas

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

There is already an open DataReader associated with this Command which must be closed first

I solved this problem by changing await _accountSessionDataModel.SaveChangesAsync(); to _accountSessionDataModel.SaveChanges(); in my Repository class.

 public async Task<Session> CreateSession()
    {
        var session = new Session();

        _accountSessionDataModel.Sessions.Add(session);
        await _accountSessionDataModel.SaveChangesAsync();
     }

Changed it to:

 public Session CreateSession()
    {
        var session = new Session();

        _accountSessionDataModel.Sessions.Add(session);
        _accountSessionDataModel.SaveChanges();
     }

The problem was that I updated the Sessions in the frontend after creating a session (in code), but because SaveChangesAsync happens asynchronously, fetching the sessions caused this error because apparently the SaveChangesAsync operation was not yet ready.

What are the differences between the urllib, urllib2, urllib3 and requests module?

Just to add to the existing answers, I don't see anyone mentioning that python requests is not a native library. If you are ok with adding dependencies, then requests is fine. However, if you are trying to avoid adding dependencies, urllib is a native python library that is already available to you.

How do I check if a string is unicode or ascii?

Note that on Python 3, it's not really fair to say any of:

  • strs are UTFx for any x (eg. UTF8)

  • strs are Unicode

  • strs are ordered collections of Unicode characters

Python's str type is (normally) a sequence of Unicode code points, some of which map to characters.


Even on Python 3, it's not as simple to answer this question as you might imagine.

An obvious way to test for ASCII-compatible strings is by an attempted encode:

"Hello there!".encode("ascii")
#>>> b'Hello there!'

"Hello there... ?!".encode("ascii")
#>>> Traceback (most recent call last):
#>>>   File "", line 4, in <module>
#>>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 15: ordinal not in range(128)

The error distinguishes the cases.

In Python 3, there are even some strings that contain invalid Unicode code points:

"Hello there!".encode("utf8")
#>>> b'Hello there!'

"\udcc3".encode("utf8")
#>>> Traceback (most recent call last):
#>>>   File "", line 19, in <module>
#>>> UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 0: surrogates not allowed

The same method to distinguish them is used.

How to SUM and SUBTRACT using SQL?

I think this is what you're looking for. NEW_BAL is the sum of QTYs subtracted from the balance:

SELECT   master_table.ORDERNO,
         master_table.ITEM,
         SUM(master_table.QTY),
         stock_bal.BAL_QTY,
         (stock_bal.BAL_QTY - SUM(master_table.QTY)) AS NEW_BAL
FROM     master_table INNER JOIN
         stock_bal ON master_bal.ITEM = stock_bal.ITEM
GROUP BY master_table.ORDERNO,
         master_table.ITEM

If you want to update the item balance with the new balance, use the following:

UPDATE stock_bal
SET    BAL_QTY = BAL_QTY - (SELECT   SUM(QTY)
                            FROM     master_table
                            GROUP BY master_table.ORDERNO,
                                     master_table.ITEM)

This assumes you posted the subtraction backward; it subtracts the quantities in the order from the balance, which makes the most sense without knowing more about your tables. Just swap those two to change it if I was wrong:

(SUM(master_table.QTY) - stock_bal.BAL_QTY) AS NEW_BAL

How to prevent form from being submitted?

Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event:

_x000D_
_x000D_
const element = document.querySelector('form');_x000D_
element.addEventListener('submit', event => {_x000D_
  event.preventDefault();_x000D_
  // actual logic, e.g. validate the form_x000D_
  console.log('Form submission cancelled.');_x000D_
});
_x000D_
<form>_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

I think it's a better solution than defining a submit event handler inline with the onsubmit attribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.

Using the .onsubmit property of the form DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick .

How to use OpenFileDialog to select a folder?

Here is another solution, that has all the source available in a single, simple ZIP file.

It presents the OpenFileDialog with additional windows flags that makes it work like the Windows 7+ Folder Selection dialog.

Per the website, it is public domain: "There’s no license as such as you are free to take and do with the code what you will."

Archive.org links:

Android, How can I Convert String to Date?

It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.

One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.

failed to open stream: No such file or directory in

include() needs a full file path, relative to the file system's root directory.

This should work:

 include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");

How do I create a table based on another table

select * into newtable from oldtable

How can I create a Java method that accepts a variable number of arguments?

Take a look at the Java guide on varargs.

You can create a method as shown below. Simply call System.out.printf instead of System.out.println(String.format(....

public static void print(String format, Object... args) {
    System.out.printf(format, args);
}

Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:

import static java.lang.System.out;

out.printf("Numer of apples: %d", 10);

Matplotlib discrete colorbar

This topic is well covered already but I wanted to add something more specific : I wanted to be sure that a certain value would be mapped to that color (not to any color).

It is not complicated but as it took me some time, it might help others not lossing as much time as I did :)

import matplotlib
from matplotlib.colors import ListedColormap

# Let's design a dummy land use field
A = np.reshape([7,2,13,7,2,2], (2,3))
vals = np.unique(A)

# Let's also design our color mapping: 1s should be plotted in blue, 2s in red, etc...
col_dict={1:"blue",
          2:"red",
          13:"orange",
          7:"green"}

# We create a colormar from our list of colors
cm = ListedColormap([col_dict[x] for x in col_dict.keys()])

# Let's also define the description of each category : 1 (blue) is Sea; 2 (red) is burnt, etc... Order should be respected here ! Or using another dict maybe could help.
labels = np.array(["Sea","City","Sand","Forest"])
len_lab = len(labels)

# prepare normalizer
## Prepare bins for the normalizer
norm_bins = np.sort([*col_dict.keys()]) + 0.5
norm_bins = np.insert(norm_bins, 0, np.min(norm_bins) - 1.0)
print(norm_bins)
## Make normalizer and formatter
norm = matplotlib.colors.BoundaryNorm(norm_bins, len_lab, clip=True)
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: labels[norm(x)])

# Plot our figure
fig,ax = plt.subplots()
im = ax.imshow(A, cmap=cm, norm=norm)

diff = norm_bins[1:] - norm_bins[:-1]
tickz = norm_bins[:-1] + diff / 2
cb = fig.colorbar(im, format=fmt, ticks=tickz)
fig.savefig("example_landuse.png")
plt.show()

enter image description here

Styling the arrow on bootstrap tooltips

Use this style sheet to get you started !

.tooltip{
    position:absolute;
    z-index:1020;
    display:block;
    visibility:visible;
    padding:5px;
    font-size:11px;
    opacity:0;
    filter:alpha(opacity=0)
}
.tooltip.in{
    opacity:.8;
    filter:alpha(opacity=80)
}
.tooltip.top{
    margin-top:-2px
}
.tooltip.right{
    margin-left:2px
}
.tooltip.bottom{
    margin-top:2px
}
.tooltip.left{
    margin-left:-2px
}
.tooltip.top .tooltip-arrow{
    bottom:0;
    left:50%;
    margin-left:-5px;
    border-left:5px solid transparent;
    border-right:5px solid transparent;
    border-top:5px solid #000
}
.tooltip.left .tooltip-arrow{
    top:50%;
    right:0;
    margin-top:-5px;
    border-top:5px solid transparent;
    border-bottom:5px solid transparent;
    border-left:5px solid #000
}
.tooltip.bottom .tooltip-arrow{
    top:0;
    left:50%;
    margin-left:-5px;
    border-left:5px solid transparent;
    border-right:5px solid transparent;
    border-bottom:5px solid #000
}
.tooltip.right .tooltip-arrow{
    top:50%;
    left:0;
    margin-top:-5px;
    border-top:5px solid transparent;
    border-bottom:5px solid transparent;
    border-right:5px solid #000
}
.tooltip-inner{
    max-width:200px;
    padding:3px 8px;
    color:#fff;
    text-align:center;
    text-decoration:none;
    background-color:#000;
    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    border-radius:4px
}
.tooltip-arrow{
    position:absolute;
    width:0;
    height:0
}

How can I do a BEFORE UPDATED trigger with sql server?

To do a BEFORE UPDATE in SQL Server I use a trick. I do a false update of the record (UPDATE Table SET Field = Field), in such way I get the previous image of the record.

Place input box at the center of div

You can just use either of the following approaches:

_x000D_
_x000D_
.center-block {
  margin: auto;
  display: block;
}
_x000D_
<div>
  <input class="center-block">
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.parent {
  display: grid;
  place-items: center;
}
_x000D_
<div class="parent">
  <input>
</div>
_x000D_
_x000D_
_x000D_

How do I use StringUtils in Java?

StringUtils is part of Apache Commons Lang (http://commons.apache.org/lang/, and as the name suggest it provides some nice utilities for dealing with Strings, going beyond what is offered in java.lang.String. It consists of over 50 static methods.

There are two different versions available, the newer org.apache.commons.lang3.StringUtils and the older org.apache.commons.lang.StringUtils. There are not really any significant differences between the two. lang3.StringUtils requires Java 5.0 and is probably the version you'll want to use.

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

This is the only thing that I found to work

-(void) testHTTPS {
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager GET:[NSString stringWithFormat:@"%@", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

Why don't you just make it easy and simple. If I need to know the number of days between today and say, March 10th, 2015, I can just enter the simple formula.

Lets say the static date is March 10th, 2015, and is in cell O5.

The formula to determine the number of days between today and O5 would be, =O5-Today()

Nothing fancy or DATEDIF stuff. Obviously, the cell where you type this formula in must have a data type of 'number'. Just type your date in normally in the reference cell, in this case O5.

What's the difference between UTF-8 and UTF-8 without BOM?

BOM tends to boom (no pun intended (sic)) somewhere, someplace. And when it booms (for example, doesn't get recognized by browsers, editors, etc.), it shows up as the weird characters  at the start of the document (for example, HTML file, JSON response, RSS, etc.) and causes the kind of embarrassments like the recent encoding issue experienced during the talk of Obama on Twitter.

It's very annoying when it shows up at places hard to debug or when testing is neglected. So it's best to avoid it unless you must use it.

how to select rows based on distinct values of A COLUMN only

use this(assume that your table name is emails):

select * from emails as a 
inner join  
(select EmailAddress, min(Id) as id from emails 
group by EmailAddress ) as b 
on a.EmailAddress = b.EmailAddress 
and a.Id = b.id

hope this help..

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

If one or both of the files you wish to compare isn't in an Eclipse project:

  1. Open the Quick Access search box

    • Linux/Windows: Ctrl+3
    • Mac: ?+3
  2. Type compare and select Compare With Other Resource

  3. Select the files to compare ? OK

You can also create a keyboard shortcut for Compare With Other Resource by going to Window ? Preferences ? General ? Keys

How to convert time milliseconds to hours, min, sec format in JavaScript?

I needed time only up to one day, 24h, this was my take:

_x000D_
_x000D_
const milliseconds = 5680000;_x000D_
_x000D_
const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);_x000D_
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);_x000D_
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);_x000D_
_x000D_
const time = `${hours}:${minutes}:${seconds}`_x000D_
console.log(time);
_x000D_
_x000D_
_x000D_

you could get days this way as well if needed.

Explain the "setUp" and "tearDown" Python methods used in test cases

You can use these to factor out code common to all tests in the test suite.

If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

For example:

class TurretTest(unittest.TestCase):

    def setUp(self):
        self.turret_factory = TurretFactory()
        self.turret = self.turret_factory.CreateTurret()

    def test_turret_is_on_by_default(self):
        self.assertEquals(True, self.turret.is_on())

    def test_turret_turns_can_be_turned_off(self):
        self.turret.turn_off()
        self.assertEquals(False, self.turret.is_on())

Why won't bundler install JSON gem?

For me, some of the answers mentioned earlier were helpful from understanding point of view, but those didn't solve my problem.

So this is what I did to solve issue.

  • Modified gemfile.lock to update json (2.0.2) (Earlier, it was 1.8.3)
  • Check the Bundler version installed (Bundler -v command). I had version 1.12.5 installed
  • Install bundler version 1.11.2 (using gem install bundler -v '1.11.2')
  • Then run bundle install

Use Font Awesome Icons in CSS

Use the following Python program via command line to create png images from Font-Awesome icons:

https://github.com/Pythonity/font-awesome-to-png

Alternative to Intersect in MySQL

For completeness here is another method for emulating INTERSECT. Note that the IN (SELECT ...) form suggested in other answers is generally more efficient.

Generally for a table called mytable with a primary key called id:

SELECT id
FROM mytable AS a
INNER JOIN mytable AS b ON a.id = b.id
WHERE
(a.col1 = "someval")
AND
(b.col1 = "someotherval")

(Note that if you use SELECT * with this query you will get twice as many columns as are defined in mytable, this is because INNER JOIN generates a Cartesian product)

The INNER JOIN here generates every permutation of row-pairs from your table. That means every combination of rows is generated, in every possible order. The WHERE clause then filters the a side of the pair, then the b side. The result is that only rows which satisfy both conditions are returned, just like intersection two queries would do.

Are string.Equals() and == operator really same?

In addition to Jon Skeet's answer, I'd like to explain why most of the time when using == you actually get the answer true on different string instances with the same value:

string a = "Hell";
string b = "Hello";
a = a + "o";
Console.WriteLine(a == b);

As you can see, a and b must be different string instances, but because strings are immutable, the runtime uses so called string interning to let both a and b reference the same string in memory. The == operator for objects checks reference, and since both a and b reference the same instance, the result is true. When you change either one of them, a new string instance is created, which is why string interning is possible.

By the way, Jon Skeet's answer is not complete. Indeed, x == y is false but that is only because he is comparing objects and objects compare by reference. If you'd write (string)x == (string)y, it will return true again. So strings have their ==-operator overloaded, which calls String.Equals underneath.

Table border left and bottom

Give a class .border-lb and give this CSS

.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}

And the HTML

<table width="770">
  <tr>
    <td class="border-lb">picture (border only to the left and bottom ) </td>
    <td>text</td>
  </tr>
  <tr>
    <td>text</td>
    <td class="border-lb">picture (border only to the left and bottom) </td>
  </tr>
</table>

Screenshot

Fiddle: http://jsfiddle.net/FXMVL/

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

MySQL Join Where Not Exists

I'd probably use a LEFT JOIN, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULLs.

So, something like:

SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL

Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.

How to truncate a foreign key constrained table?

Just use CASCADE

TRUNCATE "products" RESTART IDENTITY CASCADE;

But be ready for cascade deletes )

Woocommerce get products

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.

Add custom buttons on Slick Carousel

its very easy. Use the bellow code, Its works for me. Here I have used fontawesome icon but you can use anything as image or any other Icon's code.

$(document).ready(function(){
    $('.slider').slick({
        autoplay:true,
        arrows: true,
        prevArrow:"<button type='button' class='slick-prev pull-left'><i class='fa fa-angle-left' aria-hidden='true'></i></button>",
        nextArrow:"<button type='button' class='slick-next pull-right'><i class='fa fa-angle-right' aria-hidden='true'></i></button>"
    });
});

Oracle : how to subtract two dates and get minutes of the result

I think you can adapt the function to substract the two timestamps:

return  EXTRACT(MINUTE FROM 
  TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
  TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);

I think you could simplify it by just using CAST(p_date as TIMESTAMP).

return  EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));

Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.

How to preview git-pull without doing fetch?

I may be late to the party, but this is something which bugged me for too long. In my experience, I would rather want to see which changes are pending than update my working copy and deal with those changes.

This goes in the ~/.gitconfig file:

[alias]
        diffpull=!git fetch && git diff HEAD..@{u}

It fetches the current branch, then does a diff between the working copy and this fetched branch. So you should only see the changes that would come with git pull.

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

How to pass variable number of arguments to a PHP function

In a new Php 5.6, you can use ... operator instead of using func_get_args().

So, using this, you can get all the parameters you pass:

function manyVars(...$params) {
   var_dump($params);
}

How to get the index of an element in an IEnumerable?

The whole point of getting things out as IEnumerable is so you can lazily iterate over the contents. As such, there isn't really a concept of an index. What you are doing really doesn't make a lot of sense for an IEnumerable. If you need something that supports access by index, put it in an actual list or collection.

Centering controls within a form in .NET (Winforms)?

To center Button in panel o in other container follow this step:

  1. At design time set the position
  2. Go to properties Anchor of the button and set this value as the follow image

enter image description here

How to read text files with ANSI encoding and non-English letters?

You get the question-mark-diamond characters when your textfile uses high-ANSI encoding -- meaning it uses characters between 127 and 255. Those characters have the eighth (i.e. the most significant) bit set. When ASP.NET reads the textfile it assumes UTF-8 encoding, and that most significant bit has a special meaning.

You must force ASP.NET to interpret the textfile as high-ANSI encoding, by telling it the codepage is 1252:

String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />");  // change linebreaks to HTML

How do I set headers using python's urllib?

For both Python 3 and Python 2, this works:

try:
    from urllib.request import Request, urlopen  # Python 3
except ImportError:
    from urllib2 import Request, urlopen  # Python 2

req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()

print(content)

How to delete all files from a specific folder?

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);

Or in a single line:

Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

Get top most UIViewController

The best solution for me is an extension with a function. Create a swift file with this extension

First is the UIWindow extension:

public extension UIWindow {
    var visibleViewController: UIViewController? {
        return UIWindow.visibleVC(vc: self.rootViewController)
    }

    static func visibleVC(vc: UIViewController?) -> UIViewController? {
        if let navigationViewController = vc as? UINavigationController {
            return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
        } else if let tabBarVC = vc as? UITabBarController {
            return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
        } else {
            if let presentedVC = vc?.presentedViewController {
                return UIWindow.visibleVC(vc: presentedVC)
            } else {
                return vc
            }
        }
    }
}

inside that file add function

func visibleViewController() -> UIViewController? {
    let appDelegate = UIApplication.shared.delegate
    if let window = appDelegate!.window {
        return window?.visibleViewController
    }
    return nil
}

And if you want to use it, you can call it anywhere. Example:

  override func viewDidLoad() {
    super.viewDidLoad()
      if let topVC = visibleViewController() {
             //show some label or text field 
    }
}

File code is like this:

import UIKit

public extension UIWindow {
    var visibleViewController: UIViewController? {
        return UIWindow.visibleVC(vc: self.rootViewController)
    }

    static func visibleVC(vc: UIViewController?) -> UIViewController? {
        if let navigationViewController = vc as? UINavigationController {
            return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
        } else if let tabBarVC = vc as? UITabBarController {
            return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
        } else {
            if let presentedVC = vc?.presentedViewController {
                return UIWindow.visibleVC(vc: presentedVC)
            } else {
                return vc
            }
        }
    }
}

func visibleViewController() -> UIViewController? {
    let appDelegate = UIApplication.shared.delegate
    if let window = appDelegate!.window {
        return window?.visibleViewController
    }
    return nil
}

Query for documents where array size is greater than 1

You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.

Compare query operators vs aggregation comparison operators.

db.accommodations.find({$expr:{$gt:[{$size:"$name"}, 1]}})

SET NAMES utf8 in MySQL?

Getting encoding right is really tricky - there are too many layers:

  • Browser
  • Page
  • PHP
  • MySQL

The SQL command "SET CHARSET utf8" from PHP will ensure that the client side (PHP) will get the data in utf8, no matter how they are stored in the database. Of course, they need to be stored correctly first.

DDL definition vs. real data

Encoding defined for a table/column doesn't really mean that the data are in that encoding. If you happened to have a table defined as utf8 but stored as differtent encoding, then MySQL will treat them as utf8 and you're in trouble. Which means you have to fix this first.

What to check

You need to check in what encoding the data flow at each layer.

  • Check HTTP headers, headers.
  • Check what's really sent in body of the request.
  • Don't forget that MySQL has encoding almost everywhere:
    • Database
    • Tables
    • Columns
    • Server as a whole
    • Client
      Make sure that there's the right one everywhere.

Conversion

If you receive data in e.g. windows-1250, and want to store in utf-8, then use this SQL before storing:

SET NAMES 'cp1250';

If you have data in DB as windows-1250 and want to retreive utf8, use:

SET CHARSET 'utf8';

Few more notes:

  • Don't rely on too "smart" tools to show the data. E.g. phpMyAdmin does (was doing when I was using it) encoding really bad. And it goes through all the layers so it's hard to find out.
  • Also, Internet Explorer had really stupid behavior of "guessing" the encoding based on weird rules.
  • Use simple editors where you can switch encoding. I recommend MySQL Workbench.

could not access the package manager. is the system running while installing android application

You can avoid the error by setting default device before launching application. Launch the AVD before starting the app.

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

codes need to save UTF8 without BOM while recording. Sometimes, written codes with (Notepad++) or other coding tools and use UTF8 encode, this error occurs. I'm sorry, I do not know English. This is just my experience.

'int' object has no attribute '__getitem__'

you can also covert int to str first and assign index to it then again convert it to int like this:

int(str(x)[n]) //where x is an integer value

Google Maps: Auto close open InfoWindows?

var map;
var infowindow;
...
function createMarker(...) {
    var marker = new google.maps.Marker({...});
    google.maps.event.addListener(marker, 'click', function() {
        ...
        if (infowindow) {
            infowindow.close();
        };
        infowindow = new google.maps.InfoWindow({
            content: contentString,
            maxWidth: 300
        });
        infowindow.open(map, marker);
    }
...
function initialize() {
    ...
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    ...
    google.maps.event.addListener(map, 'click', function(event) {
        if (infowindow) {
            infowindow.close();
        };
        ...
    }
}