Programs & Examples On #Svn hooks

In Apache Subversion, a hook is a program triggered by some repository event, such as the creation of a new revision or the modification of an unversioned property. This is often used for integration of Subversion with other tools, e.g. bug tracking software.

What is a pre-revprop-change hook in SVN, and how do I create it?

For PC users: The .bat extension did not work for me when used on Windows Server maching. I used VisualSvn as Django Reinhardt suggested, and it created a hook with a .cmd extension.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

There's a difference between an empty string "" and an undefined variable. You should be checking whether or not theHref contains a defined string, rather than its lenght:

if(theHref){
   // ---
}

If you still want to check for the length, then do this:

if(theHref && theHref.length){
   // ...
}

Where to put a textfile I want to use in eclipse?

Suppose you have a project called "TestProject" on Eclipse and your workspace folder is located at E:/eclipse/workspace. When you build an Eclipse project, your classpath is then e:/eclipse/workspace/TestProject. When you try to read "staedteliste.txt", you're trying to access the file at e:/eclipse/workspace/TestProject/staedteliste.txt.

If you want to have a separate folder for your project, then create the Files folder under TestProject and then access the file with (the relative path) /Files/staedteliste.txt. If you put the file under the src folder, then you have to access it using /src/staedteliste.txt. A Files folder inside the src folder would be /src/Files/staedteliste.txt

Instead of using the the relative path you can use the absolute one by adding e:/eclipse/workspace/ at the beginning, but using the relative path is better because you can move the project without worrying about refactoring as long as the project folder structure is the same.

How to set up devices for VS Code for a Flutter emulator

VS Code needs to know where Android SDK is installed on your system. On Windows, set "ANDROID_SDK_ROOT" environment variable to the Android SDK root folder.

Plus: Always check the "OUTPUT" and "DEBUG CONSOLE" tabs for errors and information.

What is a regular expression which will match a valid domain name without a subdomain?

Thank you for pointing right direction in domain name validation solutions in other answers. Domain names could be validated in various ways.

If you need to validate IDN domain in it's human readable form, regex \p{L} will help. This allows to match any character in any language.

Note that last part might contain hyphens too! As punycode encoded Chineese names might have unicode characters in tld.

I've came to solution which will match for example:

  • google.com
  • maselkowski.pl
  • maselkowski.pl
  • m.maselkowski.pl
  • www.maselkowski.pl.com
  • xn--masekowski-d0b.pl
  • ??????????.??
  • xn--fiqa61au8b7zsevnm8ak20mc4a87e.xn--fiqs8s

Regex is:

^[0-9\p{L}][0-9\p{L}-\.]{1,61}[0-9\p{L}]\.[0-9\p{L}][\p{L}-]*[0-9\p{L}]+$

Check and tune here

NOTE: This regexp is quite permissive, as is current domain names allowed character set.

UPDATE: Even more simplified, as a-aA-Z\p{L} is same as just \p{L}

NOTE2: The only problem is that it will match domains with double dots in it... , like maselk..owski.pl. If anyone know how to fix this please improve.

How to read and write excel file

You can also consider JExcelApi. I find it better designed than POI. There's a tutorial here.

How to convert a string or integer to binary in Ruby?

If you are looking for a Ruby class/method I used this, and I have also included the tests:

class Binary
  def self.binary_to_decimal(binary)
    binary_array = binary.to_s.chars.map(&:to_i)
    total = 0

    binary_array.each_with_index do |n, i|
      total += 2 ** (binary_array.length-i-1) * n
    end
    total
   end
end

class BinaryTest < Test::Unit::TestCase
  def test_1
   test1 = Binary.binary_to_decimal(0001)
   assert_equal 1, test1
  end

 def test_8
    test8 = Binary.binary_to_decimal(1000)
    assert_equal 8, test8
 end

 def test_15
    test15 = Binary.binary_to_decimal(1111)
    assert_equal 15, test15
 end

 def test_12341
    test12341 = Binary.binary_to_decimal(11000000110101)
    assert_equal 12341, test12341
 end
end

Error: macro names must be identifiers using #ifdef 0

#ifdef 0
...
#endif

#ifdef expect a macro rather than expression when using constant or expression

#if 0
...
#endif

or

#if !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

if #ifdef is used the it reports this error

#ifdef !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

Where #ifdef expect a macro rather than macro expresssion

How to make a new line or tab in <string> XML (eclipse/android)?

Use \n for a line break and \t if you want to insert a tab.

You can also use some XML tags for basic formatting: <b> for bold text, <i> for italics, and <u> for underlined text

More info:

https://developer.android.com/guide/topics/resources/string-resource.html

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had a similar problem when I deployed my Flask app in the IIS. Apparently, IIS does not accept route that include an underline ("_"). When I removed the underline, problem was resolved.

Apply style to cells of first row

This should do the work:

.category_table tr:first-child td {
    vertical-align: top;
}

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Just add the following rules to the parent element:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

Here's a sample demo (Resize window to see the image align)

Browser support for Flexbox nowadays is quite good.

For cross-browser compatibility for display: flex and align-items, you can add the older flexbox syntax as well:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

How do I convert an array object to a string in PowerShell?

From a pipe

# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}

# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}

Write-Host

# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'

# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'

Example

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

jQuery iframe load() event?

Without code in iframe + animate:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">

function resizeIframe(obj) {

    jQuery(document).ready(function($) {

        $(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)

    });

}    
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >

Just what is an IntPtr exactly?

What is a Pointer?

In all languages, a pointer is a type of variable that stores a memory address, and you can either ask them to tell you the address they are pointing at or the value at the address they are pointing at.

A pointer can be thought of as a sort-of book mark. Except, instead of being used to jump quickly to a page in a book, a pointer is used to keep track of or map blocks of memory.

Imagine your program's memory precisely like one big array of 65535 bytes.

Pointers point obediently

Pointers remember one memory address each, and therefore they each point to a single address in memory.

As a group, pointers remember and recall memory addresses, obeying your every command ad nauseum.

You are their king.

Pointers in C#

Specifically in C#, a pointer is an integer variable that stores a memory address between 0 and 65534.

Also specific to C#, pointers are of type int and therefore signed.

You can't use negatively numbered addresses though, neither can you access an address above 65534. Any attempt to do so will throw a System.AccessViolationException.

A pointer called MyPointer is declared like so:

int *MyPointer;

A pointer in C# is an int, but memory addresses in C# begin at 0 and extend as far as 65534.

Pointy things should be handled with extra special care

The word unsafe is intended to scare you, and for a very good reason: Pointers are pointy things, and pointy things e.g. swords, axes, pointers, etc. should be handled with extra special care.

Pointers give the programmer tight control of a system. Therefore mistakes made are likely to have more serious consequences.

In order to use pointers, unsafe code has to be enabled in your program's properties, and pointers have to be used exclusively in methods or blocks marked as unsafe.

Example of an unsafe block

unsafe
{
    // Place code carefully and responsibly here.

}

How to use Pointers

When variables or objects are declared or instantiated, they are stored in memory.

  • Declare a pointer by using the * symbol prefix.

int *MyPointer;

  • To get the address of a variable, you use the & symbol prefix.

MyPointer = &MyVariable;

Once an address is assigned to a pointer, the following applies:

  • Without * prefix to refer to the memory address being pointed to as an int.

MyPointer = &MyVariable; // Set MyPointer to point at MyVariable

  • With * prefix to get the value stored at the memory address being pointed to.

"MyPointer is pointing at " + *MyPointer;

Since a pointer is a variable that holds a memory address, this memory address can be stored in a pointer variable.

Example of pointers being used carefully and responsibly

    public unsafe void PointerTest()
    {
        int x = 100; // Create a variable named x

        int *MyPointer = &x; // Store the address of variable named x into the pointer named MyPointer

        textBox1.Text = ((int)MyPointer).ToString(); // Displays the memory address stored in pointer named MyPointer

        textBox2.Text = (*MyPointer).ToString(); // Displays the value of the variable named x via the pointer named MyPointer.

    }

Notice the type of the pointer is an int. This is because C# interprets memory addresses as integer numbers (int).

Why is it int instead of uint?

There is no good reason.

Why use pointers?

Pointers are a lot of fun. With so much of the computer being controlled by memory, pointers empower a programmer with more control of their program's memory.

Memory monitoring.

Use pointers to read blocks of memory and monitor how the values being pointed at change over time.

Change these values responsibly and keep track of how your changes affect your computer.

Trigger change() event when setting <select>'s value with val() function

I separate it, and then use an identity comparison to dictate what is does next.

$("#selectField").change(function(){
  if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
  if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});

What is the difference between square brackets and parentheses in a regex?

These regexes are equivalent (for matching purposes):

  • /^(7|8|9)\d{9}$/
  • /^[789]\d{9}$/
  • /^[7-9]\d{9}$/

The explanation:

  • (a|b|c) is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9) to make it a non capturing group.

  • [abc] is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d] = [abcd])

The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def) which does not translate to a character class.

Assign variable value inside if-statement

I believe that your problem is due to the fact that you are defining the variable v inside the test. As explained by @rmalchow, it will work you change it into

int v;
if((v = someMethod()) != 0) return true;

There is also another issue of variable scope. Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it.

Variables exist only in the scope they were created. Since you are assigning the value to use it afterwards, consider the scope where you are creating the varible so that it may be used where needed.

Twitter Bootstrap add active class to li

$(function() {
// Highlight the active nav link.
var url = window.location.pathname;
var filename = url.substr(url.lastIndexOf('/') + 1);
$('.navbar a[href$="' + filename + '"]').parent().addClass("active");

});

For more details Click Here!

Authenticating against Active Directory with Java on Linux

Here's the code I put together based on example from this blog: LINK and this source: LINK.

import com.sun.jndi.ldap.LdapCtxFactory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;

class App2 {

    public static void main(String[] args) {

        if (args.length != 4 && args.length != 2) {
            System.out.println("Purpose: authenticate user against Active Directory and list group membership.");
            System.out.println("Usage: App2 <username> <password> <domain> <server>");
            System.out.println("Short usage: App2 <username> <password>");
            System.out.println("(short usage assumes 'xyz.tld' as domain and 'abc' as server)");
            System.exit(1);
        }

        String domainName;
        String serverName;

        if (args.length == 4) {
            domainName = args[2];
            serverName = args[3];
        } else {
            domainName = "xyz.tld";
            serverName = "abc";
        }

        String username = args[0];
        String password = args[1];

        System.out
                .println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);

        // bind by using the specified username/password
        Hashtable props = new Hashtable();
        String principalName = username + "@" + domainName;
        props.put(Context.SECURITY_PRINCIPAL, principalName);
        props.put(Context.SECURITY_CREDENTIALS, password);
        DirContext context;

        try {
            context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
            System.out.println("Authentication succeeded!");

            // locate this user's record
            SearchControls controls = new SearchControls();
            controls.setSearchScope(SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),
                    "(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls);
            if (!renum.hasMore()) {
                System.out.println("Cannot locate user information for " + username);
                System.exit(1);
            }
            SearchResult result = renum.next();

            List<String> groups = new ArrayList<String>();
            Attribute memberOf = result.getAttributes().get("memberOf");
            if (memberOf != null) {// null if this user belongs to no group at all
                for (int i = 0; i < memberOf.size(); i++) {
                    Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
                    Attribute att = atts.get("CN");
                    groups.add(att.get().toString());
                }
            }

            context.close();

            System.out.println();
            System.out.println("User belongs to: ");
            Iterator ig = groups.iterator();
            while (ig.hasNext()) {
                System.out.println("   " + ig.next());
            }

        } catch (AuthenticationException a) {
            System.out.println("Authentication failed: " + a);
            System.exit(1);
        } catch (NamingException e) {
            System.out.println("Failed to bind to LDAP / get account information: " + e);
            System.exit(1);
        }
    }

    private static String toDC(String domainName) {
        StringBuilder buf = new StringBuilder();
        for (String token : domainName.split("\\.")) {
            if (token.length() == 0)
                continue; // defensive check
            if (buf.length() > 0)
                buf.append(",");
            buf.append("DC=").append(token);
        }
        return buf.toString();
    }

}

High CPU Utilization in java application - why?

Your first approach should be to find all references to Thread.sleep and check that:

  1. Sleeping is the right thing to do - you should use some sort of wait mechanism if possible - perhaps careful use of a BlockingQueue would help.

  2. If sleeping is the right thing to do, are you sleeping for the right amount of time - this is often a very difficult question to answer.

The most common mistake in multi-threaded design is to believe that all you need to do when waiting for something to happen is to check for it and sleep for a while in a tight loop. This is rarely an effective solution - you should always try to wait for the occurrence.

The second most common issue is to loop without sleeping. This is even worse and is a little less easy to track down.

Reducing video size with same format and reducing frame size

ffmpeg -i <input.mp4> -b:v 2048k -s 1000x600 -fs 2048k -vcodec mpeg4 -acodec copy <output.mp4>
  • -i input file

  • -b:v videobitrate of output video in kilobytes (you have to try)

  • -s dimensions of output video

  • -fs FILESIZE of output video in kilobytes

  • -vcodec videocodec (use ffmpeg -codecs to list all available codecs)

  • -acodec audio codec for output video (only copy the audiostream, don't temper)

How can I convert radians to degrees with Python?

Python includes two functions in the math package; radians converts degrees to radians, and degrees converts radians to degrees.

To match the output of your calculator you need:

>>> math.cos(math.radians(1))
0.9998476951563913

Note that all of the trig functions convert between an angle and the ratio of two sides of a triangle. cos, sin, and tan take an angle in radians as input and return the ratio; acos, asin, and atan take a ratio as input and return an angle in radians. You only convert the angles, never the ratios.

What's the right way to pass form element state to sibling/parent elements?

With React >= 16.3 you can use ref and forwardRef, to gain access to child's DOM from its parent. Don't use old way of refs anymore.
Here is the example using your case :

import React, { Component } from 'react';

export default class P extends React.Component {
   constructor (props) {
      super(props)
      this.state = {data: 'test' }
      this.onUpdate = this.onUpdate.bind(this)
      this.ref = React.createRef();
   }

   onUpdate(data) {
      this.setState({data : this.ref.current.value}) 
   }

   render () {
      return (
        <div>
           <C1 ref={this.ref} onUpdate={this.onUpdate}/>
           <C2 data={this.state.data}/>
        </div>
      )
   }
}

const C1 = React.forwardRef((props, ref) => (
    <div>
        <input type='text' ref={ref} onChange={props.onUpdate} />
    </div>
));

class C2 extends React.Component {
    render () {
       return <div>C2 reacts : {this.props.data}</div>
    }
}

See Refs and ForwardRef for detailed info about refs and forwardRef.

Making text background transparent but not text itself

box-shadow: inset 1px 2000px rgba(208, 208, 208, 0.54);

What does "fatal: bad revision" mean?

I had a similar issue with Intellij. The issue was that someone added the file that I am trying to compare in Intellij to .gitignore, without actually deleting the file from Git.

JavaScript regex for alphanumeric string with length of 3-5 chars

First this script test the strings N having chars from 3 to 5.

For multi language (arabic, Ukrainian) you Must use this

var regex = /^([a-zA-Z0-9_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]+){3,5}$/;  regex.test('?????');

Other wise the below is for English Alphannumeric only

/^([a-zA-Z0-9_-]){3,5}$/

P.S the above dose not accept special characters

one final thing the above dose not take space as test it will fail if there is space if you want space then add after the 0-9\s

\s

And if you want to check lenght of all string add dot .

var regex = /^([a-zA-Z0-9\s@,!=%$#&_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]).{1,30}$/;

How to get nth jQuery element

For iterations using a selector doesn't seem to make any sense though:

var some = $( '...' );

for( i = some.length -1; i>=0; --i )
{
   // Have to transform in a jquery object again:
   //
   var item = $( some[ i ] );

   // use item at will
   // ...
}

Word wrap for a label in Windows Forms

Have a better one based on @hypo 's answer

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing)
            return;
        try {
            mGrowing = true;
            int width = this.Parent == null ? this.Width : this.Parent.Width;

            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height + Padding.Bottom + Padding.Top;
        } finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}

int width = this.Parent == null ? this.Width : this.Parent.Width; this allows you to use auto-grow label when docked to a parent, e.g. a panel.

this.Height = sz.Height + Padding.Bottom + Padding.Top; here we take care of padding for top and bottom.

postgresql sequence nextval in schema

The quoting rules are painful. I think you want:

SELECT nextval('foo."SQ_ID"');

to prevent case-folding of SQ_ID.

Editing specific line in text file in Python

def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()

And then:

replace_line('stats.txt', 0, 'Mage')

WCF error: The caller was not authenticated by the service

If you use basicHttpBinding, configure the endpoint security to "None" and transport clientCredintialType to "None."

<bindings>
    <basicHttpBinding>
        <binding name="MyBasicHttpBinding">
            <security mode="None">
                <transport clientCredentialType="None" />
            </security>
        </binding>
    </basicHttpBinding>
</bindings>
<services>
    <service behaviorConfiguration="MyServiceBehavior" name="MyService">
        <endpoint 
            binding="basicHttpBinding" 
            bindingConfiguration="MyBasicHttpBinding"
            name="basicEndPoint"    
            contract="IMyService" 
        />
</service>

Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access

Why is this HTTP request not working on AWS Lambda?

enter image description here

Add above code in API gateway under GET-Integration Request> mapping section.

How to remove last n characters from a string in Bash?

First, it's usually better to be explicit about your intent. So if you know the string ends in .rtf, and you want to remove that .rtf, you can just use var2=${var%.rtf}. One potentially-useful aspect of this approach is that if the string doesn't end in .rtf, it is not changed at all; var2 will contain an unmodified copy of var.

If you want to remove a filename suffix but don't know or care exactly what it is, you can use var2=${var%.*} to remove everything starting with the last .. Or, if you only want to keep everything up to but not including the first ., you can use var2=${var%%.*}. Those options have the same result if there's only one ., but if there might be more than one, you get to pick which end of the string to work from. On the other hand, if there's no . in the string at all, var2 will again be an unchanged copy of var.

If you really want to always remove a specific number of characters, here are some options.

You tagged this bash specifically, so we'll start with bash builtins. The one which has worked the longest is the same suffix-removal syntax I used above: to remove four characters, use var2=${var%????}. Or to remove four characters only if the first one is a dot, use var2=${var%.???}, which is like var2=${var%.*} but only removes the suffix if the part after the dot is exactly three characters. As you can see, to count characters this way, you need one question mark per unknown character removed, so this approach gets unwieldy for larger substring lengths.

An option in newer shell versions is substring extraction: var2=${var:0:${#var}-4}. Here you can put any number in place of the 4 to remove a different number of characters. The ${#var} is replaced by the length of the string, so this is actually asking to extract and keep (length - 4) characters starting with the first one (at index 0). With this approach, you lose the option to make the change only if the string matches a pattern; no matter what the actual value of the string is, the copy will include all but its last four characters.

Bash lets you leave the start index out; it defaults to 0, so you can shorten that to just var2=${var::${#var}-4}. In fact, newer versions of bash (specifically 4+, which means the one that ships with MacOS won't work) recognize negative lengths as end indexes counting back from the end of the string, so you can get rid of the string-length expression, too: var2=${var::-4}.

If you're not actually using bash but some other POSIX-type shell, the pattern-based suffix removal with % will still work – even in plain old dash, where the index-based substring extraction won't. Ksh and zsh do both support substring extraction, but require the explicit 0 start index; zsh also supports the negative end index, while ksh requires the length expression. Note that zsh, which indexes arrays starting at 1, nonetheless indexes strings starting at 0 if you use this bash-compatible syntax; but you can also treat parameters as arrays of characters, in which case it uses a 1-based count and expects a start and inclusive end position in brackets: var2=$var[1,-5].

Instead of using built-in shell parameter expansion, you can of course run some utility program to modify the string and capture its output with command substitution. There are several commands that will work; one is var2=$(sed 's/.\{4\}$//' <<<"$var").

How do I access call log for android?

use this method from everywhere with a context

private static String getCallDetails(Context context) {
    StringBuffer stringBuffer = new StringBuffer();
    Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
            null, null, null, CallLog.Calls.DATE + " DESC");
    int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = cursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);       
    while (cursor.moveToNext()) {
        String phNumber = cursor.getString(number);
        String callType = cursor.getString(type);
        String callDate = cursor.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = cursor.getString(duration);
        String dir = null;
        int dircode = Integer.parseInt(callType);
        switch (dircode) {
        case CallLog.Calls.OUTGOING_TYPE:
            dir = "OUTGOING";
            break;
        case CallLog.Calls.INCOMING_TYPE:
            dir = "INCOMING";
            break;

        case CallLog.Calls.MISSED_TYPE:
            dir = "MISSED";
            break;
        }
        stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
                + dir + " \nCall Date:--- " + callDayTime
                + " \nCall duration in sec :--- " + callDuration);
        stringBuffer.append("\n----------------------------------");
    }
    cursor.close();
    return stringBuffer.toString();
}

How to set focus on an input field after rendering?

@Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:

<input autoFocus name=...

Note that in jsx it's autoFocus (capital F) unlike plain old html which is case-insensitive.

Notepad++ Regular expression find and delete a line

Provide the following in the search dialog:

Find What: ^$\r\n
Replace With: (Leave it empty)

Click Replace All

DateTimePicker time picker in 24 hour but displaying in 12hr?

$(function () {
    $('#startTime, #endTimeContent').datetimepicker({
        format: 'HH:mm',
        pickDate: false,
        pickSeconds: false,
        pick12HourFormat: false            
    });
});

your selector seems to be wrong,please check it

JavaScript string newline character?

yes use \n, unless you are generating html code, in which you want to use <br />

how to get the value of a textarea in jquery?

You should check the textarea is null before you use val() otherwise, you will get undefined error.

if ($('textarea#message') != undefined) {
   var message = $('textarea#message').val();
}

Then, you could do whatever with message.

Vue template or render function not defined yet I am using neither?

I personally ran into the same error. None of the above solutions worked for me.

In fact, my component looks like this (in a file called my-component.js) :

Vue.component('my-component', {
    data() {
        return {
            ...
        }
    },
    props: {
        ...
    },
    template:`
        <div>
            ...
        </div>
    `
});

And I imported it like this in another component:

import MyComponent from '{path-to-folder}/my-component';

Vue.component('parent_component', {
    components: {
        MyComponent
    }
});

The weird thing is that this worked in some components but not in this "parent_component". So what I had to do in the component itself was stock it in a variable and export it as default.

const MyComponent = Vue.component('my-component', {
    data() {
        return {
            ...
        }
    },
    props: {
        ...
    },
    template:`
        <div>
            ...
        </div>
    `
});

export default MyComponent;

It could seem obvious but as I said above, it works in 1 other component without this so I couldn't really understand why, but at least, this works everywhere now.

How to handle query parameters in angular 2

It seems that RouteParams no longer exists, and is replaced by ActivatedRoute. ActivatedRoute gives us access to the matrix URL notation Parameters. If we want to get Query string ? paramaters we need to use Router.RouterState. The traditional query string paramaters are persisted across routing, which may not be the desired result. Preserving the fragment is now optional in router 3.0.0-rc.1.

import { Router, ActivatedRoute } from '@angular/router';
@Component ({...})
export class paramaterDemo {
  private queryParamaterValue: string;
  private matrixParamaterValue: string;
  private querySub: any;
  private matrixSub: any;

  constructor(private router: Router, private route: ActivatedRoute) { }
  ngOnInit() {
    this.router.routerState.snapshot.queryParams["queryParamaterName"];
    this.querySub = this.router.routerState.queryParams.subscribe(queryParams => 
      this.queryParamaterValue = queryParams["queryParameterName"];
    );

    this.route.snapshot.params["matrixParameterName"];
    this.route.params.subscribe(matrixParams =>
      this.matrixParamterValue = matrixParams["matrixParameterName"];
    );
  }

  ngOnDestroy() {
    if (this.querySub) {
      this.querySub.unsubscribe();
    }
    if (this.matrixSub) {
      this.matrixSub.unsubscribe();
    }
  }
}

We should be able to manipulate the ? notation upon navigation, as well as the ; notation, but I only gotten the matrix notation to work yet. The plnker that is attached to the latest router documentation shows it should look like this.

let sessionId = 123456789;
let navigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

How to export datagridview to excel using vb.net?

another easy way and more flexible , after loading data into Datagrid

Private Sub Button_Export_Click(sender As Object, e As EventArgs) Handles Button_Export.Click
    Dim file As System.IO.StreamWriter
    file = My.Computer.FileSystem.OpenTextFileWriter("c:\1\Myfile.csv", True)
    If DataGridView1.Rows.Count = 0 Then GoTo loopend

    ' collect the header's names 
    Dim Headerline As String
    For k = 0 To DataGridView1.Columns.Count - 1
        If k = DataGridView1.Columns.Count - 1 Then ' last column dont put , separate 
            Headerline = Headerline & DataGridView1.Columns(k).HeaderText
        Else
            Headerline = Headerline & DataGridView1.Columns(k).HeaderText & ","
        End If
    Next
    file.WriteLine(Headerline)  ' this will write header names at the first line 
    ' collect the data 

    For i = 0 To DataGridView1.Rows.Count - 1
        Dim DataRow As String
        For k = 0 To DataGridView1.Columns.Count - 1
            If k = DataGridView1.Columns.Count - 1 Then
                DataRow = DataRow & DataGridView1.Rows(i).Cells(k).Value ' last column dont put , separate 
            End If
            DataRow = DataRow & DataGridView1.Rows(i).Cells(k).Value & ","
        Next

        file.WriteLine(DataRow)
        DataRow = ""
    Next



loopend:
        file.Close()
End Sub

Refresh Fragment at reload

In case you do not have the fragment tag, the following code works well for me.

Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (currentFragment instanceof "NAME OF YOUR FRAGMENT CLASS") {
 FragmentTransaction fragTransaction =   (getActivity()).getFragmentManager().beginTransaction();
 fragTransaction.detach(currentFragment);
 fragTransaction.attach(currentFragment);
 fragTransaction.commit();}
}

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

Best way to test if a row exists in a MySQL table

Or you can insert raw sql part to conditions so I have 'conditions'=>array('Member.id NOT IN (SELECT Membership.member_id FROM memberships AS Membership)')

Best way to do multi-row insert in Oracle?

In Oracle, to insert multiple rows into table t with columns col1, col2 and col3 you can use the following syntax:

INSERT ALL
   INTO t (col1, col2, col3) VALUES ('val1_1', 'val1_2', 'val1_3')
   INTO t (col1, col2, col3) VALUES ('val2_1', 'val2_2', 'val2_3')
   INTO t (col1, col2, col3) VALUES ('val3_1', 'val3_2', 'val3_3')
   .
   .
   .
SELECT 1 FROM DUAL;

How to sort by Date with DataTables jquery plugin?

Follow the link https://datatables.net/blog/2014-12-18

A very easy way to integrate ordering by date.

<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script>

Put this code in before initializing the datatable:

$(document).ready(function () {
    // ......
    $.fn.dataTable.moment('DD-MMM-YY HH:mm:ss');
    $.fn.dataTable.moment('DD.MM.YYYY HH:mm:ss');
    // And any format you need
}

Export query result to .csv file in SQL Server 2008

  1. Open SQL Server Management Studio
  2. Go to Tools > Options > Query Results > SQL Server > Results To Text
  3. On the far right, there is a drop down box called Output Format
  4. Choose Comma Delimited and click OK

Here's a full screen version of that image, below

enter image description here

This will show your query results as comma-delimited text.

To save the results of a query to a file: Ctrl + Shift + F

PowerShell : retrieve JSON object by field value

David Brabant's answer led me to what I needed, with this addition:

x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type

How do I rename both a Git local and remote branch name?

  • Rename your local branch.

If you are on the branch you want to rename:

git branch -m new-name

if you stay on a different branch at the current time:

git branch -m old-name new-name
  • Delete the old-name remote branch and push the new-name local branch.

Stay on the target branch and:

git push origin :old-name new-name
  • Reset the upstream branch for the new-name local branch.

Switch to the target branch and then:

git push origin -u new-name

MVC Razor @foreach

a reply to @DarinDimitrov for a case where i have used foreach in a razor view.

<li><label for="category">Category</label>
        <select id="category">
            <option value="0">All</option>
            @foreach(Category c in Model.Categories)
            {
                <option title="@c.Description" value="@c.CategoryID">@c.Name</option>
            }
        </select>
</li>

How do I get the collection of Model State Errors in ASP.NET MVC?

If you don't know what property caused the error, you can, using reflection, loop over all properties:

public static String ShowAllErrors<T>(this HtmlHelper helper) {
    StringBuilder sb = new StringBuilder();
    Type myType = typeof(T);
    PropertyInfo[] propInfo = myType.GetProperties();

    foreach (PropertyInfo prop in propInfo) {
        foreach (var e in helper.ViewData.ModelState[prop.Name].Errors) {
            TagBuilder div = new TagBuilder("div");
            div.MergeAttribute("class", "field-validation-error");
            div.SetInnerText(e.ErrorMessage);
            sb.Append(div.ToString());
        }
    }
    return sb.ToString();
}

Where T is the type of your "ViewModel".

Right to Left support for Twitter Bootstrap 3

Bootstrap Persian version of the site http://rbootstrap.ir/ Ver.2.3.2

Default instance name of SQL Server Express

If you navigate to where you have installed SQLExpress, e.g.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn

You can run SQLLocalDB.exe and get a list of the all instances installed on your machine.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info
MSSQLLocalDB
ProjectsV12
v11.0

Then you can get further information on the instance.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info MSSQLLocalDB Name: MSSQLLocalDB
Version: 13.0.1601.5
Shared name:
Owner: Domain\User
Auto-create: Yes
State: Stopped
Last start time: 22/09/2016 10:19:33
Instance pipe name:

How to Set a Custom Font in the ActionBar Title?

TRY THIS

public void findAndSetFont(){
        getActionBar().setTitle("SOME TEST TEXT");
        scanForTextViewWithText(this,"SOME TEST TEXT",new SearchTextViewInterface(){

            @Override
            public void found(TextView title) {

            } 
        });
    }

public static void scanForTextViewWithText(Activity activity,String searchText, SearchTextViewInterface searchTextViewInterface){
    if(activity == null|| searchText == null || searchTextViewInterface == null)
        return;
    View view = activity.findViewById(android.R.id.content).getRootView();
    searchForTextViewWithTitle(view, searchText, searchTextViewInterface);
}

private static void searchForTextViewWithTitle(View view, String searchText, SearchTextViewInterface searchTextViewInterface)
{
    if (view instanceof ViewGroup)
    {
        ViewGroup g = (ViewGroup) view;
        int count = g.getChildCount();
        for (int i = 0; i < count; i++)
            searchForTextViewWithTitle(g.getChildAt(i), searchText, searchTextViewInterface);
    }
    else if (view instanceof TextView)
    {
        TextView textView = (TextView) view;
        if(textView.getText().toString().equals(searchText))
            if(searchTextViewInterface!=null)
                searchTextViewInterface.found(textView);
    }
}
public interface SearchTextViewInterface {
    void found(TextView title);
}

jQuery datepicker to prevent past date

I am using following code to format date and show 2 months in calendar...

<script>
$(function() {

    var dates = $( "#from, #to" ).datepicker({

        showOn: "button",
        buttonImage: "imgs/calendar-month.png",
        buttonImageOnly: true,                           
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 2,

        onSelect: function( selectedDate ) {




            $( ".selector" ).datepicker({ defaultDate: +7 });
            var option = this.id == "from" ? "minDate" : "maxDate",


                instance = $( this ).data( "datepicker" ),
                date = $.datepicker.parseDate(
                    instance.settings.dateFormat ||
                    $.datepicker._defaults.dateFormat,
                    selectedDate, instance.settings );

            dates.not( this ).datepicker( "option", "dateFormat", 'yy-mm-dd' );


        }
    });
});

</script>

The problem is I am not sure how to restrict previous dates selection.

Round up to Second Decimal Place in Python

Here is a more general one-liner that works for any digits:

import math
def ceil(number, digits) -> float: return math.ceil((10.0 ** digits) * number) / (10.0 ** digits)

Example usage:

>>> ceil(1.111111, 2)
1.12

Caveat: as stated by nimeshkiranverma:

>>> ceil(1.11, 2) 
1.12  #Because: 1.11 * 100.0 has value 111.00000000000001

Check if image exists on server using JavaScript?

You can just check if the image loads or not by using the built in events that is provided for all images.

The onload and onerror events will tell you if the image loaded successfully or if an error occured :

var image = new Image();

image.onload = function() {
    // image exists and is loaded
    document.body.appendChild(image);
}
image.onerror = function() {
    // image did not load

    var err = new Image();
    err.src = '/error.png';

    document.body.appendChild(err);
}

image.src = "../imgs/6.jpg";

Pygame Drawing a Rectangle

here's how:

import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
pygame.quit()

How to send FormData objects with Ajax-requests in jQuery?

You can send the FormData object in ajax request using the following code,

$("form#formElement").submit(function(){
    var formData = new FormData($(this)[0]);
});

This is very similar to the accepted answer but an actual answer to the question topic. This will submit the form elements automatically in the FormData and you don't need to manually append the data to FormData variable.

The ajax method looks like this,

$("form#formElement").submit(function(){
    var formData = new FormData($(this)[0]);
    //append some non-form data also
    formData.append('other_data',$("#someInputData").val());
    $.ajax({
        type: "POST",
        url: postDataUrl,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
           //process data
        },
        error: function(data, textStatus, jqXHR) {
           //process error msg
        },
});

You can also manually pass the form element inside the FormData object as a parameter like this

var formElem = $("#formId");
var formdata = new FormData(formElem[0]);

Hope it helps. ;)

Upgrade Node.js to the latest version on Mac OS

Because this seems to be at the top of Google when searching for how to upgrade nodejs on mac I will offer my tip for anyone coming along in the future despite its age.

Upgrading via NPM
You can use the method described by @Mathias above or choose the following simpler method via the terminal.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

After which you may opt to confirm the upgrade

node -v

Your nodejs should have upgraded to the latest version. If you wish to upgrade to a specific one say v0.8.19 then instead of

sudo n stable

use

sudo n 0.8.19

EDIT Avoid using sudo unless you need to. Refer to comment by Steve in the comments

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

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

Download android SDK from developer.android.com (its currently a 149mb file for windows OS). It is worthy of note that android has removed the sdkmanager GUI but has a command line version of the sdkmanager in the bin folder which is located inside the tools folder.

  1. When inside the bin folder, hold down the shift key, right click, then select open command line here. Shift+right click >> open command line here.
  2. When the command line opens, type sdkmanager click enter.
  3. Then run type sdkmanager (space), double hyphen (--), type list sdkmanager --list (this lists all the packages in the SDK manager)
  4. Type sdkmanager (space) then package name, press enter. Eg. sdkmanager platform-tools (press enter) It will load licence agreement. With options (y/n). Enter y to accept and it will download the package you specified.

For more reference follow official document here

I hope this helps. :)

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

If changing the name did not work run setup with \layout argument.

How to set java_home on Windows 7?

We need to make a distinction between the two environment variables that are discussed here interchangeably. One is the JAVA_HOME variable. The other is the Path variable. Any process that references the JAVA_HOME variable is looking for the search path to the JDK, not the JRE. The use of JAVA_HOME variable is not meant for the Java compiler itself. The compiler is aware of its own location. The variable is meant for other software to more easily locate the compiler. This variable is typically used by IDE software in order to compile and build applications from Java source code. By contrast, the Windows CMD interpreter, and many other first and third party software references the Path variable, not the JAVA_HOME variable.

Use case 1: Compiling from CMD

So for instance, if you are not using any IDE software, and you just want to be able to compile from the CMD, independent of your current working directory, then what you want is to set the Path variable correctly. In your case, you don't even need the JAVA_HOME variable. Because CMD is using Path, not JAVA_HOME to locate the Java compiler.

Use case 2: Compiling from IDE

However, if you are using some IDE software, then you have to look at the documentation first of all. It may require JAVA_HOME to be set, but it may also use another variable name for the same purpose. The de-facto standard over the years has been JAVA_HOME, but this may not always be the case.

Use case 3: Compiling from IDE and CMD

If in addition to the IDE software you also want to be able to compile from the CMD, independent of your current working directory, then in addition to the JAVA_HOME variable you may also need to append the JDK search path to the Path variable.

JAVA_HOME vs. Path

If your problem relates to compiling Java, then you want to check the JAVA_HOME variable, and Path (where applicable). If your problem relates to running Java applications, then you want to check your Path variable.

Path variable is used universally across all operating systems. Because it is defined by the system, and because it's the default variable that's used for locating the JRE, there is almost never any problem running Java applications. Especially not on Windows where the software installers usually set everything up for you. But if you are installing manually, the safest thing to do is perhaps to skip the JAVA_HOME variable altogether and just use the Path variable for everything, for both JDK and the JRE. Any recent version of an IDE software should be able to pick that up and use it.

Symlinks

Symbolic links may provide yet another way to reference the JDK search path by piggybacking one of the existing environment variables.

I am not sure about previous versions of Oracle/Sun JDK/JRE releases, but at least the installer for jdk1.8.0_74 appends the search path C:\ProgramData\Oracle\Java\javapath to the Path variable, and it puts it at the beginning of the string value. This directory contains symbolic links to the java.exe, javaw.exe and javaws.exe in the JRE directory.

So at least with the Java 8 JDK, and presumably the Java 8 JRE standalone, no environment variable configuration needs to be done for the JRE. As long as you use the installer package to set it up. There may be differences on your Windows installation however. Note that the Oracle JRE comes bundled with the JDK.

If you ever find that your Java JDK configuration is using the wrong version of the compiler, or it appears to be working by magic, without being explicitly defined so (without casting the spell), then you may have a symlink somewhere in your environment variables. So you may want to check for symlink.

The thread has exited with code 0 (0x0) with no unhandled exception

I have also faced this problem and the solution is:

  1. open Solution Explore
  2. double click on Program.cs file

I added this code again and my program ran accurately:

Application.Run(new PayrollSystem()); 
//File name this code removed by me accidentally.

Remove all unused resources from an android project

In Android Studio,

Analyze -> Run Inspection by Name

(Shortcut For Mac shift+command+option+i , Ctrl + Shift + A on Windows/Linux).

And type 'unused resources'.

This way you can remove unused resources, variables ,symbols ,localization ,libraries ..etc.

Select the desired inspection from the list, then select inspection scope ->OK enter image description here

Comments in Android Layout xml

XML comments start with <!-- and end with -->.

For example:

<!-- This is a comment. -->

Using "margin: 0 auto;" in Internet Explorer 8

Add <!doctype html> at the top of your HTML output.

How to check if an excel cell is empty using Apache POI?

.getCellType() != Cell.CELL_TYPE_BLANK

Regular expression field validation in jQuery

If you wanted to search some elements based on a regex, you can use the filter function. For example, say you wanted to make sure that in all the input boxes, the user has only entered numbers, so let's find all the inputs which don't match and highlight them.

$("input:text")
    .filter(function() {
        return this.value.match(/[^\d]/);
    })
    .addClass("inputError")
;

Of course if it was just something like this, you could use the form validation plugin, but this method could be applied to any sort of elements you like. Another example to show what I mean: Find all the elements whose id matches /[a-z]+_\d+/

$("[id]").filter(function() {
    return this.id.match(/[a-z]+_\d+/);
});

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

how to access downloads folder in android?

For your first question try

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 

(available since API 8)

To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.

FTP/SFTP access to an Amazon S3 Bucket

WinSCp now supports S3 protocol

First, make sure your AWS user with S3 access permissions has an “Access key ID” created. You also have to know the “Secret access key”. Access keys are created and managed on Users page of IAM Management Console.

Make sure New site node is selected.

On the New site node, select Amazon S3 protocol.

Enter your AWS user Access key ID and Secret access key

Save your site settings using the Save button.

Login using the Login button.

Load image with jQuery and append it to the DOM

With jQuery 3.x use something like:

$('<img src="'+ imgPath +'">').on('load', function() {
  $(this).width(some).height(some).appendTo('#some_target');
});

Getting View's coordinates relative to the root layout

I just found the answer here

It says: It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

so use:

view.getLeft(); // to get the location of X from left to right
view.getRight()+; // to get the location of Y from right to left

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

There is a simple trick for this. After you constructed the frame with all it buttons do this:

frame.getRootPane().setDefaultButton(submitButton);

For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.


And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:

@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode()==KeyEvent.VK_ENTER){
        System.out.println("Hello");

        JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
    }

}

UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:

SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);

"cannot resolve symbol R" in Android Studio

None of the above answers helped me. I finally realized that the issue was that the "build" folder was missing from Android Studio. I found a number of lines in the projects "iml" file excluding "build/*". After removing those, the build file appeared and the errors disappeared.

Database cluster and load balancing

Database Clustering is actually a mode of synchronous replication between two or possibly more nodes with an added functionality of fault tolerance added to your system, and that too in a shared nothing architecture. By shared nothing it means that the individual nodes actually don't share any physical resources like disk or memory.

As far as keeping the data synchronized is concerned, there is a management server to which all the data nodes are connected along with the SQL node to achieve this(talking specifically about MySQL).

Now about the differences: load balancing is just one result that could be achieved through clustering, the others include high availability, scalability and fault tolerance.

Plotting two variables as lines using ggplot2 on the same graph

You need the data to be in "tall" format instead of "wide" for ggplot2. "wide" means having an observation per row with each variable as a different column (like you have now). You need to convert it to a "tall" format where you have a column that tells you the name of the variable and another column that tells you the value of the variable. The process of passing from wide to tall is usually called "melting". You can use tidyr::gather to melt your data frame:

library(ggplot2)
library(tidyr)

test_data <-
  data.frame(
    var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
    var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
    date = seq(as.Date("2002-01-01"), by="1 month", length.out=100)
  )
test_data %>%
    gather(key,value, var0, var1) %>%
    ggplot(aes(x=date, y=value, colour=key)) +
    geom_line()

multiple series ggplot2

Just to be clear the data that ggplot is consuming after piping it via gather looks like this:

date        key     value
2002-01-01  var0    100.00000
2002-02-01  var0    115.16388 
...
2007-11-01  var1    114.86302
2007-12-01  var1    119.30996

CSS3 Transparency + Gradient

Yes. You can use rgba in both webkit and moz gradient declarations:

/* webkit example */
background-image: -webkit-gradient(
  linear, left top, left bottom, from(rgba(50,50,50,0.8)),
  to(rgba(80,80,80,0.2)), color-stop(.5,#333333)
);

(src)

/* mozilla example - FF3.6+ */
background-image: -moz-linear-gradient(
  rgba(255, 255, 255, 0.7) 0%, rgba(255, 255, 255, 0) 95%
);

(src)

Apparently you can even do this in IE, using an odd "extended hex" syntax. The first pair (in the example 55) refers to the level of opacity:

/* approximately a 33% opacity on blue */
filter: progid:DXImageTransform.Microsoft.gradient(
  startColorstr=#550000FF, endColorstr=#550000FF
);

/* IE8 uses -ms-filter for whatever reason... */
-ms-filter: progid:DXImageTransform.Microsoft.gradient(
  startColorstr=#550000FF, endColorstr=#550000FF
);

(src)

Best/Most Comprehensive API for Stocks/Financial Data

Yahoo's api provides a CSV dump:

Example: http://finance.yahoo.com/d/quotes.csv?s=msft&f=price

I'm not sure if it is documented or not, but this code sample should showcase all of the features (namely the stat types [parameter f in the query string]. I'm sure you can find documentation (official or not) if you search for it.

http://www.goldb.org/ystockquote.html

Edit

I found some unofficial documentation:

http://ilmusaham.wordpress.com/tag/stock-yahoo-data/

Get all photos from Instagram which have a specific hashtag with PHP

There is the instagram public API's tags section that can help you do this.

Best way to include CSS? Why use @import?

I think the key in this are the two reasons why you are actually writing multiple CSS style sheets.

  1. You write multiple sheets because the different pages of your website require different CSS definitions. Or at least not all of them require all the CSS definitions one other pages require. So you split up the CSS files in order to optimize what sheets are load on the different pages and avoid loading too many CSS definitions.
  2. The second reason that comes to mind is that your CSS is getting that large that is becomes clumsy to handle and in order to make it easier to maintain the large CSS file you split them up into multiple CSS files.

For the first reason the additional <link> tag would apply as this allows you to load different set of CSS files for different pages.

For the second reason the @import statement appears as the most handy because you get multiple CSS files but the files loaded are always the same.

From the perspective of the loading time there is no different. The browser has to check and download the seperated CSS files no matter how they are implemented.

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

How do I collapse a table row in Bootstrap?

You can do this without any JavaScript involved

(Using accepted answer)

HTML

<table class="table table-bordered table-striped">
    <tr>
        <td><button class="btn" data-target="#collapseme" data-toggle="collapse" type="button">Click to expand</button></td>
    </tr>
    <tr>
        <td class="nopadding">
            <div class="collapse" id="collapseme">
                <div class="content">
                    Show me collapsed
                </div>
            </div>
        </td>
    </tr>
</table>

CSS

.nopadding {
    padding: 0 !important;
}

.content {
    padding: 20px;
}

Null check in an enhanced for loop

Use, CollectionUtils.isEmpty(Collection coll) method which is Null-safe check if the specified collection is empty.

for this import org.apache.commons.collections.CollectionUtils.

Maven dependency

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.0</version>
</dependency>

Add custom icons to font awesome

Depends on what you have. If your svg icon is just a path, then it's easy enough to add that glyph by just copying the 'd' attribute to a new <glyph> element. However, the path needs to be scaled to the font's coordinate system (the EM-square, which typically is [0,0,2048,2048] - the standard for Truetype fonts) and aligned with the baseline you want.

Not all browsers support svg fonts however, so you're going to have to convert it to other formats too if you want it to work everywhere.

Fontforge can import svg files (select a glyph slot, File > Import and then select your svg image), and you can then convert to all the relevant font formats (svg, truetype, woff etc).

MS Access - execute a saved query by name in VBA

To use CurrentDb.Execute, your query must be an action query, AND in quotes.

CurrentDb.Execute "queryname"

Expand/collapse section in UITableView in iOS

I've used a NSDictionary as datasource, this looks like a lot of code, but it's really simple and works very well! how looks here

I created a enum for the sections

typedef NS_ENUM(NSUInteger, TableViewSection) {

    TableViewSection0 = 0,
    TableViewSection1,
    TableViewSection2,
    TableViewSectionCount
};

sections property:

@property (nonatomic, strong) NSMutableDictionary * sectionsDisctionary;

A method returning my sections:

-(NSArray <NSNumber *> * )sections{

    return @[@(TableViewSection0), @(TableViewSection1), @(TableViewSection2)];
}

And then setup my data soruce:

-(void)loadAndSetupData{

    self.sectionsDisctionary = [NSMutableDictionary dictionary];

    NSArray * sections = [self sections];

    for (NSNumber * section in sections) {

    NSArray * sectionObjects = [self objectsForSection:section.integerValue];

    [self.sectionsDisctionary setObject:[NSMutableDictionary dictionaryWithDictionary:@{@"visible" : @YES, @"objects" : sectionObjects}] forKey:section];
    }
}

-(NSArray *)objectsForSection:(NSInteger)section{

    NSArray * objects;

    switch (section) {

        case TableViewSection0:

            objects = @[] // objects for section 0;
            break;

        case TableViewSection1:

            objects = @[] // objects for section 1;
            break;

        case TableViewSection2:

            objects = @[] // objects for section 2;
            break;

        default:
            break;
    }

    return objects;
}

The next methods, will help you to know when a section is opened, and how to respond to tableview datasource:

Respond the section to datasource:

/**
 *  Asks the delegate for a view object to display in the header of the specified section of the table view.
 *
 *  @param tableView The table-view object asking for the view object.
 *  @param section   An index number identifying a section of tableView .
 *
 *  @return A view object to be displayed in the header of section .
 */
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    NSString * headerName = [self titleForSection:section];

    YourCustomSectionHeaderClass * header = (YourCustomSectionHeaderClass *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:YourCustomSectionHeaderClassIdentifier];

    [header setTag:section];
    [header addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]];
    header.title = headerName;
    header.collapsed = [self sectionIsOpened:section];


    return header;
}

/**
 * Asks the data source to return the number of sections in the table view
 *
 * @param An object representing the table view requesting this information.
 * @return The number of sections in tableView.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    // Return the number of sections.

    return self.sectionsDisctionary.count;
}

/**
 * Tells the data source to return the number of rows in a given section of a table view
 *
 * @param tableView: The table-view object requesting this information.
 * @param section: An index number identifying a section in tableView.
 * @return The number of rows in section.
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    BOOL sectionOpened = [self sectionIsOpened:section];
    return sectionOpened ? [[self objectsForSection:section] count] : 0;
}

Tools:

/**
 Return the section at the given index

 @param index the index

 @return The section in the given index
 */
-(NSMutableDictionary *)sectionAtIndex:(NSInteger)index{

    NSString * asectionKey = [self.sectionsDisctionary.allKeys objectAtIndex:index];

    return [self.sectionsDisctionary objectForKey:asectionKey];
}

/**
 Check if a section is currently opened

 @param section the section to check

 @return YES if is opened
 */
-(BOOL)sectionIsOpened:(NSInteger)section{

    NSDictionary * asection = [self sectionAtIndex:section];
    BOOL sectionOpened = [[asection objectForKey:@"visible"] boolValue];

    return sectionOpened;
}


/**
 Handle the section tap

 @param tap the UITapGestureRecognizer
 */
- (void)handleTapGesture:(UITapGestureRecognizer*)tap{

    NSInteger index = tap.view.tag;

    [self toggleSection:index];
}

Toggle section visibility

/**
 Switch the state of the section at the given section number

 @param section the section number
 */
-(void)toggleSection:(NSInteger)section{

    if (index >= 0){

        NSMutableDictionary * asection = [self sectionAtIndex:section];

        [asection setObject:@(![self sectionIsOpened:section]) forKey:@"visible"];

        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
    }
}

Truncating long strings with CSS: feasible yet?

OK, Firefox 7 implemented text-overflow: ellipsis as well as text-overflow: "string". Final release is planned for 2011-09-27.

Multiple -and -or in PowerShell Where-Object statement

I found the solution here:

How to properly -filter multiple strings in a PowerShell copy script

You have to use -Include flag for Get-ChildItem

My Example:

$Location = "C:\user\files" 
$result = (Get-ChildItem $Location\* -Include *.png, *.gif, *.jpg)

Dont forget put "*" after path location.

Copy a file from one folder to another using vbscripting

Just posted my finished code for a similar project. It copies files of certain extensions in my code its pdf tif and tiff you can change them to whatever you want copied or delete the if statements if you only need 1 or 2 types. When a file is created or modified it gets the archive attribute this code also looks for that attribute and only copies it if it exists and then removes it after its copied so you dont copy unneeded files. It also has a log setup in it so that you will see a log of what time and day evetrything was transfered from the last time you ran the script. Hope it helps! the link is Error: Object Required; 'objDIR' Code: 800A01A8

What is a "callable"?

Callable is a type or class of "Build-in function or Method" with a method call

>>> type(callable)
<class 'builtin_function_or_method'>
>>>

Example: print is a callable object. With a build-in function __call__ When you invoke the print function, Python creates an object of type print and invokes its method __call__ passing the parameters if any.

>>> type(print)
<class 'builtin_function_or_method'>
>>> print.__call__(10)
10
>>> print(10)
10
>>>

Thank you. Regards, Maris

excel formula to subtract number of days from a date

Assuming the original date is in cell A1:

=DATE(YEAR(A1), MONTH(A1), DAY(A1)-180)

VBA to copy a file from one directory to another

One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):

  • My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
  • I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
  • Running the above code manually from a module worked fine.
  • Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
  • I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.

My solution will be to run the code (On timer event) from another hidden form that opens with the database.

System.out.println() shortcut on Intellij IDEA

If you want to know all the shortcut in intellij hit Ctrl + J. This shows all the shortcuts. For System.out.println() type sout and press Tab.

What is the functionality of setSoTimeout and how it works?

Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?

No, it means that if no data arrives within 2000ms a SocketTimeoutException will be thrown.

What does it mean timeout expire?

It means the 2000ms (in your case) elapses without any data arriving.

What is the option which must be enabled prior to blocking operation?

There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.

Infinite Timeout menas that the socket does't read anymore?

What a strange suggestion. It means that if no data ever arrives you will block in the read forever.

Convert SVG to image (JPEG, PNG, etc.) in the browser

There are several ways to convert SVG to PNG using the Canvg library.

In my case, I needed to get the PNG blob from inline SVG.

The library documentation provides an example (see OffscreenCanvas example).

But this method does not work at the moment in Firefox. Yes, you can enable the gfx.offscreencanvas.enabled option in the settings. But will every user on the site do this? :)

However, there is another way that will work in Firefox too.

const el = document.getElementById("some-svg"); //this is our inline SVG

var canvas = document.createElement('canvas'); //create a canvas for the SVG render
canvas.width = el.clientWidth; //set canvas sizes
canvas.height = el.clientHeight;

const svg = new XMLSerializer().serializeToString(el); //convert SVG to string

//render SVG inside canvas
const ctx = canvas.getContext('2d');
const v = await Canvg.fromString(ctx, svg);
await v.render();

let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));

For the last line thanks to this answer

Set background image according to screen resolution

Delete your "body background image code" then paste this code:

html { 
    background: url(../img/background.jpg) no-repeat center center fixed #000; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How to call a function in shell Scripting?

#!/bin/bash

process_install()
{
    commands... 
    commands... 
}

process_exit()
{
    commands... 
    commands... 
}


if [ "$choice" = "true" ] then
    process_install
else
    process_exit
fi

How do I use Notepad++ (or other) with msysgit?

Update 2010-2011:

zumalifeguard's solution (upvoted) is simpler than the original one, as it doesn't need anymore a shell wrapper script.

As I explain in "How can I set up an editor to work with Git on Windows?", I prefer a wrapper, as it is easier to try and switch editors, or change the path of one editor, without having to register said change with a git config again.
But that is just me.


Additional information: the following solution works with Cygwin, while the zuamlifeguard's solution does not.


Original answer.

The following:

C:\prog\git>git config --global core.editor C:/prog/git/npp.sh

C:/prog/git/npp.sh:
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"

does work. Those commands are interpreted as shell script, hence the idea to wrap any windows set of commands in a sh script.
(As Franky comments: "Remember to save your .sh file with Unix style line endings or receive mysterious error messages!")

More details on the SO question How can I set up an editor to work with Git on Windows?

Note the '-multiInst' option, for ensuring a new instance of notepad++ for each call from Git.

Note also that, if you are using Git on Cygwin (and want to use Notepad++ from Cygwin), then scphantm explains in "using Notepad++ for Git inside Cygwin" that you must be aware that:

git is passing it a cygwin path and npp doesn't know what to do with it

So the script in that case would be:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$(cygpath -w "$*")"

Multiple lines for readability:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar \
  -nosession -noPlugin "$(cygpath -w "$*")"

With "$(cygpath -w "$*")" being the important part here.

Val commented (and then deleted) that you should not use -notabbar option:

It makes no good to disable the tab during rebase, but makes a lot of harm to general Notepad usability since -notab becomes the default setting and you must Settings>Preferences>General>TabBar> Hide>uncheck every time you start notepad after rebase. This is hell. You recommended the hell.

So use rather:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession -noPlugin "$(cygpath -w "$*")"

That is:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession \
  -noPlugin "$(cygpath -w "$*")"

If you want to place the script 'npp.sh' in a path with spaces (as in 'c:\program files\...',), you have three options:

  • Either try to quote the path (single or double quotes), as in:

    git config --global core.editor 'C:/program files/git/npp.sh'
    
  • or try the shortname notation (not fool-proofed):

    git config --global core.editor C:/progra~1/git/npp.sh
    
  • or (my favorite) place 'npp.sh' in a directory part of your %PATH% environment variable. You would not have then to specify any path for the script.

    git config --global core.editor npp.sh
    
  • Steiny reports in the comments having to do:

    git config --global core.editor '"C:/Program Files (x86)/Git/scripts/npp.sh"'
    

How to detect if URL has changed after hash in JavaScript

window.addEventListener("beforeunload", function (e) {
    // do something
}, false);

How to click a href link using Selenium

Thi is your code :

Driver.findElement(By.xpath(//a[@href ='/docs/configuration']")).click();

You missed the Quotation mark

it should be as below

Driver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();

Hope this helps!

How to sum a variable by group

Since dplyr 1.0.0, the across() function could be used:

df %>%
 group_by(Category) %>%
 summarise(across(Frequency, sum))

  Category Frequency
  <chr>        <int>
1 First           30
2 Second           5
3 Third           34

If interested in multiple variables:

df %>%
 group_by(Category) %>%
 summarise(across(c(Frequency, Frequency2), sum))

  Category Frequency Frequency2
  <chr>        <int>      <int>
1 First           30         55
2 Second           5         29
3 Third           34        190

And the selection of variables using select helpers:

df %>%
 group_by(Category) %>%
 summarise(across(starts_with("Freq"), sum))

  Category Frequency Frequency2 Frequency3
  <chr>        <int>      <int>      <dbl>
1 First           30         55        110
2 Second           5         29         58
3 Third           34        190        380

Sample data:

df <- read.table(text = "Category Frequency Frequency2 Frequency3
                 1    First        10         10         20
                 2    First        15         30         60
                 3    First         5         15         30
                 4   Second         2          8         16
                 5    Third        14         70        140
                 6    Third        20        120        240
                 7   Second         3         21         42",
                 header = TRUE,
                 stringsAsFactors = FALSE)

Bootstrap: adding gaps between divs

The easiest way to do it is to add mb-5 to your classes. That is <div class='row mb-5'>.

NOTE:

  • mb varies betweeen 1 to 5
  • The Div MUST have the row class

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

In bootstrap, simply use mx-auto class along with navbar-brand.

How to get char from string by index?

I think this is more clear than describing it in words

s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'

Remove trailing zeros

how about this:

public static string TrimEnd(this decimal d)
    {
        string str = d.ToString();
        if (str.IndexOf(".") > 0)
        {
            str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "0+?$", " ");
            str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "[.]$", " ");
        }
        return str;
    }

Maximum length for MySQL type text

TINYTEXT 256 bytes
TEXT 65,535 bytes ~64kb
MEDIUMTEXT 16,777,215 bytes ~16MB
LONGTEXT 4,294,967,295 bytes ~4GB

TINYTEXT is a string data type that can store up to to 255 characters.

TEXT is a string data type that can store up to 65,535 characters. TEXT is commonly used for brief articles.

LONGTEXT is a string data type with a maximum length of 4,294,967,295 characters. Use LONGTEXT if you need to store large text, such as a chapter of a novel.

How to stop the task scheduled in java.util.Timer class

timer.cancel();  //Terminates this timer,discarding any currently scheduled tasks.

timer.purge();   // Removes all cancelled tasks from this timer's task queue.

python location on mac osx

installed with 'brew install python3', found it here enter image description here

How to open local files in Swagger-UI

What works, is to enter a relative path or an absolute without the file://-protocol:

  • ../my.json leads to file:///D:/swagger-ui/dist/index.html/../my.json and works
  • /D:/swagger-ui/dist/my.json leads to file:///D:/swagger-ui/dist/my.json and works

HINT

This answer works with Firefox on Win7. For Chrome-Browser, see comments below:

How do you check if a JavaScript Object is a DOM Object?

In Firefox, you can use the instanceof Node. That Node is defined in DOM1.

But that is not that easy in IE.

  1. "instanceof ActiveXObject" only can tell that it is a native object.
  2. "typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.

You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)

Programmatically Creating UILabel

In Swift -

var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)

curl Failed to connect to localhost port 80

I also had problem with refused connection on port 80. I didn't use localhost.

curl --data-binary "@/textfile.txt" "http://www.myserver.com/123.php"

Problem was that I had umlauts äåö in my textfile.txt.

Android studio Gradle build speed up

The dev are working on it. Like I posted in this answer the fastest solution right now is to use gradle from the command line and you should switch to binary libs for all modules you do not develop. On g+ there is a discussion with the developers about it.

How to install mcrypt extension in xampp

First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows

Then, you should copy php_mcrypt.dll to ../xampp/php/ext/ and enable the extension by adding extension=mcrypt to your xampp/php/php.ini file.

How can I remove the search bar and footer added by the jQuery DataTables plugin?

if you are using themeroller:

.dataTables_wrapper .fg-toolbar { display: none; }

How do I convert an NSString value to NSData?

NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];

How do I generate a list with a specified increment step?

The following example shows benchmarks for a few alternatives.

library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
##                     test replications elapsed  relative user.self sys.self
## 2          (0:5e+05) * 2          100   0.587  3.536145     0.344    0.244
## 1     seq(0, 1e6, by = 2)         100   2.760 16.626506     1.832    0.900
## 3 seq.int(0, 1e6, by = 2)         100   0.166  1.000000     0.056    0.096

In this case, seq.int is the fastest method and seq the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq as the most readable solution.

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

How do I change a tab background color when using TabLayout?

You can try this:

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabBackground">@drawable/background</item>
</style>

In your background xml file:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@color/white" />
    <item android:drawable="@color/black" />
</selector>

Open S3 object as a string with Boto3

Python3 + Using boto3 API approach.

By using S3.Client.download_fileobj API and Python file-like object, S3 Object content can be retrieved to memory.

Since the retrieved content is bytes, in order to convert to str, it need to be decoded.

import io
import boto3

client = boto3.client('s3')
bytes_buffer = io.BytesIO()
client.download_fileobj(Bucket=bucket_name, Key=object_key, Fileobj=bytes_buffer)
byte_value = bytes_buffer.getvalue()
str_value = byte_value.decode() #python3, default decoding is utf-8

Why is char[] preferred over String for passwords?

Some people believe that you have to overwrite the memory used to store the password once you no longer need it. This reduces the time window an attacker has to read the password from your system and completely ignores the fact that the attacker already needs enough access to hijack the JVM memory to do this. An attacker with that much access can catch your key events making this completely useless (AFAIK, so please correct me if I am wrong).

Update

Thanks to the comments I have to update my answer. Apparently there are two cases where this can add a (very) minor security improvement as it reduces the time a password could land on the hard drive. Still I think it's overkill for most use cases.

  • Your target system may be badly configured or you have to assume it is and you have to be paranoid about core dumps (can be valid if the systems are not managed by an administrator).
  • Your software has to be overly paranoid to prevent data leaks with the attacker gaining access to the hardware - using things like TrueCrypt (discontinued), VeraCrypt, or CipherShed.

If possible, disabling core dumps and the swap file would take care of both problems. However, they would require administrator rights and may reduce functionality (less memory to use) and pulling RAM from a running system would still be a valid concern.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I also tried http://www.eclipse.org/cdt/ in Ubuntu 12.04.2 LTS and works fine!

  1. First, I downloaded it from www.eclipse.org/downloads/, choosing Eclipse IDE for C/C++ Developers.
  2. I save the file somewhere, let´s say into my home directory. Open a console or terminal, and type:

    >>cd ~; tar xvzf eclipse*.tar.gz;

  3. Remember for having Eclipse running in Linux, it is required a JVM, so download a jdk file e.g jdk-7u17-linux-i586.rpm (I cann´t post the link due to my low reputation) ... anyway

  4. Install the .rpm file following http://www.wikihow.com/Install-Java-on-Linux

  5. Find the path to the Java installation, by typing:

    >>which java

  6. I got /usr/bin/java. To start up Eclipse, type:

    >>cd ~/eclipse; ./eclipse -vm /usr/bin/java

Also, once everything is installed, in the home directory, you can double-click the executable icon called eclipse, and then you´ll have it!. In case you like an icon, create a .desktop file in /usr/share/applications:

>>sudo gedit /usr/share/applications/eclipse.desktop

The .desktop file content is as follows:

[Desktop Entry]  
Name=Eclipse  
Type=Application  
Exec="This is the path of the eclipse executable on your machine"  
Terminal=false 
Icon="This is the path of the icon.xpm file on your machine"  
Comment=Integrated Development Environment  
NoDisplay=false  
Categories=Development;IDE  
Name[en]=eclipse.desktop  

Best luck!

Adding 1 hour to time variable

Simple and smart solution:

date("H:i:s", time()+3600);

How to set a default value with Html.TextBoxFor?

This should work for MVC3 & MVC4

 @Html.TextBoxFor(m => m.Age, new { @Value = "12" }) 

If you want it to be a hidden field

 @Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" }) 

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

I have added in Application Class

@Bean
@ConfigurationProperties("app.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

application.properties I have added

app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.pool-size=30

More details Configure a Custom DataSource

How to pass variables from one php page to another without form?

You can use Ajax calls or $_GET["String"]; Method

ModelState.IsValid == false, why?

If you remove the check for the ModelsState.IsValid and let it error, if you copy this line ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors and paste it in the watch section in Visual Studio it will give you exactly what the error is. Saves a lot of time checking where the error is.

How do I configure HikariCP in my Spring Boot app in my application.properties files?

Here is the good news. HikariCP is the default connection pool now with Spring Boot 2.0.0.

Spring Boot 2.0.0 Release Notes

The default database pooling technology in Spring Boot 2.0 has been switched from Tomcat Pool to HikariCP. We’ve found that Hakari offers superior performance, and many of our users prefer it over Tomcat Pool.

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

<input type="text" id="firstname" placeholder="First Name"

Note: You can change the placeholder, id and type value to "email" or whatever suits your need.

More details by W3Schools at:http://www.w3schools.com/tags/att_input_placeholder.asp

But by far the best solutions are by Floern and Vivek Mhatre ( edited by j0k )

Python: avoid new line with print command

If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try

from __future__ import print_function

print("abcd", end='')
print("efg")

results in

abcdefg

For those using 3.x, this is already built-in.

Javascript Get Values from Multiple Select Option Box

Also, change this:

    SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;

to

    SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;

The reason is that for the first time the variable SelBranchVal will be empty

Can attributes be added dynamically in C#?

Why do you need to? Attributes give extra information for reflection, but if you externally know which properties you want you don't need them.

You could store meta data externally relatively easily in a database or resource file.

CSS-moving text from left to right

You could simply use CSS animated text generator. There are pre-created templates already

Formatting doubles for output in C#

i tried to reproduce your findings, but when I watched 'i' in the debugger it showed up as '6.8999999999999995' not as '6.89999999999999946709' as you wrote in the question. Can you provide steps to reproduce what you saw?

To see what the debugger shows you, you can use a DoubleConverter as in the following line of code:

Console.WriteLine(TypeDescriptor.GetConverter(i).ConvertTo(i, typeof(string)));

Hope this helps!

Edit: I guess I'm more tired than I thought, of course this is the same as formatting to the roundtrip value (as mentioned before).

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How do I run a spring boot executable jar in a Production environment?

If you are using gradle you can just add this to your build.gradle

springBoot {
    executable = true
}

You can then run your application by typing ./your-app.jar

Also, you can find a complete guide here to set up your app as a service

56.1.1 Installation as an init.d service (System V)

http://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

cheers

how to get the value of css style using jquery

Yes, you're right. With the css() method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/

But if you want to get its position you can check offset() and position() methods to get it's position.

How to exclude property from Json Serialization

If you are using System.Text.Json then you can use [JsonIgnore].
FQ: System.Text.Json.Serialization.JsonIgnoreAttribute

Official Microsoft Docs: JsonIgnoreAttribute

As stated here:

The library is built-in as part of the .NET Core 3.0 shared framework.
For other target frameworks, install the System.Text.Json NuGet package. The package supports:

  • .NET Standard 2.0 and later versions
  • .NET Framework 4.6.1 and later versions
  • .NET Core 2.0, 2.1, and 2.2

How to Change Margin of TextView

This one is tricky problem, i set margin to textview in a row of a table layout. see the below:

TableLayout tl = new TableLayout(this);
tl.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

TableRow tr = new TableRow(this);        
tr.setBackgroundResource(R.color.rowColor);

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(4, 4, 4, 4);

TextView tv = new TextView(this);
tv.setBackgroundResource(R.color.textviewColor);
tv.setText("hello");
tr.addView(tv, params);

TextView tv2 = new TextView(this);
tv2.setBackgroundResource(R.color.textviewColor);
tv2.setText("hi");
tr.addView(tv2, params);

tl.addView(tr);
setContentView(tl);

the class needed to import for LayoutParams for use in a table row is :

import android.widget.**TableRow**.LayoutParams;

important to note that i added the class for table row. similarly many other classes are available to use LayoutParams like:

import android.widget.**RelativeLayout**.LayoutParams;

import android.widget.LinearLayout.LayoutParams;

so use accordingly.

Check if Python Package is installed

If you mean a python script, just do something like this:

Python 3.3+ use sys.modules and find_spec:

import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

if name in sys.modules:
    print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
    # If you choose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    print(f"{name!r} has been imported")
else:
    print(f"can't find the {name!r} module")

Python 3:

try:
    import mymodule
except ImportError as e:
    pass  # module doesn't exist, deal with it.

Python 2:

try:
    import mymodule
except ImportError, e:
    pass  # module doesn't exist, deal with it.

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

First, since length always returns a non-negative number,

if ( length $name )

and

if ( length $name > 0 )

are equivalent.

If you are OK with replacing an undefined value with an empty string, you can use Perl 5.10's //= operator which assigns the RHS to the LHS unless the LHS is defined:

#!/usr/bin/perl

use feature qw( say );
use strict; use warnings;

my $name;

say 'nonempty' if length($name //= '');
say "'$name'";

Note the absence of warnings about an uninitialized variable as $name is assigned the empty string if it is undefined.

However, if you do not want to depend on 5.10 being installed, use the functions provided by Scalar::MoreUtils. For example, the above can be written as:

#!/usr/bin/perl

use strict; use warnings;

use Scalar::MoreUtils qw( define );

my $name;

print "nonempty\n" if length($name = define $name);
print "'$name'\n";

If you don't want to clobber $name, use default.

GitLab git user password

After adding the new SSH Key in GitLab, check if you have "git" group included in SSHD AllowGroups (for Debian /etc/ssh/sshd_config). If not, add it and restart sshd (systemctl restart ssh).

Test it with ssh -vT [email protected] as suggested above.

Mask output of `The following objects are masked from....:` after calling attach() function

You actually don't need to use the attach at all. I had the same problem and it was resolved by removing the attach statement.

bootstrap popover not showing on top of all elements

Many years later, but like me, others may search for this. All updates taking into consideration, all this can be solved with correct initialization options, in JavaScript.

$('.tip').tooltip({
    boundary: 'viewport',
    placement: 'top',
    container:'body',
    sanitize: true,
    appendToBody: true
});

Those settings solved all may issues. I had tooltips flickering, showing corectly only for half of the items on page, jumping from top to left continously, all kinds of wierdness. But with those settings everything is solved. Hope it help anyone looking.

Popup window in winform c#

i am using this method.

add a from that you want to pop up, add all controls you need. in the code you can handle the user input and return result to the caller. for pop up the form just create a new instance of the form and show method.

/* create new form instance. i am overriding constructor to allow the caller form to set the form header */ 
var t = new TextPrompt("Insert your message and click Send button");
// pop up the form
t.Show();
if (t.DialogResult == System.Windows.Forms.DialogResult.OK)
{ 
  MessageBox.Show("RTP", "Message sent to user"); 
}

How to get back to the latest commit after checking out a previous commit?

git reflog //find the hash of the commit that you want to checkout
git checkout <commit number>>

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

A solution that correctly handles all file names (including newlines) and extracts into a directory that is at the same location as the file, just with the extension removed:

find . -iname '*.zip' -exec sh -c 'unzip -o -d "${0%.*}" "$0"' '{}' ';'

Note that you can easily make it handle more file types (such as .jar) by adding them using -o, e.g.:

find . '(' -iname '*.zip' -o -iname '*.jar' ')' -exec ...

Python Script Uploading files via FTP

Try this:

#!/usr/bin/env python

import os
import paramiko 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

How to Set Active Tab in jQuery Ui

Inside your function for the click action use

$( "#tabs" ).tabs({ active: # });

Where # is replaced by the tab index you want to select.

Edit: change from selected to active, selected is deprecated

add created_at and updated_at fields to mongoose schemas

In your model schema, just add an attribute timestamps and assign value true to it as shown:-

var ItemSchema = new Schema({
   name :  { type: String, required: true, trim: true },
},{timestamps : true}
);

Unable to ping vmware guest from another vmware guest

There are several related solutions available on the internet, but it all depends on the configuration of the machine and the firewall rules.

For me below solution is worked:

  • Disabled the VMware Network Adapter VMNet8
  • Removed the network from the VM
  • Enabled the VMware Network Adapter VMNet8
  • Re-added the Network to VM, and set it to NAT
  • Restarted the machine

Check this blog post for detailed solution.

jQuery: Handle fallback for failed AJAX Request

Yes, it's built in to jQuery. See the docs at jquery documentation.

ajaxError may be what you want.

dlib installation on Windows 10

Simple and 100% working trick

(Make sure you install cmake)

My Anaconda python ver : 3.6.8 (64 bit) | OS :Windows 10

python -m pip install https://files.pythonhosted.org/packages/0e/ce/f8a3cff33ac03a8219768f0694c5d703c8e037e6aba2e865f9bae22ed63c/dlib-19.8.1-cp36-cp36m-win_amd64.whl#sha256=794994fa2c54e7776659fddb148363a5556468a6d5d46be8dad311722d54bfcf

enter image description here

Styles.Render in MVC4

A bit late to the party. But it seems like no one has mentioned
bundling & minification of StyleBundle, so..

@Styles.Render("~/Content/css") 

calls in Application_Start():

BundleConfig.RegisterBundles(BundleTable.Bundles);            

which in turn calls

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new StyleBundle("~/Content/css").Include(
              "~/Content/bootstrap.css",
              "~/Content/Site.css"));
}

RegisterBundles() effectively combines & minifies bootstrap.css & Site.css
into a single file,

<link href="/Content/css?v=omEnf6XKhDfHpwdllcEwzSIFQajQQLOQweh_aX9VVWY1" rel="stylesheet">

But..

<system.web>
  <compilation debug="false" targetFramework="4.6.1" />
</system.web>

only when debug is set to false in Web.config.
Otherwise bootstrap.css & Site.css will be served individually.
Not bundled, nor minified:

<link href="/Content/bootstrap.css" rel="stylesheet">
<link href="/Content/Site.css" rel="stylesheet">

not-null property references a null or transient value

Make that variable as transient.Your problem will get solved..

@Column(name="emp_name", nullable=false, length=30)
    private transient String empName;

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

This is what helped me: Adding specific android platform

What should be done is the following... In my case it was cordova but the same is relevant for ionic, phonegap and other frameworks like these:

  1. list all platforms installed for your project: cordova platform list. You'll see something like this:

enter image description here

  1. remove the android platform: cordova platform remove android.

  2. then add the specific android platform: cordova platform add [email protected].

Good luck! :)

What's the safest way to iterate through the keys of a Perl hash?

One thing you should be aware of when using each is that it has the side effect of adding "state" to your hash (the hash has to remember what the "next" key is). When using code like the snippets posted above, which iterate over the whole hash in one go, this is usually not a problem. However, you will run into hard to track down problems (I speak from experience ;), when using each together with statements like last or return to exit from the while ... each loop before you have processed all keys.

In this case, the hash will remember which keys it has already returned, and when you use each on it the next time (maybe in a totaly unrelated piece of code), it will continue at this position.

Example:

my %hash = ( foo => 1, bar => 2, baz => 3, quux => 4 );

# find key 'baz'
while ( my ($k, $v) = each %hash ) {
    print "found key $k\n";
    last if $k eq 'baz'; # found it!
}

# later ...

print "the hash contains:\n";

# iterate over all keys:
while ( my ($k, $v) = each %hash ) {
    print "$k => $v\n";
}

This prints:

found key bar
found key baz
the hash contains:
quux => 4
foo => 1

What happened to keys "bar" and baz"? They're still there, but the second each starts where the first one left off, and stops when it reaches the end of the hash, so we never see them in the second loop.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I'm playing right now with Git 1.6.5, and I can't replicate your setup:

Administrator@WS2008 /k/git
$ ll ~/.ssh
total 8
drwxr-xr-x    2 Administ Administ     4096 Oct 13 22:04 ./
drwxr-xr-x    6 Administ Administ     4096 Oct  6 21:36 ../
-rw-r--r--    1 Administ Administ        0 Oct 13 22:04 c.txt
-rw-r--r--    1 Administ Administ      403 Sep 30 22:36 config_disabled
-rw-r--r--    1 Administ Administ      887 Aug 30 16:33 id_rsa
-rw-r--r--    1 Administ Administ      226 Aug 30 16:34 id_rsa.pub
-rw-r--r--    1 Administ Administ      843 Aug 30 16:32 id_rsa_putty.ppk
-rw-r--r--    1 Administ Administ      294 Aug 30 16:33 id_rsa_putty.pub
-rw-r--r--    1 Administ Administ     1626 Sep 30 22:49 known_hosts

Administrator@WS2008 /k/git
$ git clone [email protected]:alexandrul/gitbook.git
Initialized empty Git repository in k:/git/gitbook/.git/
remote: Counting objects: 1152, done.
remote: Compressing objects: 100% (625/625), done.
remote: Total 1152 (delta 438), reused 1056 (delta 383)s
Receiving objects: 100% (1152/1152), 1.31 MiB | 78 KiB/s, done.
Resolving deltas: 100% (438/438), done.

Administrator@WS2008 /k/git
$ ssh [email protected]
ERROR: Hi alexandrul! You've successfully authenticated, but GitHub does not pro
vide shell access
Connection to github.com closed.

$ ssh -v
OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007

chmod doesn't modify file permissions for my keys either.

Environment:

  • Windows Server 2008 SP2 on NTFS
  • user: administrator
  • environment vars:
    • PLINK_PROTOCOL=ssh
    • HOME=/c/profiles/home

Update: Git 1.6.5.1 works as well.

MySQL - count total number of rows in php

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  echo "number of rows: ",$rowcount;
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($con);
?>

it is best way (I think) to get the number of special row in mysql with php.

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

Including external jar-files in a new jar-file build with Ant

With the helpful advice from people who have answered here I started digging into One-Jar. After some dead-ends (and some results that were exactly like my previous results I managed to get it working. For other peoples reference I'm listing the build.xml that worked for me.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="build" name="<INSERT_PROJECT_NAME_HERE>">
    <property environment="env"/>
    <property name="debuglevel" value="source,lines,vars"/>
    <property name="target" value="1.6"/>
    <property name="source" value="1.6"/>

    <property name="one-jar.dist.dir" value="../onejar"/>
    <import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />

    <property name="src.dir"          value="src"/>
    <property name="bin.dir"          value="bin"/>
    <property name="build.dir"        value="build"/>
    <property name="classes.dir"      value="${build.dir}/classes"/>
    <property name="jar.target.dir"   value="${build.dir}/jars"/>
    <property name="external.lib.dir" value="../jars"/>
    <property name="final.jar"        value="${bin.dir}/<INSERT_NAME_OF_FINAL_JAR_HERE>"/>

    <property name="main.class"       value="<INSERT_MAIN_CLASS_HERE>"/>

    <path id="project.classpath">
        <fileset dir="${external.lib.dir}">
            <include name="*.jar"/>
        </fileset>
    </path>

    <target name="init">
        <mkdir dir="${bin.dir}"/>
        <mkdir dir="${build.dir}"/>
        <mkdir dir="${classes.dir}"/>
        <mkdir dir="${jar.target.dir}"/>
        <copy includeemptydirs="false" todir="${classes.dir}">
            <fileset dir="${src.dir}">
                <exclude name="**/*.launch"/>
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
    </target>

    <target name="clean">
        <delete dir="${build.dir}"/>
        <delete dir="${bin.dir}"/>
    </target>

    <target name="cleanall" depends="clean"/>

    <target name="build" depends="init">
        <echo message="${ant.project.name}: ${ant.file}"/>
        <javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
            <src path="${src.dir}"/>
            <classpath refid="project.classpath"/>   
        </javac>
    </target>

    <target name="build-jar" depends="build">
        <delete file="${final.jar}" />
        <one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
            <main>
                <fileset dir="${classes.dir}"/>
            </main>
            <lib>
                <fileset dir="${external.lib.dir}" />
            </lib>
        </one-jar>
    </target>
</project>

I hope someone else can benefit from this.

Spring profiles and testing

Can I recommend doing it this way, define your test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    TestPreperationExecutionListener.class
    })
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {

  @Test
  public void testContext(){

  }

  @Configuration
  @PropertySource("classpath:/myprops.properties")
  @ImportResource({"classpath:context.xml" })
  public static class MyContextConfiguration{

  }
}

with the following content in myprops.properties file:

spring.profiles.active=localtest

With this your second properties file should get resolved:

META-INF/spring/config_${spring.profiles.active}.properties

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

CLOCK_REALTIME is affected by NTP, and can move forwards and backwards. CLOCK_MONOTONIC is not, and advances at one tick per tick.

Array versus linked-list

It's really a matter of efficiency, the overhead to insert, remove or move (where you are not simply swapping) elements inside a linked list is minimal, i.e. the operation itself is O(1), verses O(n) for an array. This can make a significant difference if you are operating heavily on a list of data. You chose your data-types based on how you will be operating on them and choose the most efficient for the algorithm you are using.

How do I get the IP address into a batch-file variable?

try something like this

echo "yours ip addresses are:"
ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1

linux like systems

Replace spaces with dashes and make all letters lower-case

You can also use split and join:

"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games

Defining a variable with or without export

Others have answered that export makes the variable available to subshells, and that is correct but merely a side effect. When you export a variable, it puts that variable in the environment of the current shell (ie the shell calls putenv(3) or setenv(3)).
The environment of a process is inherited across exec, making the variable visible in subshells.

Edit (with 5 year's perspective): this is a silly answer. The purpose of 'export' is to make variables "be in the environment of subsequently executed commands", whether those commands be subshells or subprocesses. A naive implementation would be to simply put the variable in the environment of the shell, but this would make it impossible to implement export -p.

How to send email to multiple recipients using python smtplib?

You need to understand the difference between the visible address of an email, and the delivery.

msg["To"] is essentially what is printed on the letter. It doesn't actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email to.

The actual delivery however can work quite different. So you can drop the email (or a copy) into the post box of someone completely different.

There are various reasons for this. For example forwarding. The To: header field doesn't change on forwarding, however the email is dropped into a different mailbox.

The smtp.sendmail command now takes care of the actual delivery. email.Message is the contents of the letter only, not the delivery.

In low-level SMTP, you need to give the receipients one-by-one, which is why a list of adresses (not including names!) is the sensible API.

For the header, it can also contain for example the name, e.g. To: First Last <[email protected]>, Other User <[email protected]>. Your code example therefore is not recommended, as it will fail delivering this mail, since just by splitting it on , you still not not have the valid adresses!

The type WebMvcConfigurerAdapter is deprecated

I have been working on Swagger equivalent documentation library called Springfox nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer has been implemented by class WebMvcConfigurationSupport class which we can directly extend.

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConfig extends WebMvcConfigurationSupport { }

And this is how I have used it for setting my resource handling mechanism as follows -

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

PHP case-insensitive in_array function

function in_arrayi($needle, $haystack) {
    return in_array(strtolower($needle), array_map('strtolower', $haystack));
}

Source: php.net in_array manual page.

Should switch statements always contain a default clause?

Atleast it is not mandatory in Java. According to JLS, it says atmost one default case can be present. Which means no default case is acceptable . It at times also depends on the context that you are using the switch statement. For example in Java, the following switch block does not require default case

private static void switch1(String name) {
    switch (name) {
    case "Monday":
        System.out.println("Monday");
        break;
    case "Tuesday":
        System.out.println("Tuesday");
        break;
    }
}

But in the following method which expects to return a String, default case comes handy to avoid compilation errors

    private static String switch2(String name) {
    switch (name) {
    case "Monday":
        System.out.println("Monday");
        return name;

    case "Tuesday":
        System.out.println("Tuesday");
        return name;

    default:
        return name;
    }
}

though you can avoid compilation error for the above method without having default case by just having a return statement at the end, but providing default case makes it more readable.

Can I call an overloaded constructor from another constructor of the same class in C#?

EDIT: According to the comments on the original post this is a C# question.

Short answer: yes, using the this keyword.

Long answer: yes, using the this keyword, and here's an example.

class MyClass
{
   private object someData;

   public MyClass(object data)
   {
      this.someData = data;
   }

   public MyClass() : this(new object())
   {
      // Calls the previous constructor with a new object, 
      // setting someData to that object
   }
}

Looping each row in datagridview

I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.

foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
    File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}

background-image: url("images/plaid.jpg") no-repeat; wont show up

You may debug using two ways:

  1. Press CTRL+U to view page Source . Press CTRL+F to find "mystyles.css" in source . click on mystyles.css link and check if it is not showing "404 not found".

  2. You can INSPECT ELEMENT IN FIRBUG and set path to Image ,Set Image height and width because sometimes image doesnt show up.

Hope this may works !!.

C#: How to add subitems in ListView

Suppose you have a List Collection containing many items to show in a ListView, take the following example that iterates through the List Collection:

foreach (Inspection inspection in anInspector.getInspections())
  {
    ListViewItem item = new ListViewItem();
    item.Text=anInspector.getInspectorName().ToString();
    item.SubItems.Add(inspection.getInspectionDate().ToShortDateString());
    item.SubItems.Add(inspection.getHouse().getAddress().ToString());
    item.SubItems.Add(inspection.getHouse().getValue().ToString("C"));
    listView1.Items.Add(item);
  }

That code produces the following output in the ListView (of course depending how many items you have in the List Collection):

Basically the first column is a listviewitem containing many subitems (other columns). It may seem strange but listview is very flexible, you could even build a windows-like file explorer with it!

Serving static web resources in Spring Boot & Spring Security application

If you are using webjars. You need to add this in your configure method: http.authorizeRequests().antMatchers("/webjars/**").permitAll();

Make sure this is the first statement. For example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
         http.formLogin()
         .loginPage("/login")
         .failureUrl("/login?error")
         .usernameParameter("email")
         .permitAll()
         .and()
         .logout()
         .logoutUrl("/logout")
         .deleteCookies("remember-me")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe();
    }

You will also need to have this in order to have webjars enabled:

@Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        ...
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        ...
    }

How to send multiple data fields via Ajax?

Here's what works for me after 2 days of head-scratching; why I couldn't get the AJaX 'data' setting to send two key/values (including a variable containing raw image data) was a mystery, but that seems to be what the jQuery.param() function was written for;

create a params array with your variables, without quotes:

var params = { key_name1: var_1, key_name2: var_2  }; // etc.

var ser_data = jQuery.param( params );   // arbitrary variable name

Use variable ser_data as your data value;

      $.ajax({
       type: 'POST',
       url: '../php_handler_url.php',
       data: ser_data,
    }).success(function(response) {
       alert(response);
    });

Documentation is here: https://api.jquery.com/jQuery.param/

Hope that helps!

IntelliJ Organize Imports

Shortcut for the Mac: (ctrl + opt + o)

What are good examples of genetic algorithms/genetic programming solutions?

Football Tipping. I built a GA system to predict the week to week outcome of games in the AFL (Aussie Rules Football).

A few years ago I got bored of the standard work football pool, everybody was just going online and taking the picks from some pundit in the press. So, I figured it couldn't be too hard to beat a bunch of broadcast journalism majors, right? My first thought was to take the results from Massey Ratings and then reveal at the end of the season my strategy after winning fame and glory. However, for reasons I've never discovered Massey does not track AFL. The cynic in me believes it is because the outcome of each AFL game has basically become random chance, but my complaints of recent rule changes belong in a different forum.

The system basically considered offensive strength, defensive strength, home field advantage, week to week improvement (or lack thereof) and velocity of changes to each of these. This created a set of polynomial equations for each team over the season. The winner and score for each match for a given date could be computed. The goal was to find the set of coefficients that most closely matched the outcome of all past games and use that set to predict the upcoming weeks game.

In practice, the system would find solutions that accurately predicted over 90% of past game outcomes. It would then successfully pick about 60-80% of games for the upcoming week (that is the week not in the training set).

The result: just above middle of the pack. No major cash prize nor a system that I could use to beat Vegas. It was fun though.

I built everything from scratch, no framework used.

Convert date to day name e.g. Mon, Tue, Wed

echo date('D', strtotime($date));
echo date('l', strtotime($date));

Result

Tue
Tuesday

How can a Java program get its own process ID?

I am adding this, in addition to other solutions.

with Java 10, to get process id

final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
final long pid = runtime.getPid();
out.println("Process ID is '" + pid);

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Cell Style Alignment on a range

For SpreadSheetGear users (a C# framework for interacting easier with spreadsheets) try this:

workbook.Worksheets[0].Cells["B1:B4"].HorizontalAlignment = HAlign.Center;. This will align all the cells in your sheet from B1 to B4 (column 2- row 1 through 4).

Disable form auto submit on button click

<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!

$('form button').on("click",function(e){
    e.preventDefault();
});

How can I calculate the number of years between two dates?

let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)

Initializing a static std::map<int, int> in C++

If you are stuck with C++98 and don't want to use boost, here there is the solution I use when I need to initialize a static map:

typedef std::pair< int, char > elemPair_t;
elemPair_t elemPairs[] = 
{
    elemPair_t( 1, 'a'), 
    elemPair_t( 3, 'b' ), 
    elemPair_t( 5, 'c' ), 
    elemPair_t( 7, 'd' )
};

const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );

std::string length() and size() member functions

Ruby's just the same, btw, offering both #length and #size as synonyms for the number of items in arrays and hashes (C++ only does it for strings).

Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).

Making RGB color in Xcode

You already got the right answer, but if you dislike the UIColor interface like me, you can do this:

#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];

UIColor+Helper.h:

#import <UIKit/UIKit.h>

@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end

UIColor+Helper.m:

#import "UIColor+Helper.h"

@implementation UIColor (Helper)

+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
    return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
                           green:((color >> 16) & 0xFF) / 255.0f
                            blue:((color >> 8) & 0xFF) / 255.0f
                           alpha:((color) & 0xFF) / 255.0f];
}

@end

Get file name from a file location in Java

new File(absolutePath).getName();

Get decimal portion of a number with JavaScript

Math functions are faster, but always returns not native expected values. Easiest way that i found is

(3.2+'').replace(/^[-\d]+\./, '')

How can I pass a member function where a free function is expected?

@Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:

#include <functional>
using namespace std::placeholders;

void function1(std::function<void(int, int)> fun)
{
    fun(1, 1);
}

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

   aClass a;
   auto fp = std::bind(&aClass::test, a, _1, _2);
   function1(fp);

   return 0;
}

Variable not accessible when initialized outside function

Declare systemStatus in an outer scope and assign it in an onload handler.

systemStatus = null;

function onloadHandler(evt) {
    systemStatus = document.getElementById("....");
}

Or if you don't want the onload handler, put your script tag at the bottom of your HTML.